使用SpringBoot发邮件
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发邮件的更多相关文章
- 带着新人学springboot的应用10(springboot+定时任务+发邮件)
接上一节,环境一样,这次来说另外两个任务,一个是定时任务,一个是发邮件. 1.定时任务 定时任务可以设置精确到秒的准确时间去自动执行方法. 我要一个程序每一秒钟说一句:java小新人最帅 于是,我就写 ...
- spring-boot(六) 邮件服务
学习文章来自:springboot(十):邮件服务 简单使用 1.pom包配置 pom包里面添加spring-boot-starter-mail包引用 <dependencies> < ...
- Springboot】Springboot整合邮件服务(HTML/附件/模板-QQ、网易)
介绍 邮件服务是常用的服务之一,作用很多,对外可以给用户发送活动.营销广告等:对内可以发送系统监控报告与告警. 本文将介绍Springboot如何整合邮件服务,并给出不同邮件服务商的整合配置. 如图所 ...
- 阿里云服务器25端口禁用之如何使用Java发邮件(解决25端口禁用问题)
通常我们在本地使用Java发送邮件,通常是没有问题的,但是部署到服务器的话,就可能遇到问题.当然了,这与运营商也有关系.比如我之前在咖啡主机上购买虚拟机,然后将个人网站部署上去,通常是没有问题的,没有 ...
- Java实现发邮件功能---网易邮箱
目录 Java实现发邮件功能 前言 开发环境 代码 效果 结束语 Java实现发邮件功能 前言 电子邮件的应用场景非常广泛,例如新用户加入,即时发送优惠清单.通过邮件找回密码.监听后台程序,出现异常自 ...
- # PHP - 使用PHPMailer发邮件
PHPMailer支持多种邮件发送方式,使用起来非常简单 1.下载PHPMailer https://github.com/PHPMailer/PHPMailer,下载完成加压后, 把下边的两个文件复 ...
- Linux发邮件之mail命令
一.mail命令 1.配置 vim /etc/mail.rc 文件尾增加以下内容 set from=1968089885@qq.com smtp="smtp.qq.com" set ...
- 测试MailUtils,作用是发邮件
package cn.itcast.test; import java.io.IOException; import javax.mail.MessagingException; import jav ...
- SQL Server定时自动抓取耗时SQL并归档数据发邮件脚本分享
SQL Server定时自动抓取耗时SQL并归档数据发邮件脚本分享 第一步建库和建表 USE [master] GO CREATE DATABASE [MonitorElapsedHighSQL] G ...
随机推荐
- 通过wscript运行的JS脚本,如何引入另一个JS文件
链接: https://helloacm.com/include-external-files-in-vbscriptjscript-wsh/ 代码示例: function Include(jsFil ...
- java:IO流(File,字节流/输入输出流(InputStream(FileInputStream),OutputStream(FileOutStream)),字符流(Reader,Writer))
File: * java.io.File类:代表一个文件或目录. * 常用的构造方法: * File(String pathname)通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例 ...
- Win10无法安装.net framework 3.5出错提示无法安装以下功能该怎么办?
在Windows操作系统中,.NET Framewor对今天应用程序的成功提供了的安全解决方案,它能强化两个安全模型间的平衡.在提供对资源的访问,以便以完成有用的工作,对应用程序的安全性作细致的控制以 ...
- Java网络爬虫
一.前言 首先我们把准备工作做好:IDEA 2019.1.JDK1.8.Maven3.5 Jsoup的Maven依赖: <dependency> <groupId>org.js ...
- Python 用户交互程序(day1)
一: 变量 变:变化,重在变字,量:计量,衡量,表示一种状态 变量赋值 : number = 1 变量的规则: 数字,字母,下划线, 任意组合,数字不能开头,python 的关键字不能用,变量名尽量有 ...
- 快速安装create-react-app脚手架
create-react-app搭建react项目:https://blog.csdn.net/weixin_41077029/article/details/82622106 快速安装create- ...
- [javascript基础]constructor与prototype
最初对js中 object.constructor 的认识: 在学习JS的面向对象过程中,一直对constructor与prototype感到很迷惑,看了一些博客与书籍,觉得自己弄明白了,现在记录如下 ...
- tp5框架用foreach循环时候报Indirect modification of overloaded element of think\paginator\driver\Bootst错误
thinkphp5使用paginator分页查询数据后,需要foreach便利处理某一字段的数据,会出现类似题目的错误.主要是因为tp5使用分页类读取的数据不是纯数组的格式!所以在循环的时候需要用数据 ...
- javaweb:Response/Request的概述 (转发、重定向、get/post)转
请求响应流程图 1]response 1 response概述 response是Servlet.service方法的一个参数,类型为javax.servlet.http.HttpServletR ...
- 140. 后缀数组(hash + 二分 / 后缀数组)
题目链接 : https://www.acwing.com/problem/content/description/142/ Hash + 二分 #include <bits/stdc++.h& ...