SpringBoot中已有发邮件的工具包,只需要引用即可使用

1,pom引用

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

2,在配置文件中配置邮件服务器信息。这里需要一个可用的邮件服务器。

spring.mail.default-encoding=utf-8
spring.mail.host=mail.xxxx.com
spring.mail.username=xxxx@xxxx.com
spring.mail.password=password

3,编写发邮件service,调用JavaMailSender.send()即可,支持简单文本邮件、富文本邮件、html邮件

Service代码如下

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service; import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File; @Service
public class EmailService {
@Autowired
private JavaMailSender mailSender; @Value("${spring.mail.username}")
private String from; /**
* 发送简单文本邮件
* @param content 邮件正文
* @param subject 邮件主题
* @param to 邮件接收地址
* */
public void sendSimpleMail(String to, String subject, String content) throws MailException {
System.out.println("-----from:" + from);
System.out.println("-----to:" + to);
System.out.println("-----subject:" + subject);
System.out.println("-----content:" + content); SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
} /**
* 发送富文本邮件
* @param content 邮件正文
* @param rscId 设置在header头中的文件ID
* @param rscPath 图片路径
* @param subject 邮件主题
* @param to 邮件接收地址
* */
public void sendRichTextMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException {
//MimeMessageHelper支持发送复杂邮件模板,支持文本、附件、HTML、图片等。
//如果需要发送多张图片,可以改变传参方式,使用集合添加多个<img src='cid:rscId'>和helper.addInline(rscId, res);即可实现 MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
File file = new File(rscPath);
FileSystemResource res = new FileSystemResource(file);
helper.addInline(rscId, res); mailSender.send(message); } /**
* 发送HTML邮件
* @param to 邮件接收地址
* @param subject 邮件主题
* @param content 邮件正文
* */
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
//true 表⽰示需要创建⼀一个 multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
}
}

controller测试代码

 import com.hyp.emailtest.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import javax.mail.MessagingException; @RestController
@RequestMapping("Mail")
public class EmailController { @Autowired
private EmailService emailService; //发送简单文本邮件
@RequestMapping(value = "send", method = RequestMethod.GET)
public void Send() {
String To = "test@xxxx.com";
String Subject = "Java发邮件测试";
String Content = "这是一封来自JavaMailSender自动发送的测试邮件";
try {
emailService.sendSimpleMail(To, Subject, Content);
System.out.println("发送成功");
} catch (MailException ex) {
System.out.println("发送失败");
System.out.println(ex.toString());
}
} //发送富文本邮件
@RequestMapping(value = "sendImg", method = RequestMethod.GET)
public void SendWithImg() {
String to = "test@xxxx.com";
String subject = "Java发邮件测试";
String rscId = "img1";
String content = "<html><body><img width='250px' src=\'cid:" + rscId + "\'></body></html>";
//图片路径,这里要写绝对路径
String imgPath = "E:\\11.jpg";
try {
emailService.sendRichTextMail(to, subject, content, imgPath, rscId);
System.out.println("发送成功");
} catch (MessagingException ex) {
System.out.println("发送失败");
System.out.println(ex.toString());
}
} //发送HTML邮件
@RequestMapping(value = "sendHtml", method = RequestMethod.GET)
public void SendWithHtml() {
String to = "test@xxxx.com";
String subject = "Java发邮件测试";
String content = "<html><head></head><body><h3>这是html邮件。。。</h3></body></html>";
try {
emailService.sendHtmlMail(to, subject, content);
System.out.println("发送成功");
} catch (MessagingException ex) {
System.out.println("发送失败");
System.out.println(ex.toString());
}
}
}

在controller中要注意的是,需要把EmailService注入,不能实例化,否则在Service类中@Value()注解会找不到spring.mail.username的值,

原因请参考:https://stackoverflow.com/questions/39047333/spring-boot-value-properties

我的理解是,手动实例化(new)类的实例是JVM做的事情,SpringBoot并没有参与,所以Value注解将被忽略,字段自然取不到值。

还有被注解的字段不能是static,SpringBoot依赖注入不支static的变量注入。原因是Spring依赖注入的底层原理还是利用反射方式来创建对象。而static修饰的字段、变量在JVM加载类的时候就已经创建,存在于方法区,是类的属性而不是对象的属性,Spring是基于对象层面的依赖注入。

