`
rensanning
  • 浏览: 3514324 次
  • 性别: Icon_minigender_1
  • 来自: 大连
博客专栏
Efef1dba-f7dd-3931-8a61-8e1c76c3e39f
使用Titanium Mo...
浏览量:37481
Bbab2146-6e1d-3c50-acd6-c8bae29e307d
Cordova 3.x入门...
浏览量:604342
C08766e7-8a33-3f9b-9155-654af05c3484
常用Java开源Libra...
浏览量:678107
77063fb3-0ee7-3bfa-9c72-2a0234ebf83e
搭建 CentOS 6 服...
浏览量:87280
E40e5e76-1f3b-398e-b6a6-dc9cfbb38156
Spring Boot 入...
浏览量:399819
Abe39461-b089-344f-99fa-cdfbddea0e18
基于Spring Secu...
浏览量:69075
66a41a70-fdf0-3dc9-aa31-19b7e8b24672
MQTT入门
浏览量:90487
社区版块
存档分类
最新评论

Spring Boot 入门 - 基础篇(10)- 发送邮件

 
阅读更多
(1)配置
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.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);


设置特殊编码
引用
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);


(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


(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


(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);
    }
 
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics