Springboot2(21)轻松整合mail

版权声明:转载请注明出处 https://blog.csdn.net/cowbin2012/article/details/85252433

源码地址

springboot2教程系列

SpringBoot实现邮件功能是非常的方便快捷的,因为SpringBoot默认有starter实现了Mail。 发送邮件应该是网站的必备功能之一,什么注册验证,忘记密码或者是给用户发送营销信息。 最早期的时候我们会使用JavaMail相关api来写发送邮件的相关代码,后来spring退出了 JavaMailSender更加简化了邮件发送的过程,在之后springboot对此进行了封装就有了 现在的spring-boot-starter-mail。

基础配置

引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- 模板引擎 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

获取QQ邮箱授权码

QQ邮箱->设置->账户->POP3/SMTP服务:开启服务后会获得QQ的授权码.

Mail配置文件

# JavaMailSender 邮件发送的配置
spring.mail.host: smtp.qq.com
spring.mail.username: 用户qq邮箱
#QQ邮箱的授权码
spring.mail.password: 授权码
spring.mail.properties.mail.smtp.auth: true
spring.mail.properties.mail.smtp.starttls.enable: true
spring.mail.properties.mail.smtp.starttls.required: true
spring.mail.default-encoding: UTF-8

163邮箱配置

#邮箱服务器地址
spring.mail.host: smtp.***.cn
#用户名
spring.mail.username: ****@****.cn
#密码
spring.mail.password: *****
spring.mail.default-encoding: UTF-8
spring.mail.sendTo: *****@qq.com

实现过程

@Component
@Slf4j
public class MailServiceImp implements MailService{

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void sendSimpleMail(String from,String to, String subject, String content) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        try {
            mailSender.send(message);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 发送html邮件
     * @param to
     * @param subject
     * @param content
     */
    @Override
    public void sendHtmlMail(String from,String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            log.info("html邮件发送成功");
        } catch (MessagingException e) {
            log.error("发送html邮件时发生异常!", e);
        }
    }


    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String from,String to, String subject, String content, String filePath){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            //helper.addAttachment("test"+fileName, file);

            mailSender.send(message);
            log.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送带附件的邮件时发生异常!", e);
        }
    }


    /**
     * 发送正文中有静态资源(图片)的邮件
     * @param to
     * @param subject
     * @param content
     * @param rscPath
     * @param rscId
     */
    public void sendInlineResourceMail(String from,String to, String subject, String content, String rscPath, String rscId){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

            mailSender.send(message);
            log.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }
}

在resorces/templates下创建MailTemplate.html.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
您好,这是验证邮件,请点击下面的链接完成验证,<br/>
<a href="#" th:href="@{ http://www.rojao.com/n/{id}(id=${id}) }">激活账号</a>
</body>
</html>

发送邮件

@RestController
public class MainController {


    @Autowired
    private MailService mailService;

    @Autowired
    private TemplateEngine templateEngine;

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

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

    @RequestMapping("/send")
    public String send(){
        sendSimpleMail();
        return "success";
    }

    public void sendSimpleMail(){
        mailService.sendSimpleMail(from,sendTo,"这是一封测试邮件!","这是一封测试邮件!");
    }

    public void sendHtmlMail() throws Exception {
        String content="<html>\n" +
                "<body>\n" +
                "    <h3>hello world ! 这是一封html邮件!</h3>\n" +
                "</body>\n" +
                "</html>";
        mailService.sendHtmlMail(from,sendTo,"test simple mail",content);
    }

    public void sendAttachmentsMail() {
        String filePath="e:\\tmp\\application.log";
        mailService.sendAttachmentsMail(from,sendTo, "主题:带附件的邮件", "有附件,请查收!", filePath);
    }


    public void sendInlineResourceMail() {
        String rscId = "neo006";
        String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>";
        String imgPath = "C:\\Users\\summer\\Pictures\\favicon.png";

        mailService.sendInlineResourceMail(from,sendTo,"主题:这是有图片的邮件", content, imgPath, rscId);
    }


    public void sendTemplateMail() {
        //创建邮件正文
        Context context = new Context();
        context.setVariable("id", "006");
        String emailContent = templateEngine.process("MailTemplate", context);
        mailService.sendHtmlMail(from,sendTo,"主题:这是模板邮件",emailContent);
    }
}

邮件异步发送

很多时候邮件发送并不是我们主业务必须关注的结果,比如通知类、提醒类的业务可以允许延时或者失败。
这个时候可以采用异步的方式来发送邮件,加快主交易执行速度,在实际项目中可以采用MQ发送邮件相关
参数,监听到消息队列之后启动发送邮件

猜你喜欢

转载自blog.csdn.net/cowbin2012/article/details/85252433