无标题文档
人多不足以依赖,要生存只有靠自己。
      深窥自己的心,而后发觉一切的奇迹在你自己。
          凡事皆有终结,因此,耐心是赢得成功的一种手段。

在Spring中提供了非常好用的 JavaMailSender接口实现邮件发送,在SpringBoot的Starter模块中也为此提供了自动化配置。

项目源码已托管在Gitee-SpringBoot_Guide

几个名词解释

Spring Boot中发送邮件步骤

Spring Boot中发送邮件具体的使用步骤如下

  • 1、添加Starter模块依赖
  • 2、添加Spring Boot配置(QQ/网易系/Gmail)
  • 3、调用JavaMailSender接口发送邮件

添加Starter模块依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

添加Spring Boot配置

application.yml中添加邮件相关的配置,这里分别罗列几个常用邮件的配置比如QQ邮箱、网易系邮箱、Gmail邮箱。

QQ邮箱配置

官方配置说明:参考官方帮助中心

获取客户端授权码:参考官方帮助中心

详细的配置如下:

spring:
  mail:
    host: smtp.qq.com #发送邮件服务器
    username: xx@qq.com #QQ邮箱
    password: xxxxxxxxxxx #客户端授权码
    protocol: smtp #发送邮件协议
    properties.mail.smtp.auth: true
    properties.mail.smtp.port: 465 #端口号465或587
    properties.mail.display.sendmail: Javen #可以任意
    properties.mail.display.sendname: Spring Boot Guide Email #可以任意
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8
    from: xx@qq.com #与上面的username保持一致

说明:开启SSL时使用587端口时无法连接QQ邮件服务器

网易系(126/163/yeah)邮箱配置

网易邮箱客户端授码:参考官方帮助中心

客户端端口配置说明:参考官方帮助中心

详细的配置如下:

spring:
  mail:
    host: smtp.126.com
    username: xx@126.com
    password: xxxxxxxx
    protocol: smtp
    properties.mail.smtp.auth: true
    properties.mail.smtp.port: 994 #465或者994
    properties.mail.display.sendmail: Javen
    properties.mail.display.sendname: Spring Boot Guide Email
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8
    from: xx@126.com

特别说明:

  • 126邮箱SMTP服务器地址:smtp.126.com,端口号:465或者994
  • 163邮箱SMTP服务器地址:smtp.163.com,端口号:465或者994
  • yeah邮箱SMTP服务器地址:smtp.yeah.net,端口号:465或者994
Gmail邮箱配置

Gmail 客户端设置说明:参考官方Gmail帮助

以上链接需要自行搭梯子,这里截几张图参考下

image
image
image

总结:
Gmail 发送邮件服务器为:smtp.gmail.com,端口号:465。客户端授权码为Gmail账号的密码,必须使用使用SSL。

还需要开启允许不够安全的应用 ,不然会出现Authentication failed的异常
选择登录与安全滑到底部有个允许不够安全的应用开启即可

详细的配置如下:

spring:
  mail:
    host: smtp.gmail.com
    username:xxx@gmail.com
    password: xxxxx #Gmail账号密码
    protocol: smtp
    properties.mail.smtp.auth: true
    properties.mail.smtp.port: 465
    properties.mail.display.sendmail: Javen
    properties.mail.display.sendname: Spring Boot Guide Email
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    from: xxx@gmail.com
    default-encoding: utf-8

调用JavaMailSender接口发送邮件

常用几种邮件形式接口的封装

import javax.mail.MessagingException;

public interface IMailService {
    /**
     * 发送文本邮件
     * @param to
     * @param subject
     * @param content
     */
    public void sendSimpleMail(String to, String subject, String content);

    public void sendSimpleMail(String to, String subject, String content, String... cc);

    /**
     * 发送HTML邮件
     * @param to
     * @param subject
     * @param content
     * @throws MessagingException
     */
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException;

    public void sendHtmlMail(String to, String subject, String content, String... cc);

    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     * @throws MessagingException
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException;

    public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc);

    /**
     * 发送正文中有静态资源的邮件
     * @param to
     * @param subject
     * @param content
     * @param rscPath
     * @param rscId
     * @throws MessagingException
     */
    public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException;

    public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc);

} 

再写一个组件实现上面的接口并注入JavaMailSender

