pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
application.properties
引用
spring.mail.host=localhost
spring.mail.protocol=smtp # Protocol
spring.mail.port=25 # SMTP server port.
spring.mail.username= # Login user of the SMTP server.
spring.mail.password= # Login password of the SMTP server.
spring.mail.default-encoding=UTF-8 # Default MimeMessage encoding.
# Additional JavaMail session properties.
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.protocol=smtp # Protocol
spring.mail.port=25 # SMTP server port.
spring.mail.username= # Login user of the SMTP server.
spring.mail.password= # Login password of the SMTP server.
spring.mail.default-encoding=UTF-8 # Default MimeMessage encoding.
# Additional JavaMail session properties.
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
*** 一般只需要配置spring.mail.host属性即可。
(2)文本邮件
@Service public class MailService { @Autowired private JavaMailSender mailSender; public void sendMail(String from, String to, String subject, String msg) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(msg); mailSender.send(message); } }
(3)HTML邮件
引用
message.setText("<html><h1>HTML EMAIL</h1></html>", true);
(4)带附件邮件
引用
File attachmentFile = new File("d://test.txt");
FileSystemResource file = new FileSystemResource(attachmentFile);
messageHelper.addAttachment("test.txt", file);
FileSystemResource file = new FileSystemResource(attachmentFile);
messageHelper.addAttachment("test.txt", file);
设置特殊编码
引用
File attachmentFile = new File("d://test.csv");
String csv = FileUtils.readFileToString(attachmentFile, "GBK");
javax.activation.DataSource dataSource = new ByteArrayDataSource(csv, "text/csv; charset=GBK");
messageHelper.addAttachment("test.csv", dataSource);
String csv = FileUtils.readFileToString(attachmentFile, "GBK");
javax.activation.DataSource dataSource = new ByteArrayDataSource(csv, "text/csv; charset=GBK");
messageHelper.addAttachment("test.csv", dataSource);
(5)Template模板
无论thymeleaf或freemarker都可以。(使用FreeMarker居多)
@Service public class MailService { @Autowired private JavaMailSender mailSender; @Autowired private TemplateEngine thymeleafTemplateEngine; @Autowired private Configuration freemarkerConfiguration; public void prepareAndSend(SimpleMailMessage msg, Map<String, Object> tplVariables) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(msg.getTo()); message.setFrom(msg.getFrom()); message.setSubject(msg.getSubject()); String body = buildThymeleaf(tplVariables); message.setText(body, true); } }; try { mailSender.send(preparator); } catch (MailException e) { // ... } } public String buildThymeleaf(String templateName, Map<String, Object> model) { Context context = new Context(); context.setVariables(model); return templateEngine.process(templateName, context); } public String buildFreeMarker(String templateName, Map<String, Object> model) { Template tpl = freemarkerConfiguration.getTemplate(templateName); return FreeMarkerTemplateUtils.processTemplateIntoString(tpl, model); } }
模板文件
src/main/resources/templates/email
引用
template_name.html
或
template_name.tpl
或
template_name.tpl
(6)国际化对应
传入locale
public String buildThymeleaf(String templateName, Map<String, Object> model, Locale locale) { Context context = new Context(locale); context.setVariables(model); return templateEngine.process(templateName, context); } public String buildFreeMarker(String templateName, Map<String, Object> model, Locale locale) { Template tpl = freemarkerConfiguration.getTemplate(templateName, locale); return FreeMarkerTemplateUtils.processTemplateIntoString(tpl, model); }
模板文件
src/main/resources/templates/email
引用
template_name.html
template_name_zh.html
template_name_ja.html
或
template_name.tpl
template_name_zh.tpl
template_name_ja.tpl
template_name_zh.html
template_name_ja.html
或
template_name.tpl
template_name_zh.tpl
template_name_ja.tpl
(7)异步发送邮件
开启异步支持@EnableAsync
@EnableAsync // 追加 @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
设置@Async
@Async public void sendMail(String from, String to, String subject, String msg) { // ... }
(8)测试
FakeSMTP https://github.com/Nilhcem/FakeSMTP
smtp4dev https://github.com/rnwood/smtp4dev
Papercut https://github.com/changemakerstudios/papercut
GreenMail https://github.com/greenmail-mail-test/greenmail
代码示例
@Service public class MailService { @Autowired private JavaMailSender mailSender; @Autowired private TemplateEngine thymeleafTemplateEngine; @Autowired private Configuration freemarkerConfiguration; public void sendTextMail(String from, String to, String subject, String text) { return sendMail(from, to, subject, text, false); } public void sendHtmlMail(String from, String to, String subject, String htmlBody) { return sendMail(from, to, subject, htmlBody, true); } public void sendMail(String from, String to, String subject, String msg, Boolean isHtml) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(msg, isHtml); mailSender.send(message); } public void prepareAndSend(SimpleMailMessage msg, Map<String, Object> tplVariables) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(msg.getTo()); message.setFrom(msg.getFrom()); message.setSubject(msg.getSubject()); String body = buildThymeleaf(tplVariables); // ... message.setText(body, true); } }; try { mailSender.send(preparator); } catch (MailException e) { // ... } } public String buildThymeleaf(String templateName, Map<String, Object> model) { Context context = new Context(); context.setVariables(model); return templateEngine.process(templateName, context); } public String buildThymeleaf(String templateName, Map<String, Object> model, Locale locale) { Context context = new Context(locale); context.setVariables(model); return templateEngine.process(templateName, context); } public String buildFreeMarker(String templateName, Map<String, Object> model) { Template tpl = freemarkerConfiguration.getTemplate(templateName); return FreeMarkerTemplateUtils.processTemplateIntoString(tpl, model); } public String buildFreeMarker(String templateName, Map<String, Object> model, Locale locale) { Template tpl = freemarkerConfiguration.getTemplate(templateName, locale); return FreeMarkerTemplateUtils.processTemplateIntoString(tpl, model); } }