Spring Boot集成邮件服务

Spring Boot版本:2.0.6.RELEASE。
源代码:https://github.com/wu-boy/parker.git,parker-mail模块。

1、pom.xml中添加spring-boot-starter-mail引用

            org.springframework.boot
            spring-boot-starter-mail
        
2、application.yml中添加邮箱配置
spring:
  mail:
    host: smtp.mxhichina.com
    username: [email protected]
    password: 12345678

如果需要将项目发布到阿里云服务器,需要做如下配置,不然发送邮件老是失败。据说以普通SMTP的发送方式在阿里云上是不行的,阿里云是禁止使用25端口发送邮件的。

spring:
  mail:
    host: smtp.mxhichina.com
    username: [email protected]
    password: 12345678
    properties:
      mail:
        smtp:
          ssl:
            trust: smtp.mxhichina.com
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory
            port: 465
          auth: true
          starttls:
            enable: true
            required: true
3、编写服务进行测试
package com.wu.parker.mail.pojo.dto;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import javax.validation.constraints.NotBlank;

/**
 * @author wusq
 * @date 2019/3/15
 */
@ApiModel("邮件参数")
public class MailMessageDto {

    @ApiModelProperty("收件人")
    @NotBlank(message = "收件人不能为空")
    private String to;

    @ApiModelProperty("主题")
    @NotBlank(message = "主题不能为空")
    private String subject;

    @ApiModelProperty("内容")
    @NotBlank(message = "内容不能为空")
    private String text;

    // get/set略
}
package com.wu.parker.mail.pojo.dto;

/**
 * 邮件HTML参数
 * @author wusq
 * @date 2019/3/27
 */
public class MailHtmlMessageDto {

    /**
     * 收件人
     */
    private String to;

    /**
     * 主题
     */
    private String subject;

    /**
     * 参数,json字符串,例如{"id":"123"}
     */
    private String params;

    /**
     * 邮件模版代码,例如需要使用resource/templates/htmlTemplate.html,则mailCode是htmlTemplate
     */
    private String mailCode;

     // get/set略
}

package com.wu.parker.mail.controller;

import com.alibaba.fastjson.JSONObject;
import com.wu.parker.common.web.BaseResult;
import com.wu.parker.mail.pojo.dto.MailHtmlMessageDto;
import com.wu.parker.mail.pojo.dto.MailMessageDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;

/**
 * @author wusq
 * @date 2019/3/27
 */
@Api(description = "邮件服务")
@RestController
@RequestMapping("mail")
public class MailController {

    private static final Logger log = LoggerFactory.getLogger(MailController.class);

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;

    @ApiOperation("发送邮件")
    @PostMapping("send")
    public BaseResult send(@RequestBody MailMessageDto dto){
        BaseResult result = new BaseResult();

        if(StringUtils.isBlank(dto.getTo())){
            result.setData(0);
            result.setMessage("缺少收信人");
            return result;
        }

        if(StringUtils.isBlank(dto.getSubject())){
            result.setData(0);
            result.setMessage("缺少主题");
            return result;
        }

        if(StringUtils.isBlank(dto.getText())){
            result.setData(0);
            result.setMessage("缺少内容");
            return result;
        }

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(dto.getTo());
        message.setSubject(dto.getSubject());
        message.setText(dto.getText());

        try {
            javaMailSender.send(message);
        } catch (Exception e) {
            result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            result.setMessage(e.getMessage());
            log.error("发送邮件参数错误{}", e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @ApiOperation("发送HTML格式的邮件")
    @PostMapping("send/html")
    public BaseResult sendHtml(@RequestBody MailHtmlMessageDto dto){
        BaseResult result = new BaseResult();

        if(StringUtils.isBlank(dto.getTo())){
            result.setData(0);
            result.setMessage("缺少收信人");
            return result;
        }

        if(StringUtils.isBlank(dto.getSubject())){
            result.setData(0);
            result.setMessage("缺少主题");
            return result;
        }

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        try {
            // true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(dto.getTo());
            helper.setSubject(dto.getSubject());

            // 创建邮件正文
            Context context = new Context();
            if(StringUtils.isNotBlank(dto.getParams())){
                JSONObject params = JSONObject.parseObject(dto.getParams());
                context.setVariables(params);
            }
            String text = templateEngine.process(dto.getMailCode(), context);

            if(StringUtils.isNotBlank(text)){
                helper.setText(text, true);
            }else{
                result.setData(0);
                result.setMessage("缺少内容");
                return result;
            }

            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            result.setMessage(e.getMessage());
            log.error("发送HTML格式的邮件参数错误{}", e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

}

4、利用thymeleaf创建HTML模版来发送HTML格式的邮件

需要引入


            org.springframework.boot
            spring-boot-starter-thymeleaf
        

在resorces/templates下创建htmlTemplate.html




    
    Title


    您好,这是验证邮件,请点击下面的链接完成验证,
激活账号
源代码

https://github.com/wu-boy/parker.git
parker-mail模块

参考资料

1、springboot(十):邮件服务
2、Springboot完美解决在阿里云发布邮件的功能

你可能感兴趣的:(Spring,Spring,Boot)