//pom.xml
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/>
</parent>
<repositories>
<repository>
<id>maven-ali</id>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>aliyun-plugin</id>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.time.LocalDate;
import java.util.Date;
import java.util.Properties;
@Service
@Slf4j
public class MailService {
public String from = "[email protected]";
public String password = "TXzUeNDAUhYGjxSw";// 登录密码
public String protocol = "smtp";// 协议
public String port = "465";// 端口
public String host = "smtp.exmail.qq.com";// 服务器地址
private String theme = "通知";
//初始化参数
public Session initProperties() {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", protocol);
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", port);
// 使用smtp身份验证
properties.put("mail.smtp.auth", "true");
// 开启安全协议,使用SSL,企业邮箱必需
MailSSLSocketFactory mailSSLSocketFactory = null;
try {
mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
properties.put("mail.smtp.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.socketFactory.port", port);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
// session.setDebug(true);
return session;
}
public void email(String emailTo, String title, String content, String[] fileNames) {
try {
Session session = initProperties();
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(from, from));// 发件人,可以设置发件人的别名
// 收件人,多人接收,emailTo 逗号分隔
InternetAddress[] internetAddressTo = InternetAddress.parse(emailTo);
mimeMessage.setRecipients(Message.RecipientType.TO, internetAddressTo);
// 主题
if (StringUtils.isEmpty(title)){
mimeMessage.setSubject(theme);
}else{
mimeMessage.setSubject(title);
}
// 时间
mimeMessage.setSentDate(new Date());
// 容器类 附件
MimeMultipart mimeMultipart = new MimeMultipart();
// 可以包装文本,图片,附件
if (!StringUtils.isEmpty(content)){
MimeBodyPart bodyPart = new MimeBodyPart();
// 设置内容 getEmailHtml是邮箱内容模板
bodyPart.setContent(content, "text/html; charset=UTF-8");
mimeMultipart.addBodyPart(bodyPart);
}
if (!StringUtils.isEmpty(fileNames) && fileNames.length > 0){
for (String fileName:fileNames) {
File attachFile = new File(fileName);
if (attachFile.exists()){
MimeBodyPart attachPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource(attachFile);
attachPart.setDataHandler(new DataHandler(fileDataSource));
attachPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
mimeMultipart.addBodyPart(attachPart);
}else{
log.error("邮件附件文件 {} 不存在",fileName);
return;
}
}
}
mimeMessage.setContent(mimeMultipart);
mimeMessage.saveChanges();
Transport.send(mimeMessage);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
log.error("发送邮件失败:" + emailTo + " ----" + e.getMessage());
}
}
}
测试用例
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class MailServiceTest {
@Autowired
private MailService mailService;
@Test
void email() {
mailService.email("[email protected],[email protected]","邮件标题", "邮件内容", new String[]{"file.csv","file.csv"});
}
}