说明
通过smtp实现邮件发送功能
引入pom.xml
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
源码
/**
* 发送邮件
* @param username 发送者账号
* @param password 发送者账号的密码
* @param host 邮件服务器地址
* @param port 邮件服务器端口
* @param ssl 是否使用ssl
* @param toUsername 接收者账号
* @param subject 邮件主题
* @param body 邮件内容
* @param filePath 附件路径
*/
public static void sendEmail(String username, String password, String host, String port, String ssl,String toUsername, String subject, String body,String filePath) {
log.info("发送邮件中...");
// 设置邮件服务器属性
Properties properties = System.getProperties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", ssl);
if("true".equals(ssl)) {
properties.put("mail.smtp.socketFactory.port", port);
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
}
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUsername));
message.setSubject(subject);
//有附件的情况下
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
//邮件内容
contentPart.setContent(body, "text/html;charset=utf-8");
multipart.addBodyPart(contentPart);
//邮件附件部分
if (org.apache.commons.lang3.StringUtils.isNotBlank(filePath)) {
String[] filePathArr=filePath.split(",");
for (String path: filePathArr) {
//判断文件是否存在,如不存在则不加入附件
if(new File(path).exists()){
//将文件设置为附件
BodyPart attachPart = new MimeBodyPart();
//附件地址
FileDataSource fileDataSource = new FileDataSource(path);
attachPart.setDataHandler(new DataHandler(fileDataSource));
attachPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
multipart.addBodyPart(attachPart);
}
}
}
message.setContent(multipart);
//没有附件
//message.setText(body);
Transport.send(message);
log.info("邮件发送成功!");
} catch (MessagingException | UnsupportedEncodingException e) {
log.error("邮件发送失败!", e);
}
}
标签:String,实现,param,发送,mail,new,properties,邮件
From: https://blog.csdn.net/weixin_46836162/article/details/140094787