100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > exchange无法收发邮件_SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送

exchange无法收发邮件_SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送

时间:2021-09-13 23:41:00

相关推荐

exchange无法收发邮件_SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送

SpringBoot2.x系列教程69--SpringBoot中整合邮件发送

作者:一一哥

注:

本文案例以QQ邮箱发送的实现为例!

一. 邮件发送概述

1. 概述

在Spring框架中提供了一个JavaMailSender接口,可以实现发送邮件功能。

而在Spring Boot中提供了一个对应的spring-boot-starter-mail依赖,添加该依赖后,Spring Boot将创建一个默认的JavaMailSender,该sender可以通过spring.mail命名空间下的配置项进一步自定义。

2. 发送邮件的场景

用户通过邮件注册激活;通过邮件找回密码;通过邮件发送系统情况;通过邮件发送报表信息等。

3. 常用邮箱系统提供商

126邮箱SMTP服务器地址:,端口号:465或者994163邮箱SMTP服务器地址:,端口号:465或者994qq邮箱SMTP服务器地址:,端口号:465或587yeah邮箱SMTP服务器地址:,端口号:465或者994

4. QQ邮箱开启SMTP功能

为了保障用户邮箱的安全,QQ邮箱设置了POP3/SMTP/IMAP的开关。系统默认情况下相关设置是“关闭”状态的,在用户需要这些功能时请先“开启”,才可以用客户端软件收发邮件。

QQ邮箱开启SMTP功能步骤

默认情况下,SMTP服务器功能没有开启,所以需要在“设置”-->"账号"-->"POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务"中对SMTP进行开启。

可以看到默认情况下并没有开启SMTP服务。

点击开启按钮就可以了,但是前提条件是你QQ邮箱绑定了手机号码,因为开启时需要发送短信验证码。

开启成功后,会有一个授权码,这个授权码就是我们进行邮件发送时的邮箱密码,可以把它记住,不记也可以。因为这个授权码可以多次生成,只要用的时候发一次短信验证码,就可以得到一个新的授权码了。

关于126或者163邮箱授权码的获取过程,与QQ类似,不一一列举。

二. Spring Boot整合邮件发送实现步骤

1. 创建web项目

我们按照之前的经验,创建一个web程序,并将之改造成Spring Boot项目,具体过程略。

2. 添加依赖包

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

3. 创建application.yml配置文件

spring:#freemarker模板配置freemarker:template-loader-path: classpath:/templates/#spring.freemarker.prefix=suffix: .ftlcache: falsecharset: utf-8check-template-location: truecontent-type: text/html#邮件配置 mail:host: from: 2312119590@username: 2312119590@#这里要替换成自己的邮箱授权码password: xxxxxxprotocol: smtpdefault-encoding: UTF-8#以下可以不配置properties:mail:smtp:auth: truestarttls:enable: truerequired: true

QQ邮箱配置

## QQ邮箱配置spring:mail:host: #发送邮件服务器username: 2312119590@ #发送邮件的邮箱地址password: xxx #客户端授权码,不是邮箱密码,在qq邮箱设置里面自动生成from: 2312119590@ # 发送邮件的地址,和上面username一致protocol: smtpdefault-encoding: UTF-8#以下可以配置或者不配置properties:mail:smtp:port: 465 #端口号465或587auth: truestarttls:enable: truerequired: true

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

spring:mail:host: #发送邮件服务器username: xx@ #发送邮件的邮箱地址password: xxxxxxx #客户端授权码,不是邮箱密码,网易的是自己设置的properties.mail.smtp.port: 994 #465或者994from: xxx@ # 发送邮件的地址,和上面username一致default-encoding: UTF-8#以下可以配置或者不配置properties:mail:smtp:port: 465 #端口号465或994auth: truestarttls:enable: truerequired: true

4. 定义发送邮件的服务类

定义邮件发送接口IMailService

package com.yyg.boot.mail;/*** @Author 一一哥Sun* @Date Created in /4/20* @Description 封装一个发邮件的接口,方便后边直接调用.*/public interface IMailService {/*** 发送文本邮件** @param to收件人* @param subject 主题* @param content 内容*/void sendSimpleMail(String to, String subject, String content);/*** 发送HTML邮件** @param to收件人* @param subject 主题* @param content 内容*/void sendHtmlMail(String to, String subject, String content);/*** 发送带附件的邮件** @param to 收件人* @param subject 主题* @param content 内容* @param filePath 附件*/void sendAttachmentsMail(String to, String subject, String content, String filePath);/*** 发送模板邮件* @param to 收件人* @param subject 主题* @param fileName 邮件模板文件名称* @param model 邮件数据载体*/void sendModelMail(String to, String subject, String fileName, Object model);}

