• SpringBoot配置Email发送功能


    快速入门

    在Spring Boot的工程中的 pom.xml 中引入 spring-boot-starter-mail 依赖:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.3.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.james</groupId>
        <artifactId>springbootmail</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>springbootmail</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!-- 邮件服务 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-mail</artifactId>
            </dependency>
            <!-- Thymeleaf 模版,用于发送模版邮件 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    

    在 application.properties 中配置相应的属性内容
    126邮箱做如下配置

    server.port=8080
    spring.mail.host=smtp.126.com
    spring.mail.port=25
    spring.mail.username=123456@126.com
    spring.mail.password=123456
    spring.mail.default-encoding=UTF-8
    spring.mail.properties.mail.smtp.auth=true
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.starttls.required=true
    

    QQ邮箱的配置则是

    #spring.mail.host=smtp.qq.com
    #spring.mail.port=465
    # 你的邮箱地址
    #spring.mail.username=123456@qq.com
    # 你的授权码(126 和 163 以及 qq 邮箱 都需要授权码登录,没有授权码的直接登录网页版邮箱设置里设置)
    spring.mail.password=xrgkewnbmdphefje
    spring.mail.properties.mail.smtp.auth=false
    spring.mail.default-encoding=UTF-8
    spring.mail.properties.mail.smtp.auth=true
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.starttls.required=true
    ### QQ邮箱必须加此注解
    spring.mail.properties.mail.smtp.ssl.enable=true
    

    创建 MailService 类,注入 JavaMailSender 用于发送邮件,使用 @Value("${spring.mail.username}") 绑定配置文件中的参数用于设置邮件发送的来邮箱。使用 @Service 注解把 MailService 注入到 Spring 容器,使用 Lombok 的 @Slf4j 引入日志。

    package com.james.springbootmail.serivice;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.stereotype.Service;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.Context;
    
    import javax.mail.MessagingException;
    import javax.mail.internet.MimeMessage;
    import java.io.File;
    import java.text.Normalizer;
    import java.util.Map;
    
    /**
     * @author James
     * @create 2019-04-01 10:14
     * @desc
     **/
    
    @Service
    @Slf4j
    public class MailService {
    
        @Value("${spring.mail.username}")
        private String from;
    
        @Value("${spring.mail.password}")
        private String pass;
    
        @Autowired
        private JavaMailSender mailSender;
    
        @Autowired
        private TemplateEngine templateEngine;
    
        /**
         * 发送简单文本邮件
         *
         * @param to
         * @param subject
         * @param content
         */
        public void sendSimpleTextMail(String to, String subject, String content) {
            System.out.println("ddd  "+ from);
            System.out.println("ddd  "+ pass);
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            message.setFrom(from);
            mailSender.send(message);
            log.info("【文本邮件】成功发送!to={}", to);
        }
    
        /**
         * 发送 HTML 邮件
         *
         * @param to
         * @param subject
         * @param content
         * @throws MessagingException
         */
        public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            // true 为 HTML 邮件
            messageHelper.setText(content, true);
            mailSender.send(message);
            log.info("【HTML 邮件】成功发送!to={}", to);
        }
    
        /**
         * 发送带附件的邮件
         *
         * @param to
         * @param subject
         * @param content
         * @param fileArr
         */
        public void sendAttachmentMail(String to, String subject, String content, String... fileArr)
                throws MessagingException {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content, true);
    
            // 添加附件
            for (String filePath : fileArr) {
                FileSystemResource fileResource = new FileSystemResource(new File(filePath));
                if (fileResource.exists()) {
                    String filename = fileResource.getFilename();
                    messageHelper.addAttachment(filename, fileResource);
                }
            }
            mailSender.send(mimeMessage);
            log.info("【附件邮件】成功发送!to={}", to);
        }
    
    
        /**
         *  发送带图片的邮件
         * @param to
         * @param subject
         * @param content
         * @param imgMap
         * @throws MessagingException
         */
        public void sendImgMail(String to, String subject, String content, Map<String, String> imgMap)
                throws MessagingException {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content, true);
            // 添加图片
            for (Map.Entry<String, String> entry : imgMap.entrySet()) {
                FileSystemResource fileResource = new FileSystemResource(new File(entry.getValue()));
                if (fileResource.exists()) {
                    String filename = fileResource.getFilename();
                    messageHelper.addInline(entry.getKey(), fileResource);
                }
            }
            mailSender.send(mimeMessage);
            log.info("【图片邮件】成功发送!to={}", to);
        }
    
        /**
         * 发送模版邮件
         *
         * @param to
         * @param subject
         * @param paramMap
         * @param template
         * @throws MessagingException
         */
        public void sendTemplateMail(String to, String subject, Map<String, Object> paramMap, String template)
                throws MessagingException {
            Context context = new Context();
            // 设置变量的值
            context.setVariables(paramMap);
            String emailContent = templateEngine.process(template, context);
            sendHtmlMail(to, subject, emailContent);
            log.info("【模版邮件】成功发送!paramsMap={},template={}", paramMap, template);
        }
    }
    
    

    运行单元测试,测试邮件的发送。

    package com.james.springbootmail;
    
    import com.james.springbootmail.serivice.MailService;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.thymeleaf.TemplateEngine;
    
    import javax.mail.MessagingException;
    import java.util.HashMap;
    import java.util.Map;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class SpringbootmailApplicationTests {
    
        @Autowired
        private MailService mailService;
        @Autowired
        private TemplateEngine templateEngine;
    
        @Test
        public void contextLoads() {
            String to = "123456@126.com";
            String subject = "Springboot 发送简单文本邮件";
            String content = "<h2>Hi~</h2><p>第一封 Springboot HTML 邮件</p>";
            mailService.sendSimpleTextMail(to, subject, content);
        }
    
        @Test
        public void sendHtmlMailTest() throws MessagingException {
            String to = "123456@126.com";
            String subject = "Springboot 发送 HTML 邮件";
            String content = "<h2>Hi~</h2><p>第一封 Springboot HTML 邮件</p>";
            mailService.sendHtmlMail(to, subject, content);
        }
    
    
        @Test
        public void sendAttachmentTest() throws MessagingException {
            String to = "123456@126.com";
            String subject = "Springboot 发送 HTML 附件邮件";
            String content = "<h2>Hi~</h2><p>第一封 Springboot HTML 附件邮件</p>";
            String filePath = "pom.xml";
            mailService.sendAttachmentMail(to, subject, content, filePath);
        }
    
        @Test
        public void sendImgTest() throws MessagingException {
            String to = "123456@126.com";
            String subject = "Springboot 发送 HTML 图片邮件";
            String content =
                  "<h2>Hi~</h2><p>第一封 Springboot HTML 图片邮件</p><br/><img src='img/1.jpg' />";
            String imgPath = "img/1.jpg";
            Map<String, String> imgMap = new HashMap<>();
            imgMap.put("img01", imgPath);
            imgMap.put("img02", imgPath);
            mailService.sendImgMail(to, subject, content, imgMap);
        }
    
        @Test
        public void sendTemplateMailTest() throws MessagingException {
            String to = "123456@126.com";
            String subject = "Springboot 发送 模版邮件";
            Map<String, Object> paramMap = new HashMap();
            paramMap.put("username", "Darcy");
            mailService.sendTemplateMail(to, subject, paramMap, "RegisterSuccess");
        }
    }
    
    

    关注我的技术公众号,每天都有优质技术文章推送。
    微信扫一扫下方二维码即可关注:
    在这里插入图片描述

    尚未佩妥剑,转眼便江湖,愿历尽千帆,归来仍少年 
  • 相关阅读:
    grpc xservice 使用
    modsecurity3.0 nginx 安装
    scrapy docker 基本部署使用
    fabio 安装试用&&实际使用的几个问题
    yugabyte cloud native db 基本试用
    coredns 编译模式添加插件
    gradle 项目构建以及发布maven 私服&& docker 私服构建发布
    groovy gradle 构建配置
    groovy && java 混编 gradle 配置
    gradle 构建包含源码配置
  • 原文地址:https://www.cnblogs.com/James-1024/p/12203770.html
Copyright © 2020-2023  润新知