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

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

前言

做大学毕设的时候,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

后记

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

目录
相关文章
|
28天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
41 0
|
7天前
|
安全 Java 应用服务中间件
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
24 0
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
|
9天前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
【Spring系列】Sping VS Sping Boot区别与联系
|
2月前
|
消息中间件 JSON Java
如何利用springboot + rabbitmq发送邮件?
RabbitMQ相关知识请参考: RabbitMQ消息确认、消息持久化等核心知识总结 - 简书
29 2
|
2月前
|
Java
【Java专题_03】使用springboot发送邮件
【Java专题_03】使用springboot发送邮件
|
2月前
|
XML 监控 druid
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
|
3月前
|
安全 Java 数据安全/隐私保护
SpringBoot+Email发送邮件
邮件通知是现代应用中常见的一种通信方式,特别是在需要及时反馈、告警或重要事件通知的场景下。Spring Boot提供了简单而强大的邮件发送功能,使得实现邮件通知变得轻而易举。本文将研究如何在Spring Boot中使用JavaMailSender实现邮件发送,以构建一个可靠的通知体系。
67 0
SpringBoot+Email发送邮件
|
3月前
|
Java
springboot项目打包瘦身
springboot项目打包瘦身
|
4月前
|
Java
SpringBoot项目发送邮件
SpringBoot项目发送邮件
47 1
|
5月前
|
Java 测试技术 Maven
Spring Boot发送邮件
Spring Boot发送邮件