导包
java"><dependency><groupId>javax.mail</groupId><artifactId>mail</artifactId><version>1.4.7</version>
</dependency>
内容
java">调用
EmilUtil.sendEmail("xxxx@163.com",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() {@Overrideprotected 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.comport: 465username: xxx@aliyun.compassword: xxxx@#123465