使用SpringBoot发邮件的更多相关文章

  1. 带着新人学springboot的应用10(springboot+定时任务+发邮件)

    接上一节,环境一样,这次来说另外两个任务,一个是定时任务,一个是发邮件. 1.定时任务 定时任务可以设置精确到秒的准确时间去自动执行方法. 我要一个程序每一秒钟说一句:java小新人最帅 于是,我就写 ...

  2. spring-boot(六) 邮件服务

    学习文章来自:springboot(十):邮件服务 简单使用 1.pom包配置 pom包里面添加spring-boot-starter-mail包引用 <dependencies> < ...

  3. Springboot】Springboot整合邮件服务(HTML/附件/模板-QQ、网易)

    介绍 邮件服务是常用的服务之一,作用很多,对外可以给用户发送活动.营销广告等:对内可以发送系统监控报告与告警. 本文将介绍Springboot如何整合邮件服务,并给出不同邮件服务商的整合配置. 如图所 ...

  4. 阿里云服务器25端口禁用之如何使用Java发邮件(解决25端口禁用问题)

    通常我们在本地使用Java发送邮件,通常是没有问题的,但是部署到服务器的话,就可能遇到问题.当然了,这与运营商也有关系.比如我之前在咖啡主机上购买虚拟机,然后将个人网站部署上去,通常是没有问题的,没有 ...

  5. Java实现发邮件功能---网易邮箱

    目录 Java实现发邮件功能 前言 开发环境 代码 效果 结束语 Java实现发邮件功能 前言 电子邮件的应用场景非常广泛,例如新用户加入,即时发送优惠清单.通过邮件找回密码.监听后台程序,出现异常自 ...

  6. # PHP - 使用PHPMailer发邮件

    PHPMailer支持多种邮件发送方式,使用起来非常简单 1.下载PHPMailer https://github.com/PHPMailer/PHPMailer,下载完成加压后, 把下边的两个文件复 ...

  7. Linux发邮件之mail命令

    一.mail命令 1.配置 vim /etc/mail.rc 文件尾增加以下内容 set from=1968089885@qq.com smtp="smtp.qq.com" set ...

  8. 测试MailUtils,作用是发邮件

    package cn.itcast.test; import java.io.IOException; import javax.mail.MessagingException; import jav ...

  9. SQL Server定时自动抓取耗时SQL并归档数据发邮件脚本分享

    SQL Server定时自动抓取耗时SQL并归档数据发邮件脚本分享 第一步建库和建表 USE [master] GO CREATE DATABASE [MonitorElapsedHighSQL] G ...

随机推荐

  1. 【ABAP系列】SAP ABAP 关于FUNCTION-POOL的理解

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[ABAP系列]SAP ABAP 关于FUNCT ...

  2. echarts 饼图-->如何修改legend模板?

    首先需要在初始化图表的方法中过滤一下数据 ,将你需要的 名称  所占百分比 所占数量  筛选出来 let dataFilter = [ { value: 20, name: "未知" ...

  3. vue2 学习笔记

    一.部署环境1.安装nodeJS -- 地址:https://nodejs.org/zh-cn/ 2.安装vue脚手架 (用于创建VUE项目的) 进入项目文件或者新建一个文件 npm install ...

  4. C语言作业11

    问题 答案 这个作业属于那个课程 C语言程序设计 这个作业要求在哪里 https://www.cnblogs.com/galen123/p/11996995.html 我在这个课程的目标是 在学好C语 ...

  5. springboot笔记-文件上传

    使用 Spring Boot 和 Thymeleaf 上传文件 Spring Boot 利用 MultipartFile 的特性来接收和处理上传的文件,本示例前端页面使用 Thymeleaf 来处理. ...

  6. noip2015day2-运输计划

    题目描述 公元$ 2044 $年,人类进入了宇宙纪元. \(L\) 国有 \(n\) 个星球,还有 \(n-1\) 条双向航道,每条航道建立在两个星球之间,这 \(n-1\) 条航道连通了 \(L\) ...

  7. git diff 命令用法

    理解git diff的前提,首先要理解git中工作区,暂存区,本地版本库的概念,如果头脑中有这些概念,接着往下读. git diff test.c 用来查看工作区和暂存区中test.c文件的区别. g ...

  8. allure 这么高大上的测试报告环境,5 分钟搞定

    allure 的测试报告是老板喜欢的样子.如果能用上 allure,干嘛还选择其他的测试报告类型呢?python 的 pytest 单元测试框架有 allure 的插件,可以很方便的在 python ...

  9. PropertyUtilsBean 将bean转成map

    public static Map<String,String> beanToMap(Object bean) { Map<String,String> params =Map ...

  10. setTimeout定时器

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...