定义邮件发送实现类IMailServiceImpl

package com.yyg.boot.mail.impl;import com.yyg.boot.mail.IMailService;import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.FileSystemResource;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.stereotype.Service;import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import java.io.IOException;import java.util.Objects;/*** @Author 一一哥Sun* @Date Created in /4/20* @Description Description*/@Slf4j@Servicepublic class IMailServiceImpl implements IMailService {/*** Spring Boot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用*/@Autowiredprivate JavaMailSender mailSender;@Autowiredprivate Configuration configuration;/*** 配置文件中我的qq邮箱*/@Value("${spring.mail.from}")private String from;/*** 简单文本邮件** @param to收件人* @param subject 主题* @param content 内容*/@Overridepublic void sendSimpleMail(String to, String subject, String content) {//创建SimpleMailMessage对象SimpleMailMessage message = new SimpleMailMessage();//邮件发送人message.setFrom(from);//邮件接收人message.setTo(to);//邮件主题message.setSubject(subject);//邮件内容message.setText(content);//发送邮件mailSender.send(message);}/*** html邮件** @param to收件人* @param subject 主题* @param content 内容*/@Overridepublic void sendHtmlMail(String to, String subject, String content) {//获取MimeMessage对象MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper messageHelper;try {messageHelper = new MimeMessageHelper(message, true);//邮件发送人messageHelper.setFrom(from);//邮件接收人messageHelper.setTo(to);//邮件主题message.setSubject(subject);//邮件内容,html格式messageHelper.setText(content, true);//发送mailSender.send(message);//日志信息log.info("邮件已经发送...");} catch (MessagingException e) {log.error("发送邮件时发生异常!", e);}}/*** 带附件的邮件* @param to 收件人* @param subject 主题* @param content 内容* @param filePath 附件*/@Overridepublic void sendAttachmentsMail(String to, String subject, String content, String filePath) {MimeMessage message = mailSender.createMimeMessage();try {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));ClassPathResource resource = new ClassPathResource(filePath);FileSystemResource file = new FileSystemResource(resource.getFile());helper.addAttachment(Objects.requireNonNull(file.getFilename()), file);//可以同时添加多个附件,只需要在这里直接添加第2,第3...附件就行了.//helper.addAttachment(fileName2, file2);mailSender.send(message);//日志信息log.info("邮件已经发送...");} catch (MessagingException e) {log.error("发送邮件时发生异常!", e);} catch (IOException e) {e.printStackTrace();log.error("发送邮件时发生异常!", e);}}@Overridepublic void sendModelMail(String to, String subject, String fileName, Object model) {MimeMessage mimeMessage = mailSender.createMimeMessage();try {MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);helper.setFrom(from);helper.setTo(to);helper.setSubject(subject);Template template = configuration.getTemplate(fileName);String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);helper.setText(html, true);mailSender.send(mimeMessage);//日志信息log.info("邮件已经发送...");} catch (MessagingException e) {log.error("发送邮件时发生异常!", e);} catch (TemplateException e) {e.printStackTrace();log.error("发送邮件时发生异常!", e);} catch (IOException e) {e.printStackTrace();}}}

5. 定义实体类

package com.yyg.boot.entity;import lombok.Data;import java.util.Date;/*** @Author 一一哥Sun* @Date Created in /4/20* @Description Description*/@Datapublic class Employee {/*** 员工编号*/private Long id;/*** 员工名称*/private String username;/*** 合同期限*/private Integer contractTerm;/*** 员工薪水*/private Double salary;/*** 合同起始日期*/private Date beginContract;/*** 合同截至日期*/private Date endContract;/*** 部门名称*/private String departmentName;/*** 职位名称*/private String posName;}

6. 创建入口类

package com.yyg.boot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/*** @Author 一一哥Sun* @Date Created in /4/20* @Description Description*/@SpringBootApplicationpublic class MailApplication {public static void main(String[] args){SpringApplication.run(MailApplication.class,args);}}

7. 创建Controller接口

7.1 定义发送简单邮件的接口方法:

@GetMapping("/simple")public String sendSimpleMail() {iMailService.sendSimpleMail("收件箱@", "邮件标题", "邮件内容.....机密");return "success";}

启动程序进行测试

邮件发送成功:

去目标邮箱的收件箱中进行查看,可以看到如下邮件内容,说明邮件发送成功!

7.2定义发送html格式邮件的接口方法:

@GetMapping("/html")public String sendHtmlMail() {iMailService.sendHtmlMail("收件箱@", "邮件主题", "<h1>邮件主题</h1><br/><p><font color='red'>邮件内容</font></p>");return "success";}

邮件发送成功:

去目标邮箱的收件箱中进行查看,可以看到如下邮件内容,说明邮件发送成功!

7.3创建发送带附件的邮件接口方法:

@GetMapping("/attachment")public String sendAttachmentMail() {iMailService.sendAttachmentsMail("收件箱@", "主题:带附件的邮件", "有附件的邮件,不要错过哦...", "static/touxiang.png");return "success";}

注意:

我这里是把附件直接放到了项目的resource/static目录下了,我们也可以存放到桌面等位置。

邮件发送成功:

然后去目标邮箱的收件箱中进行查看,可以看到如下邮件内容,说明邮件发送成功!

7.4创建发送模板邮件的接口方法:

首先利用FreeMarker创建页面模板。

<p>${username}--你好,欢迎加入XXX大家庭!您的入职信息如下:</p><table border="1" cellspacing="0"><tr><td><strong style="color: #F00">工号</strong></td><td>${id}</td></tr><tr><td><strong style="color: #F00">合同期限</strong></td><td>${contractTerm}年</td></tr><tr><td><strong style="color: #F00">员工薪资</strong></td><td>${salary}/月(美元)</td></tr><tr><td><strong style="color: #F00">合同起始日期</strong></td><td>${beginContract?string("yyyy-MM-dd")}</td></tr><tr><td><strong style="color: #F00">合同截至日期</strong></td><td>${endContract?string("yyyy-MM-dd")}</td></tr><tr><td><strong style="color: #F00">所属部门</strong></td><td>${departmentName}</td></tr><tr><td><strong style="color: #F00">职位</strong></td><td>${posName}</td></tr></table><p><strong style="color: #F00; font-size: 24px;">希望在未来的日子里,携手共进!</strong></p>

别忘了在application.yml文件中对freemarker进行配置:

spring:freemarker:template-loader-path: classpath:/templates/#spring.freemarker.prefix=suffix: .ftlcache: falsecharset: utf-8check-template-location: truecontent-type: text/html

创建接口方法

@PostMapping("/model")public String sendModelMail(@RequestBody Employee employee) {iMailService.sendModelMail("收件箱@", "主题:新员工入职欢迎邮件--模板邮件", "mail.ftl", employee);return "success";}

在postman中进行接口测试

然后去目标邮箱的收件箱中进行查看,可以看到如下邮件内容,说明邮件发送成功!

8. Controller完整代码

package com.yyg.boot.web;import com.yyg.boot.entity.Employee;import com.yyg.boot.mail.IMailService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;/*** @Author 一一哥Sun* @Date Created in /4/20* @Description Description*/@RestController@RequestMapping("/mail")public class MailController {@Autowiredprivate IMailService iMailService;@GetMapping("/simple")public String sendSimpleMail() {iMailService.sendSimpleMail("309733895@", "邮件标题", "邮件内容.....机密");return "success";}@GetMapping("/html")public String sendHtmlMail() {iMailService.sendHtmlMail("309733895@", "邮件主题", "<h1>邮件主题</h1><br/><p><font color='red'>邮件内容</font></p>");return "success";}@GetMapping("/attachment")public String sendAttachmentMail() {iMailService.sendAttachmentsMail("309733895@", "主题:带附件的邮件", "有附件的邮件,不要错过哦...", "static/touxiang.png");return "success";}@PostMapping("/model")public String sendModelMail(@RequestBody Employee employee) {iMailService.sendModelMail("309733895@", "主题:新员工入职欢迎邮件--模板邮件", "mail.ftl", employee);return "success";}}

9. 完整项目结构

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。