@Component
public class MailUtil {
@Autowired
JavaMailSenderImpl mailSender;
static {
System.setProperty("mail.mime.splitlongparameters","false");
}
/**
* @return 邮件发件人,也可以设置到配置文件中
*/
private String getAddress(){
return "";
}
public void send(String content, String subject, String email){
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject(subject);
message.setText(content);
message.setTo(email);
message.setFrom(getAddress());
mailSender.send(message);
}
public void sendHtml(String content, String subject, String email){
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(mimeMessage, false, "UTF-8");
helper.setFrom(getAddress());
helper.setTo(email);
helper.setText(content, true);
mailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void sendAttachment(String content, String subject, String email, String filePath){
sendAttachment(content,subject, email, filePath, FilenameUtils.getName(filePath));
}
/**
*
* @param content 邮件内容
* @param subject 邮件标题
* @param email 邮箱
* @param filePath 附件路径
* @param fileName 附件名
*/
public void sendAttachment(String content, String subject, String email, String filePath, String fileName) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom(getAddress());
helper.setTo(email);
helper.setText(content, false);
helper.addAttachment(MimeUtility.encodeWord(fileName, "UTF-8", "B"), new File(filePath));
mailSender.send(mimeMessage);
} catch (MessagingException | UnsupportedEncodingException e) {
//可以在异常中进行处理,例如重发
e.printStackTrace();
}
}
public void sendAttachments(String content, String subject, String email, List<String> filePaths) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom(getAddress());
helper.setTo(email);
helper.setText(content, false);
for (String filePath : filePaths) {
helper.addAttachment(MimeUtility.encodeWord(FilenameUtils.getName(filePath), "UTF-8", "B"), new File(filePath));
}
mailSender.send(mimeMessage);
} catch (MessagingException | UnsupportedEncodingException e) {
//可以在异常中进行处理,例如重发
e.printStackTrace();
}
}
}
application.properties文件
spring.mail.host=1.1.1.1
spring.mail.username=wen.jie
spring.mail.password=wen.jie
spring.mail.default-encoding=UTF-8
spring.mail.port=25
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.timeout=250000