使用Spring Boot 发送邮件(持续更新...)

前言

做大学毕设的时候,SSM项目需要向用户的邮箱发送一个验证码,对于当时的我来说,对于这个问题一点思路都没有,所有查找的资料最后都指向了JavaMail,于是当时就在网上找到了一个相关的代码,经过使用确实是好用的。

package tony.common;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.util.MailSSLSocketFactory;

public class MailUtil implements Runnable{

    private String email;
    private String code;
    public  boolean flag;
    
    public MailUtil(String email,String code){
        this.email=email;
        this.code=code;
    }
    
    public void run() {
        // 1.创建连接对象javax.mail.Session
        // 2.创建邮件对象 javax.mail.Message
        // 3.发送一封激活邮件
        String from = "";// 发件人电子邮箱
        String host = "smtp.qq.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)

        Properties properties = System.getProperties();// 获取系统属性

        properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
        properties.setProperty("mail.smtp.auth", "true");// 打开认证

        try {
            //QQ邮箱需要下面这段代码,163邮箱不需要
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);


            // 1.获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("", ""); // 发件人邮箱账号、授权码
                }
            });

            // 2.创建邮件对象
            Message message = new MimeMessage(session);
            // 2.1设置发件人
            message.setFrom(new InternetAddress(from));
            // 2.2设置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 2.3设置邮件主题
            message.setSubject("账号激活");
            // 2.4设置邮件内容
            String content = "<html><head></head><body><h2>这是一封来自账号激活的邮件</h2><h1>您的验证码是:"
                    + code + "</h2></body></html>";
            message.setContent(content, "text/html;charset=UTF-8");
            // 3.发送邮件
            Transport.send(message);
            System.out.println("邮件成功发送!");
            flag=true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
}

这是对JavaMail最基本的封装,当时我并不知道Spring,以及Spring boot对JavaMail也有特别好的封装。
直到前几天我在慕课网上无意间看到了一个课程讲述的是Spring Boot发送邮件,于是便有了这篇文章,也是对那个课程的总结和整理,原课程视频传送门。在此特别感谢这位作者的分享。

正文

在给出代码之前,我们先看看相关的知识。

邮件使用场景

1.注册验证,需要发送一个验证码,或者一个验证的链接
2.网站营销 可以发送推销相关的信息,以及服务。
3.可以在忘记密码的时候发送验证码,例如注册。
4.提醒监控系统。

邮件发送原理

传输协议SMTP 和POP3
内容拓展后:IMAP
下面简单说一下发送文件的原理,这里我用一个例子进行讲解,让大家更容易理解:
假设我现在想通过sina邮箱发送邮件到qq邮箱,那么当我在sina客户端发送了一个邮件之后,邮件通过SMTP 协议到达了新浪的SMTP 服务器,但是它发现自己是要发到qq邮箱的,于是会通过SMTP协议继续路由到qq的SMTP服务器上去,然后这个邮箱继续会进入到POP3 服务器中的对用的这个用户的区域中去,可以给它理解为一个消息队列等待着有对应的客户端来取,然后qq邮件客户端会通过POP3协议去POP3服务器中获取获取邮件的列表,获得后返回给客户端。
下面给出相应代码:
我们首先需要获得一个Maven的空项目,这个可以在以下链接下载到Spring Boot 空项目
然后我们需要在pom.xml中加入以下依赖。

<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>

一个是对Spring Boot对JavaMail的集成,另一个是对thymeleaf模版引擎的集成(为什么要用这个模版引擎,我会在下面说到)
然后在 application.properties中加入以下代码:

spring.mail.host=smtp.qq.com(SMTP服务器的名字)
spring.mail.username=(邮箱名称)
spring.mail.password = (邮箱密码,这里指的是,在邮箱中打开SMTP/POP3验证之后,会给出一个验证码)
spring.mail.default-encoding=UTF-8(编码格式)
spring.mail.port=465(SMTP服务器开放的端口)
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

然后是Java代码,我们写了一个service去完成它:

package com.harry.mail.service;

import com.sun.mail.smtp.DigestMD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailSender;
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.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Random;

@Service
public class MailService {

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

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private MailSender sender;

