引入 pom
<!-- 发送邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
/**
* 发送邮件.
*
* @param mailSender
* JavaMailSenderImpl对象
* @param toAddresses
* 收信人地址列表。使用此方法时,要注意邮件服务器对群发邮件数量的考虑
* @param subject
* 邮件主题
* @param content
* 邮件内容
* @return true, if successful
* @throws Exception
* the exception
* @return
*/
public static boolean send(JavaMailSenderImpl mailSender, String[] toAddresses, String subject,
String content) throws Exception {
MimeMessage mimeMsg = null;
try {
mimeMsg = ((JavaMailSenderImpl) mailSender).createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true, "UTF-8");
InternetAddress[] address = new InternetAddress[toAddresses.length];
for (int i = 0; i < address.length; i++) {
address[i] = new InternetAddress(toAddresses[i]);
}
helper.setTo(address);
String fromAddress = ((JavaMailSenderImpl) mailSender).getUsername();
helper.setFrom(fromAddress, "xx系统平台");
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(mimeMsg);
} catch (Exception ex) {
logger.error("邮件发送异常。", ex);
throw new Exception("邮件发送失败");
}
return true;
}
/**
* 发送邮件并添加附件
*/
public static boolean send(JavaMailSenderImpl mailSender, String[] toAddresses, String subject,
String content, List<File> files) throws Exception {
MimeMessage mimeMsg = null;
try {
mimeMsg = ((JavaMailSenderImpl) mailSender).createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true, "UTF-8");
InternetAddress[] address = new InternetAddress[toAddresses.length];
for (int i = 0; i < address.length; i++) {
address[i] = new InternetAddress(toAddresses[i]);
}
helper.setTo(address);
String fromAddress = ((JavaMailSenderImpl) mailSender).getUsername();
helper.setFrom(fromAddress, "餐补系统平台");
helper.setSubject(subject);
helper.setText(content, true);
for (File file : files) {
helper.addAttachment(file.getName(), file);
}
((JavaMailSenderImpl) mailSender).send(mimeMsg);
return true;
} catch (Exception ex) {
logger.error("邮件发送异常。", ex);
return false;
}
}
/**
* 单人邮件
* @param mailSender
* @param toAddresses
* @param subject
* @param content
* @throws Exception
*/
public static void send(JavaMailSenderImpl mailSender, String toAddresses, String subject,
String content) throws Exception {
MimeMessage mimeMsg = null;
try {
mimeMsg = ((JavaMailSenderImpl) mailSender).createMimeMessage(); //使用JavaMail的MimeMessage,支持更加复杂的邮件格式和内容
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true, "UTF-8");//设置utf-8编码,否则邮件会有乱码,
helper.setTo(toAddresses);
String fromAddress = ((JavaMailSenderImpl) mailSender).getUsername();
helper.setFrom(fromAddress, "xx系统平台");
helper.setSubject(subject);
helper.setText(content, true);//第二个参数true,表示text的内容为html
mailSender.send(mimeMsg);
} catch (Exception ex) {
logger.error("邮件发送异常。", ex);
throw new Exception("邮件发送失败");
}
}