内容纲要

SpringBoot 亚马逊Simple邮件发送

1.添加maven依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.添加配置文件

spring:
  freemarker:
    # 是否允许HttpServletRequest属性覆盖(隐藏)控制器生成的同名模型属性。
    allow-request-override: false
    # 是否允许HttpSession属性覆盖(隐藏)控制器生成的同名模型属性。
    allow-session-override: false
    # 是否启用模板缓存。
    cache: false
    # 模板编码。
    charset: UTF-8
    # 是否检查模板位置是否存在。
    check-template-location: true
    # 是否启用freemarker
    enabled: true
    # 设定模板的加载路径,多个以逗号分隔,默认:
    template-loader-path: classpath:templates/
  mail:
    # 配置 SMTP 服务器地址
    host: email-smtp.ap-northeast-1.amazonaws.com
    # 发送者邮箱
    fromuser: *******.com
    # 用户名
    username: *****
    # 密码
    password: ********
    # 端口
    port: 465
    # 默认的邮件编码为UTF-8
    default-encoding: UTF-8
    # 协议
    protocol: smtp
    # 配置SSL 加密工厂
    properties:
      mail.smtp.auth: true
      mail.smtp.starttls.enable: true
      mail.smtp.starttls.required: true
      mail.smtp.socketFactory.port: 465
      mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
      mail.smtp.socketFactory.fallback: false
      #表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
      mail.debug: true

3.java类

import com.alibaba.fastjson.JSONObject;
import com.***.***.config.PropertiesConfig;
import com.***.***.dto.EmailUserDto;
import com.***.***.service.MailService;

import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
* 邮件发送接口实现类
*
* @author 111
* @since 2021/04/20 10:54
*/
@Service
    public class MailServiceImpl implements MailService {

        private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

        // 注入MailSender
        @Autowired
        private JavaMailSender mailSender;

        // 发送邮件的模板引擎
        @Autowired
        private FreeMarkerConfigurer configurer;

        // 配置信息
        @Autowired
        private PropertiesConfig propertiesConfig;

        /**
* 发送邮件
*
* @param params       发送邮件的主题对象 object
* @param title        邮件标题
* @param templateName 模板名称
*/
        @Override
        public void sendMessageMail(Object params, String title, String templateName, List<EmailUserDto> emailUserDtoList) {

            try {
                for (int i = 0; i < emailUserDtoList.size(); i++) {
                    MimeMessage mimeMessage = mailSender.createMimeMessage();
                    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
                    // 接收者(可能有多个)
                    helper.setTo(emailUserDtoList.get(i).getEmail());
                    // 邮件标题
                    helper.setSubject(propertiesConfig.getMailTitle());
                    // 发件人信息
                    helper.setFrom(propertiesConfig.getMailFrom());
                    JSONObject jsonObject = JSONObject.parseObject(params.toString());
                    jsonObject.put("username", emailUserDtoList.get(i).getUsername());
                    Template template = configurer.getConfiguration().getTemplate(templateName);
                    String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, jsonObject);
                    helper.setText(text, true);

                    mailSender.send(mimeMessage);
                    logger.info(LocalDateTime.now() + "发送邮件成功!");
                }
            } catch (Exception e) {
                logger.info(e.getMessage(), e);
            }

        }

    }
Spread the knowledge