    @Resource
    private TemplateEngine templateEngine;

    //这是发送一个文本邮件
    public void sendSimpleMail(String to,String subject,String content){
        SimpleMailMessage mail =new SimpleMailMessage();
        mail.setTo(to);
        mail.setSubject(subject);
        mail.setText(content);
        mail.setFrom(from);
        sender.send(mail);
    }

    //发送html邮件
    public void sendHtmlMail(String to , String subject , String content){
        MimeMessage message =mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper =new MimeMessageHelper(message,true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content,true);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    //带有附件的邮件
    //可以把附件装进list集合中,然后放入多个附件
    public void sendAttachmentsMail(String to ,String subject,String content , String filePath){

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            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 = file.getFilename();
            //在这里可以add 多个附件,我这里就是为了测试说明,放了两个相同的文件,但是名字不同的。
            helper.addAttachment(fileName,file);
            helper.addAttachment(fileName+"_2",file);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    //带有图片的邮件
    public void sendImageMail(String to ,String subject,String content , String filePath,String srcId){

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            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));
            helper.addInline(srcId,file);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
//使用模版发送邮件
    public void sendTemplateMail(String to ,String subject, String content){
        Context context = new Context();
        context.setVariable("validvalue", new Random().nextInt(999999));

        String templateContext = templateEngine.process("emailTemplate",context);
        sendHtmlMail(to,subject,templateContext);
    }
}

我们可以看出来使用模版发送邮件调用了上面的使用html发送邮件的方法,而这个模版就是我们上面要使用的thymeleaf,那么我们为什么需要模版呢,正是因为,我们很多使用场景,大致的内容都是相同的,只是里面的参数不同罢了,就是我们的例子中一样,我们只是想要不同的验证码,没必要每一次都把html代码重新写一遍对吧,下面给出html模版代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>邮件模版</title>
</head>
<body>
    <p>
        你好,欢迎你的到来你的验证码为:
    </p>
    <h3 th:text="${validvalue}"></h3>
</body>
</html>

最后是测试类:
在test文件夹下面建造自己的

package com.harry.mail.service;

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.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloTest {

    @Autowired
    private MailService mailService;

    @Resource
    private TemplateEngine templateEngine;

    @Test
    public void sendSimpleMailTest(){
        mailService.sendSimpleMail("要发送给你的邮箱账户","主题","内容");
    }

    @Test
    public void sendHtmlMailTest(){
        mailService.sendHtmlMail("要发送给你的邮箱账户","主题","内容(应当为html形式的)");
    }

    @Test
    public void sendAttachment(){

        mailService.sendAttachmentsMail(""要发送给你的邮箱账户","主题","内容","文件的路径");
    }

    @Test
    public void sendImageMail(){
        String srcId = "harryImage";
        String htmlContent = "<html><body><h3>this is a image:</h3> <img src = \'cid:{srcId}\'></body></html>".replace("{srcId}",srcId);
        mailService.sendImageMail("要发送给你的邮箱账户","主题",htmlContent,"图片路径",srcId(赋予图片一个标实码));
    }
    @Test
    public  void sendTemplateMail(){
        mailService.sendTemplateMail("发送到的邮箱账户","主题",null(内容从模版中读,所以为空));
    }
}

我把代码放在了下面github上,如果有需要可以去看一下。
https://github.com/luckypoison/mailProject

后记

在之后,我会把这些代码进行封装然后提供给大家,有什么需要补充的,我也会持续更新在这个文章中,谢谢大家,希望对大家有帮助。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,654评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,806评论 6 342
  • 原文链接:https://docs.spring.io/spring-boot/docs/1.4.x/refere...
    pseudo_niaonao阅读 4,692评论 0 9
  • 今天送下闺女,阳光明媚带着儿子去理了理发,准备送幼儿园,一到理发店门口儿子的哭声就没断,哭着找姐姐,要姐姐去...
    淑婷妈咪阅读 121评论 0 1
  • 我站在夜的中央 一个头发凌乱 双手皲裂的老女人 紧握的火把 吱吱的响 故乡的高梁在燃烧 总得要前行 我咬着牙扔出...
    桔树上阅读 165评论 0 0