Spring Boot 邮件发送

Spring Boot 邮件发送

依赖配置

build.gradle


// 添加邮件依赖
compile('org.springframework.boot:spring-boot-starter-mail')

// 用于处理邮件模版

compile("org.springframework.boot:spring-boot-starter-thymeleaf")

邮件服务器配置

以下是邮件相关配置项说明


# Email (MailProperties)
spring.mail.default-encoding=UTF-8 # Default MimeMessage encoding.
spring.mail.host= # SMTP server host. For instance, `smtp.example.com`.
spring.mail.jndi-name= # Session JNDI name. When set, takes precedence over other mail settings.
spring.mail.password= # Login password of the SMTP server.
spring.mail.port= # SMTP server port.
spring.mail.properties.*= # Additional JavaMail session properties.
spring.mail.protocol=smtp # Protocol used by the SMTP server.
spring.mail.test-connection=false # Whether to test that the mail server is available on startup.
spring.mail.username= # Login user of the SMTP server.

以下是实际配置(注意:当服务器使用SSL加密时,最后一行是必须的)


spring:

  mail:
    host: smtp.exmail.qq.com
    port: 465
    protocol: smtp
    username: 
    password: 
    properties:
      mail:
        smtp:
          auth: true
          socketFactory.class: javax.net.ssl.SSLSocketFactory

Thymeleaf配置

以下是Thymeleaf的配置项说明


spring.thymeleaf.cache – enable/disable template caching.
spring.thymeleaf.check-template – check that the template exists before rendering it.
spring.thymeleaf.check-template-location – check that the templates location exists.
spring.thymeleaf.content-type – specifies content-type value.
spring.thymeleaf.enabled – enable mvc thymeleaf view resolution.
spring.thymeleaf.encoding – specifies template encoding.
spring.thymeleaf.excluded-view-names – comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode – template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix – specifies the prefix that gets prepended to view names when building a URL.
spring.thymeleaf.suffix – specifies the suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order – specifies the order of the template resolver in the chain.
spring.thymeleaf.view-names – comma-separated list of view names that can be resolved.

也可以使用java代码进行配置


@Configuration
public class ThymeleafConfig {
    @Bean
    public SpringTemplateEngine springTemplateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.addTemplateResolver(htmlTemplateResolver());
        return templateEngine;
    }
    @Bean
    public SpringResourceTemplateResolver htmlTemplateResolver(){
        SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
        emailTemplateResolver.setPrefix("classpath:/templates/");
        emailTemplateResolver.setSuffix(".html");
        emailTemplateResolver.setTemplateMode(StandardTemplateModeHandlers.HTML5.getTemplateModeName());
        emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        return emailTemplateResolver;
    }
}

发送邮件


@Component
public class MailHelper {
    @Value("${mail.from}")
    private String from;

    @Value("${mail.nickname}")
    private String nickname;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private SpringTemplateEngine templateEngine;

    /**
     * 发送纯文本内容
     * @param to
     * @param title
     * @param text
     * @throws MessagingException
     */
    public void sendTextMail(String to, String title, String text) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false,"UTF-8");
        try {
            helper.setFrom(new InternetAddress(from, nickname, "UTF-8"));
        } catch (UnsupportedEncodingException e){
            helper.setFrom(from);
        }
        helper.setTo(to);
        helper.setSubject(title);
        helper.setText(text);
        mailSender.send(mimeMessage);
    }

    /**
     * 发送模版邮件
     * @param to
     * @param title
     * @param templateName
     * @param data
     * @param files
     * @throws MessagingException
     */
    public void sendTemplateMail(String to, String title, String templateName, Map data, Map files) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        Context context = new Context();
        context.setVariables(data);
        String html = templateEngine.process(templateName, context);
        try {
            helper.setFrom(new InternetAddress(from, nickname, "UTF-8"));
        } catch (UnsupportedEncodingException e){
            helper.setFrom(from);
        }
        helper.setTo(to);
        helper.setSubject(title);
        helper.setText(html, true);
        if (null != files){
            for(String name: files.keySet()){
                ClassPathResource file = new ClassPathResource(files.get(name));
                helper.addInline(name, file);  // 内联图片

                // helper.addAttachment(name, file); // 添加附件
            }
        }
        mailSender.send(mimeMessage);
    }
}

Thymeleaf 模版

Thymeleaf模版的使用网上教程很多,这里放一个示例。





    
    
    
    
    
    Getting Started: Serving Web Content



Spring Boot Thymeleaf Configuration Example

如果在邮件中使用内联图片,图片的src属性需要按如下代码设置


facebook

其中cid的值是MimeMessageHelper.addInline()方法第一个参数的值。

参考:

  • Sending Email](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-email.html))

  • Appendix A. Common application properties](https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html))

  • Spring Boot Thymeleaf Configuration Example - Memorynotfound

你可能感兴趣的:(Spring Boot 邮件发送)