导包
java
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
内容
java
调用
EmilUtil.sendEmail("[email protected]",
host,
username,
password,
port,
excelFile,
"主题",
content);
工具类
java
package com.ruoyi.common.utils.emil;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.security.Security;
import java.util.Map;
import java.util.Properties;
public class EmilUtil {
public static void sendEmail(String toEmail, String host, String username, String password,String port, File file, String bt, String contentXML) {
try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
//设置端口
props.setProperty("mail.smtp.port", port);
//启用调试
props.setProperty("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.port", port);
props.setProperty("mail.smtp.auth", "true");
//建立邮件会话
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
//建立邮件对象
MimeMessage message = new MimeMessage(session);
//设置邮件的发件人、收件人、主题
//发件人账号
message.setFrom(new InternetAddress(username));
//收件人账号
message.setRecipients(Message.RecipientType.TO, toEmail);
//邮件标题
message.setSubject(bt);
//内容
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
//邮件内容
contentPart.setContent(contentXML, "text/html;charset=utf-8");
multipart.addBodyPart(contentPart);
message.setContent(multipart);
//附件
// 创建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
message.saveChanges();
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
配置
java
//注意阿里邮箱设置设置第三方权限验证则无法验证通过
mail:
host: smtp.qiye.aliyun.com
port: 465
username: [email protected]
password: xxxx@#123465