Java代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
@Component
public class EmailUtil {
@Autowired
private JavaMailSender sender;
@Value("${spring.mail.username}")
private String from; // 发件人
@Value("${spring.mail.to}")
private String toStr; // 收件人
@Value("${spring.mail.cc}")
private String ccStr; // 抄送人
/**
* 发送纯文本邮件
* @param subject 标题
* @param content 内容
*/
public void sendSimpleMail(String subject, String content) {
String[] to = toStr.split(",");
String[] cc = ccStr == null || "".equals(ccStr) ? null : ccStr.split(",");
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
if (cc != null && cc.length > 0) {
message.setCc(cc);
}
message.setSubject(subject);
message.setText(content);
sender.send(message);
}
/**
* 发送带html的邮件
* @param subject 标题
* @param text html片段
* @param imgPath html片段中图片路径
*/
public void senderHtmlMail(String subject, String text, String imgPath) throws MessagingException {
String[] to = toStr.split(",");
String[] cc = ccStr == null || "".equals(ccStr) ? null : ccStr.split(",");
MimeMessage msg = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true);
helper.setFrom(from);
helper.setTo(to);
if (cc != null && cc.length > 0) {
helper.setCc(cc);
}
helper.setSubject(subject);
helper.setSentDate(new Date());
helper.setText(text, true);
if (imgPath != null && !"".equals(imgPath)) {
FileSystemResource res = new FileSystemResource(new File(imgPath));
helper.addInline("imagePicId", res);
}
sender.send(msg);
}
}
html模版(使用freemark)
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
Java代码
// 邮件html拼接
Map<String, Object> model = new HashMap<>();
model.put("timeSpanStr", year + "年 第" + weekNum + "周 " + timeSpan);
//读取 html 模板
Template template = freeMarkerConfigurer.getConfiguration().getTemplate("mail.html");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); // html片段
EmailUtil.senderHtmlMail(... ... // 调用发送邮件方法
配置文件
#邮件配置
spring.mail.host= smtp.126.com
spring.mail.username= elf***@126.com
spring.mail.password= *** ***
spring.mail.default-encoding= UTF-8
spring.mail.port= 25
spring.mail.to= elf***@126.com
spring.mail.cc=
注意:部分邮箱需要设置开启POP3/SMTP授权服务,在邮箱设置中进行设置
部分SpringBoot的jar中已整合mail,如未引入jar需在pom.xml中引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>