原理:通过JavaMailSender发送带附件的邮件
1.发送邮件代码
//注入邮件发送类
@Autowired
private MyJavaMailSender sender;
/**
发送邮件的方法
* @param to 邮件接收方
* @param subject 邮件标题
* @param content 邮件内容
* @param filePath 附件位置(例如: d://activityCDetailExcel/aaa.xlsx)
* @return
*/
public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
MimeMessage message = sender.createMimeMessage();
try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = null;
helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(sender.getUsername());//邮件的发送方,可以写死
helper.setTo(to.split(","));//邮件接收方,分割逗号.实现同时发送给多个用户
helper.setSubject(subject);
helper.setText(content, true);
File file = new File(filePath);
if (file.exists()) {
FileSystemResource tempFile = new FileSystemResource(new File(filePath));
helper.addAttachment(MimeUtility.encodeWord(file.getName(), "utf-8", "B"), tempFile);
}
sender.send(message);
return;
} catch (Exception e) {
logger.error("系统报错,错误信息:{}", e);
return;
}
}
2.yml配置文件:配置了发送方的邮箱等相关配置信息
spring:
mail:
username: 15*****@qq.com
password: z****
properties:
mail:
transport:
protocol: smtp
smtp:
host: smtp.exmail.qq.com
auth: true
port: 465
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory
fallback: false
3.实现JavaMailSender类,继承JavaMailSenderImpl方法,重写部分功能
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;
/**
* 实现多账号,轮询发送
*/
@Configuration
@EnableConfigurationProperties(MailProperties.class)
public class MyJavaMailSender extends JavaMailSenderImpl implements JavaMailSender {
private static Logger logger = LoggerFactory.getLogger(MyJavaMailSender.class);
private ArrayList<String> usernameList;
private ArrayList<String> passwordList;
private int currentMailId = 0;
private int currentMailId2 = 0;
private final MailProperties properties;
public MyJavaMailSender(MailProperties properties) {
this.properties = properties;
// 初始化账号
if (usernameList == null)
usernameList = new ArrayList<String>();
String[] userNames = this.properties.getUsername().split(",");
if (userNames != null) {
for (String user : userNames) {
usernameList.add(user);
}
}
// 初始化密码
if (passwordList == null)
passwordList = new ArrayList<String>();
String[] passwords = this.properties.getPassword().split(",");
if (passwords != null) {
for (String pw : passwords) {
passwordList.add(pw);
}
}
}
@Override
protected void doSend(MimeMessage[] mimeMessage, Object[] object) throws MailException {
super.setUsername(usernameList.get(currentMailId));
super.setPassword(passwordList.get(currentMailId));
logger.info("正在使用邮箱账号:"+super.getUsername()+"发送邮件.............");
currentMailId2 = (currentMailId == (usernameList.size()-1)? 0 : (currentMailId+1));
// 设置编码和各种参数
// super.setHost(this.properties.getHost());
super.setDefaultEncoding(this.properties.getDefaultEncoding().name());
super.setJavaMailProperties(asProperties(this.properties.getProperties()));
try {
super.doSend(mimeMessage, object);
} catch (MailException e) {
e.printStackTrace();
} finally {
currentMailId = currentMailId2;
}
}
private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
}
@Override
public String getUsername() {
return usernameList.get(currentMailId);
}
public int getCurrentMailId() {
return currentMailId;
}
public int getCurrentMailId2() {
return currentMailId2;
}
}