@Component
public class IMailServiceImpl implements IMailService {
	@Autowired
    private JavaMailSender mailSender;
	@Value("${spring.mail.from}")
    private String from;
	//具体实现请继续向下阅读
}
发送文本邮件
 /**
     * 发送文本邮件
     * @param to
     * @param subject
     * @param content
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    @Override
    public void sendSimpleMail(String to, String subject, String content, String... cc) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setCc(cc);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }
发送html邮件
 /**
     * 发送HTML邮件
     * @param to
     * @param subject
     * @param content
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        mailSender.send(message);
    }

省略实现带有抄送方法的实现

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

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

        mailSender.send(message);
    }

省略实现带有抄送方法的实现

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

        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);
    }

省略实现带有抄送方法的实现

发送模板邮件

发送模板邮件使用的方法与发送HTML邮件的方法一致。只是发送邮件时使用到的模板引擎,这里使用的模板引擎为Thymeleaf

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

模板HTML代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>IJPay让支付触手可及</title>
    <style>
        body {
            text-align: center;
            margin-left: auto;
            margin-right: auto;
        }
        #welcome {
            text-align: center;
            position: absolute;
        }
    </style>
</head>
<body>
<div id="welcome">
    <h3>欢迎使用 <span th:text="${project}"></span> -By <span th:text=" ${author}"></span></h3>
    <span th:text="${url}"></span>
    <div style="text-align: center; padding: 10px">
        <a style="text-decoration: none;" href="#" th:href="@{${url}}" target="_bank">
            <strong>IJPay让支付触手可及,欢迎Start支持项目发展:)</strong>
        </a>
    </div>
    <div style="text-align: center; padding: 4px">
        如果对你有帮助,请任意打赏
    </div>
    <img width="180px" height="180px"
         src="https://oscimg.oschina.net/oscnet/8e86fed2ee9571eb133096d5dc1b3cb2fc1.jpg">
</div>
</body>
</html>

如何使用请看测试中实现的代码。

测试


package com.javen.controller;

import com.javen.email.impl.IMailServiceImpl;
import com.javen.vo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@RestController
@RequestMapping("email")
public class EmailController {

    @Autowired
    private IMailServiceImpl mailService;//注入发送邮件的各种实现方法
    @Autowired
    private TemplateEngine templateEngine;//注入模板引擎

    @RequestMapping
    public JsonResult index(){
        try {
            mailService.sendSimpleMail("xxx@126.com","SpringBoot Email","这是一封普通的SpringBoot测试邮件");
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(-1,"邮件发送失败!!");
        }
        return new JsonResult();
    }

    @RequestMapping("/htmlEmail")
    public JsonResult htmlEmail(){
        try {
            mailService.sendHtmlMail(""xxx@126.com","IJPay让支付触手可及","<body style=\"text-align: center;margin-left: auto;margin-right: auto;\">\n"
                    + "	<div id=\"welcome\" style=\"text-align: center;position: absolute;\" >\n"
                    +"		<h3>欢迎使用IJPay -By Javen</h3>\n"
                    +"		<span>https://github.com/Javen205/IJPay</span>"
                    + "		<div\n"
                    + "			style=\"text-align: center; padding: 10px\"><a style=\"text-decoration: none;\" href=\"https://github.com/Javen205/IJPay\" target=\"_bank\" ><strong>IJPay 让支付触手可及,欢迎Start支持项目发展:)</strong></a></div>\n"
                    + "		<div\n" + "			style=\"text-align: center; padding: 4px\">如果对你有帮助,请任意打赏</div>\n"
                    + "		<img width=\"180px\" height=\"180px\"\n"
                    + "			src=\"https://javen205.gitbooks.io/ijpay/content/assets/wxpay.png\">\n"
                    + "	</div>\n" + "</body>");
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(-1,"邮件发送失败!!");
        }
        return new JsonResult();
    }

    @RequestMapping("/attachmentsMail")
    public JsonResult attachmentsMail(){
        try {
            String filePath = "/Users/Javen/Desktop/IJPay.png";
            mailService.sendAttachmentsMail("xxx@126.com", "这是一封带附件的邮件", "邮件中有附件,请注意查收!", filePath);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(-1,"邮件发送失败!!");
        }
        return new JsonResult();
    }

    @RequestMapping("/resourceMail")
    public JsonResult resourceMail(){
        try {
            String rscId = "IJPay";
            String content = "<html><body>这是有图片的邮件<br/><img src=\'cid:" + rscId + "\' ></body></html>";
            String imgPath = "/Users/Javen/Desktop/IJPay.png";
            mailService.sendResourceMail("xxx@126.com", "这邮件中含有图片", content, imgPath, rscId);

        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(-1,"邮件发送失败!!");
        }
        return new JsonResult();
    }

    @RequestMapping("/templateMail")
    public JsonResult templateMail(){
        try {
            Context context = new Context();
            context.setVariable("project", "IJPay");
            context.setVariable("author", "Javen");
            context.setVariable("url", "https://github.com/Javen205/IJPay");
            String emailContent = templateEngine.process("emailTemp", context);

            mailService.sendHtmlMail("xxx@126.com", "这是模板邮件", emailContent);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(-1,"邮件发送失败!!");
        }
        return new JsonResult();
    }
}

效果图

[接收到的所有邮件
发送普通邮件
发送HTML邮件
发送带有附件的邮件
发送含有图片的邮件
发送模板邮件

源码下载

项目源码已托管在Gitee-SpringBoot_Guide
如果对你有帮助请点击博客下的推荐,欢迎转发

使用 Spring Boot 发送邮件到这里就介绍完了。个人能力有限如有错误欢迎指正。你有更好的解决方案或者建议欢迎一起交流讨论,如有疑问欢迎留言。

参考资料

posted @ 2018-08-27 18:22 酷玩时刻 阅读(2023) 评论(0) 推荐(1) 编辑
摘要: 此项目已开源欢迎Start、PR、发起Issues一起讨论交流共同进步 https://github.com/Javen205/IJPay http://git.oschina.net/javen205/IJPay 微信极速开发系列文章: "点击这里" 上两篇文章介绍了微信 "公众号支付" 以及 " 阅读全文
posted @ 2016-10-16 19:35 酷玩时刻 阅读(2102) 评论(0) 推荐(1) 编辑
摘要: 此项目已开源欢迎Start、PR、发起Issues一起讨论交流共同进步 https://github.com/Javen205/IJPay http://git.oschina.net/javen205/IJPay 微信极速开发系列文章:http://www.jianshu.com/p/a172a1 阅读全文
posted @ 2016-10-16 19:34 酷玩时刻 阅读(4109) 评论(0) 推荐(2) 编辑
摘要: 新博客地址: http://javen205.oschina.io https://javen205.github.io Hexo 是高效的静态站点生成框架,她基于 Node.js。 通过 Hexo 你可以轻松地使用 Markdown 编写文章,除了 Markdown 本身的语法之外,还可以使用 H 阅读全文
posted @ 2016-07-10 20:02 酷玩时刻 阅读(656) 评论(0) 推荐(0) 编辑
摘要: 项目开源地址:http://git.oschina.net/javen205/weixin_guide 微信扫码支付(模式一)你有测试成功吗?如果你看到了这篇文章,我想你是在测试中遇到问题了。OK 那现在我们来看看微信扫码支付中的坑。 原生支付URL参数错误 回调接口URL有回调,但是接收不到参数 阅读全文
posted @ 2016-05-15 13:37 酷玩时刻 阅读(17906) 评论(0) 推荐(0) 编辑
摘要: 微信公众号 1、企业微信公众号 jfinal-qyweixin https://git.oschina.net/javen205/jfinal_qyweixin.git 2、服务号、订阅号 jfinal-weixin https://git.oschina.net/jfinal/jfinal-wei 阅读全文
posted @ 2016-01-19 10:20 酷玩时刻 阅读(2137) 评论(0) 推荐(1) 编辑
摘要: 自学资料总结实现的功能:Java实现Excel导入数据库,如果存在就更新数据库中的数据导入到Excel1、添加jxl.jarmysql-connector-java.1.7-bin.jar包到项目的lib目录下­2、Excel文件目录:D://book.xls3、数据库名:javenforexcel... 阅读全文
posted @ 2014-06-05 16:22 酷玩时刻 阅读(221097) 评论(37) 推荐(23) 编辑
摘要: 欢迎加入群:347245650 345531810进行讨论相互交流 我的微信号:572839485网页授权获取用户基本信息此接口是通过OAuth2.0来完成网页授权的,是安全可靠的。 一、什么是OAuth2.0 OAuth是一个开放协议,允许用户让第三方应用以安全且标准的方式获取该用户在某一... 阅读全文
posted @ 2014-03-05 10:13 酷玩时刻 阅读(54270) 评论(15) 推荐(3) 编辑
摘要: 提问之前在通过电邮、新闻组或者聊天室提出技术问题前,检查你有没有做到: 1.通读手册,试着自己找答案。 2.在FAQ里找答案(一份维护得好的FAQ可以包罗万象:)。 3.在网上搜索(个人推荐google~~~)。 4.向你身边精于此道的朋友打听。描述问题使用含义丰富,描述准确的标题1.谨慎明确的描述症状。 2.提供问题发生的环境(机器配置、操作系统、应用程序以及别的什么)。 3.说明你在提问前是怎样去研究和理解这个问题的。 4.说明你在提问前采取了什么步骤去解决它。 5.有可能和罗列最近做过什么可能有影响的硬件、软件变更。 内容精简,注意质量你需要提供精确有效的信息。这并不是... 阅读全文
posted @ 2012-12-20 14:37 酷玩时刻 阅读(4816) 评论(0) 推荐(0) 编辑
摘要: XmlUtils.javapackage cn.zyw.utils;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.UnsupportedEncodingException;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import or 阅读全文
posted @ 2012-09-15 17:08 酷玩时刻 阅读(3274) 评论(0) 推荐(0) 编辑
摘要: 初始枚举:测试枚举常用的方法如何定义枚举的构造函数、方法和字段,去封装更多的信息展开 1 package com.zhou.enumeration; 2 3 import org.junit.Test; 4 5 public class Enum_test { 6 7 8 @Test 9 public void test(){10 print(Grade.A);11 }12 13 14 //测试枚举常用的方法15 @Test16 public void test2(){17 ... 阅读全文
posted @ 2012-08-30 11:35 酷玩时刻 阅读(243) 评论(0) 推荐(0) 编辑
摘要: 注意:使用beanUtils操纵bean的属性时需要使用到的包有:commons-beanutils-1.8.3.jar commons-logging-1.1.1.jar创建Demo1类来操作Person中的benanView Code Person 1 package com.zyw.beanutils; 2 3 import java.util.Date; 4 5 public class Person { 6 private String name; 7 private String password; 8 private int age; 9 pr... 阅读全文
posted @ 2012-08-29 15:46 酷玩时刻 阅读(533) 评论(0) 推荐(0) 编辑
摘要: 产生乱码的原因: 一般 jsp文件以 utf-8编码存储 而浏览器端默认处理中文使用gb2312编码。 tomcat处理request,response使用 iso-8859-1编码。解决方案: 在page指令中指定如下属性: pageEncoding="UTF-8" 页面使用UTF-8编码 contentType="text/html;charset=gb2312" 页面输出时使用gb2312编码 并在页面中加入以下代码: response.setContentType("text/html;charset=gb2312") (注: 阅读全文
posted @ 2012-08-27 14:21 酷玩时刻 阅读(522) 评论(0) 推荐(0) 编辑
摘要: t io 集群解决方案以及源码解析 0x01 概要说明 本博客是基于老谭 "t io" showcase中的 "tio websocket showcase" 示例来实现集群。看showcase 入门还是挺容易的,入坑(入门)请看老谭写的 "用t io来写一个网页聊天室或客服是个怎样的体验" 。 要 阅读全文
posted @ 2018-09-04 10:40 酷玩时刻 阅读(990) 评论(0) 推荐(0) 编辑
摘要: 前端后台以及游戏中使用Google Protocol Buffer详解 0、什么是protoBuf protoBuf是一种灵活高效的独立于语言平台的结构化数据表示方法,与XML相比,protoBuf更小更快更简单。你可以用定义自己protoBuf的数据结构,用ProtoBuf编译器生成特定语言的源代 阅读全文
posted @ 2018-09-02 13:26 酷玩时刻 阅读(1239) 评论(0) 推荐(1) 编辑
友情链接:快递查询 快递查询
点击右上角即可分享
微信分享提示