SpringBoot 2.x 封装集成QQ邮箱、网易系邮箱、Gmail邮箱发送邮件

编程入门 行业动态 更新时间:2024-10-11 13:24:03

SpringBoot 2.x 封装集成QQ<a href=https://www.elefans.com/category/jswz/34/1769795.html style=邮箱、网易系邮箱、Gmail邮箱发送邮件"/>

SpringBoot 2.x 封装集成QQ邮箱、网易系邮箱、Gmail邮箱发送邮件

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

项目源码已托管在:Gitee-SpringBoot_Guide

几个名词解释

  • 什么是POP3、SMTP和IMAP?

详细介绍-请移步至网易帮助文档

  • IMAP和POP3有什么区别?

详细介绍-请移步至网易帮助文档

  • 什么是免费邮箱客户端授权码功能?

详细介绍-请移步至网易帮助文档

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

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

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

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

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

详细的配置如下:

spring:mail:host: smtp.126username: xx@126password: xxxxxxxxprotocol: smtpproperties.mail.smtp.auth: trueproperties.mail.smtp.port: 994 #465或者994properties.mail.display.sendmail: Javenproperties.mail.display.sendname: Spring Boot Guide Emailproperties.mail.smtp.starttls.enable: trueproperties.mail.smtp.starttls.required: trueproperties.mail.smtp.ssl.enable: truedefault-encoding: utf-8from: xx@126

特别说明:

126邮箱SMTP服务器地址:smtp.126,端口号:465或者994
163邮箱SMTP服务器地址:smtp.163,端口号:465或者994
yeah邮箱SMTP服务器地址:smtp.yeah,端口号:465或者994


Gmail邮箱配置

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

以上链接需要自行搭梯子,这里不作详述;

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

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

详细的配置如下:

spring:mail:host: smtp.gmailusername:xxx@gmailpassword: xxxxx #Gmail账号密码protocol: smtpproperties.mail.smtp.auth: trueproperties.mail.smtp.port: 465properties.mail.display.sendmail: Javenproperties.mail.display.sendname: Spring Boot Guide Emailproperties.mail.smtp.starttls.enable: trueproperties.mail.smtp.starttls.required: trueproperties.mail.smtp.ssl.enable: truefrom: xxx@gmaildefault-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 {@Autowiredprivate JavaMailSender mailSender;@Value("${spring.mail.from}")private String from;//具体实现请继续向下阅读
}


发送文本邮件

/*** 发送文本邮件* @param to* @param subject* @param content*/@Overridepublic 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);}@Overridepublic 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*/@Overridepublic 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="">
<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=".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 {@Autowiredprivate IMailServiceImpl mailService;//注入发送邮件的各种实现方法@Autowiredprivate TemplateEngine templateEngine;//注入模板引擎@RequestMappingpublic JsonResult index(){try {mailService.sendSimpleMail("xxx@126","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","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>;/span>"+ "        <div\n"+ "            style=\"text-align: center; padding: 10px\"><a style=\"text-decoration: none;\" href=\"\" 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=\".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", "这是一封带附件的邮件", "邮件中有附件,请注意查收!", 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", "这邮件中含有图片", 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", "");String emailContent = templateEngine.process("emailTemp", context);mailService.sendHtmlMail("xxx@126", "这是模板邮件", emailContent);}catch (Exception ex){ex.printStackTrace();return new JsonResult(-1,"邮件发送失败!!");}return new JsonResult();}
}

效果图如下(此处省略)

 

 

更多推荐

SpringBoot 2.x 封装集成QQ邮箱、网易系邮箱、Gmail邮箱发送邮件

本文发布于:2024-03-23 15:02:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1739544.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:邮箱   网易   发送邮件   SpringBoot   Gmail

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!