zoukankan      html  css  js  c++  java
  • SpringBoot发送邮件(163邮箱)

    SpringBoot发送邮件(163邮箱)

    常用的电子邮件协议有SMTP、POP3、IMAP4,它们都隶属于TCP/IP协议簇,默认状态下,分别通过TCP端口25、110和143建立连接。下面示例基于163邮箱,其他邮箱也都大同小异。

    一、准备工作

    登录163邮箱,开启 POP3/SMTP服务

    image

    设置授权密码,就是后面代码里的密码

    image

    二、构建SpringBoot项目发送邮件

    • 添加pom依赖
    <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.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    • 配置文件
    #####163邮箱########
    spring.mail.host=smtp.163.com
    spring.mail.username=159***3412@163.com
    spring.mail.password=***授权密码***
    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 
    spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactory
    spring.mail.properties.mail.debug=true 
    
    • 邮件发送工具类
    package com.cnsyear.util;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.stereotype.Component;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.Context;
    
    import javax.mail.MessagingException;
    import javax.mail.internet.MimeMessage;
    import java.io.File;
    import java.util.Date;
    import java.util.Map;
    
    /**
     * @Description 邮件相关工具类
     * http://www.javaboy.org/2019/0717/springboot-mail.html
     * https://blog.csdn.net/Tracycater/article/details/73441010
     * @Author jie.zhao
     * @Date 2019/12/13 10:22
     */
    @Component
    public class MailUtils {
    
        @Autowired
        private JavaMailSender javaMailSender;
        @Autowired
        private TemplateEngine templateEngine;
    
        /**
         * 发送简单的文件邮件
         *
         * @param subject 主题
         * @param from    发件人
         * @param to      收件人
         * @param text    邮件的正文
         */
        public void sendTextMail(String subject, String from, String to, String text) {
            this.sendTextMail(subject, from, to, null, null, text);
        }
    
        /**
         * 发送简单的文件邮件
         *
         * @param subject 主题
         * @param from    发件人
         * @param to      收件人
         * @param cc      抄送人,可以有多个抄送人
         * @param bcc     隐秘抄送人,可以有多个
         * @param text    邮件的正文
         */
        public void sendTextMail(String subject, String from, String to, String[] cc, String[] bcc, String text) {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject(subject);
            message.setFrom(from);
            message.setTo(to);
            if (cc != null) {
                message.setCc(cc);
            }
            if (bcc != null) {
                message.setBcc(bcc);
            }
            message.setSentDate(new Date());
            message.setText(text);
            javaMailSender.send(message);
        }
    
        /**
         * 发送带附件的邮件
         *
         * @param subject  主题
         * @param from     发件人
         * @param to       收件人
         * @param text     邮件的正文
         * @param filePath 附件
         */
        public void sendAttachFileMail(String subject, String from, String to, String text, String filePath) throws MessagingException {
            this.sendAttachFileMail(subject, from, to, null, null, text, filePath);
        }
    
        /**
         * 发送带附件的邮件
         *
         * @param subject  主题
         * @param from     发件人
         * @param to       收件人
         * @param cc       抄送人,可以有多个抄送人
         * @param bcc      隐秘抄送人,可以有多个
         * @param text     邮件的正文
         * @param filePath 附件
         */
        public void sendAttachFileMail(String subject, String from, String to, String[] cc, String[] bcc, String text, String filePath) throws MessagingException {
            //1. 构建邮件对象,注意,这里要通过 javaMailSender 来获取一个复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //2. MimeMessageHelper 是一个邮件配置的辅助工具类,true 表示构建一个 multipart message 类型的邮件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            //3. 针对工具类,配置邮件发送的基本信息
            helper.setSubject(subject);
            helper.setFrom(from);
            helper.setTo(to);
            if (cc != null) {
                helper.setCc(cc);
            }
            if (bcc != null) {
                helper.setBcc(bcc);
            }
            helper.setSentDate(new Date());
            helper.setText(text);
    
            File file = new File(filePath);
            //4. 添加邮件附件
            helper.addAttachment(file.getName(), file);
            //5. 发送邮件
            javaMailSender.send(mimeMessage);
        }
    
        /**
         * 发送邮件使用Thymeleaf模板
         *
         * @param subject      主题
         * @param from         发件人
         * @param to           收件人
         * @param data         邮件模板需要替换的数据
         * @param templatePath 模板路径 路径在src/main/resources/templates/下
         * @throws MessagingException
         */
        public void sendThymeleafMail(String subject, String from, String to, Map<String, Object> data, String templatePath) throws MessagingException {
            this.sendThymeleafMail(subject, from, to, null, null, data, templatePath);
        }
    
        /**
         * 发送邮件使用Thymeleaf模板
         *
         * @param subject      主题
         * @param from         发件人
         * @param to           收件人
         * @param cc           抄送人,可以有多个抄送人
         * @param bcc          隐秘抄送人,可以有多个
         * @param data         邮件模板需要替换的数据
         * @param templatePath 模板路径 路径在src/main/resources/templates/下
         * @throws MessagingException
         */
        public void sendThymeleafMail(String subject, String from, String to, String[] cc, String[] bcc, Map<String, Object> data, String templatePath) throws MessagingException {
            //1. 构建邮件对象,注意,这里要通过 javaMailSender 来获取一个复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //2. MimeMessageHelper 是一个邮件配置的辅助工具类,true 表示构建一个 multipart message 类型的邮件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            //3. 针对工具类,配置邮件发送的基本信息
            helper.setSubject(subject);
            helper.setFrom(from);
            helper.setTo(to);
            if (cc != null) {
                helper.setCc(cc);
            }
            if (bcc != null) {
                helper.setBcc(bcc);
            }
            helper.setSentDate(new Date());
    
            Context context = new Context();
            if (data != null) {
                data.forEach((k, v) -> {
                    context.setVariable(k, v);
                });
            }
            String process = templateEngine.process(templatePath, context);
            helper.setText(process, true);
            javaMailSender.send(mimeMessage);
        }
    }
    
    • 测试使用模板发送
    Java代码
    
    @Autowired
    private MailUtils mailUtils;
    
    public void sendMail() throws MessagingException {
        //省略data数据的获取。。。
        
        Map<String, Object> data = new HashMap<>();
        data.put("dsResult", dsResult);
        
        String[] cc = {"82****80@qq.com"};
        String[] bcc = {};
        mailUtils.sendThymeleafMail("今日的日期",
                "159****3412@163.com", "zha****e6@b****.cn", cc, bcc, data, "mail.html");
    }
    
    
    邮件模板 srcmain
    esources	emplatesmail.html
    
    <!DOCTYPE html>
    <html class="x-admin-sm" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
        <head>
            <meta charset="utf-8">
            <title>邮件模板</title>
        </head>
        <body>
            <div style="padding: 20px 50px;">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title"># 今天的日期</h3>
                </div>
                <div class="panel-body">
                    <div>
                        <p th:text="${dayResult.date}"></p>
                        <p th:text="${dayResult.yearTips+'年 农历' +dayResult.lunarCalendar}"></p>
                        <p th:text="${dayResult.typeDes}"></p>
                    </div>
                </div>
            </div>
        </body>
    </html>
    

    参考文档:

    http://www.javaboy.org/2019/0717/springboot-mail.html

  • 相关阅读:
    java枚举常见用法
    redis初使用
    Linux上搭建svn资源库
    redis集群创建
    大数据学习之Hadoop运行模式
    集群时间同步
    ssh免密登录
    mvc项目问题清单以及解决方法
    Memcached分布式缓存初体验
    Asp.Net 一个请求的处理流程
  • 原文地址:https://www.cnblogs.com/cnsyear/p/12712409.html
Copyright © 2011-2022 走看看