邮件发送
原生java-mail进行邮件发送; 前提:先登录邮箱,开启POP3/SMTP服务,使第三方可以使用授权码登录邮箱。
@Test
public void sendEmail(){
String account="[email protected]";
String pwd="KXNZHOZDMLTVWHOZ";
//设置SMTP请求头
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 连接协议
properties.put("mail.smtp.host", "smtp.163.com");// QQ smtp.qq.com
properties.put("mail.smtp.port", 465);// 默认端口号 25
properties.put("mail.smtp.auth", "true");//服务端认证。
properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
String to="[email protected]";
//会话对象
Session s = Session.getDefaultInstance(properties);
try {
Message msg = new MimeMessage(s);
msg.setFrom(new InternetAddress(account));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
msg.addRecipient(Message.RecipientType.CC,new InternetAddress(account));
msg.setSubject("今日新闻");
msg.setText("飓风来袭");
//邮差对象
Transport transport = s.getTransport();
transport.connect(account,pwd);
transport.sendMessage(msg,msg.getAllRecipients());
} catch (Exception e) {
e.printStackTrace();
}
}
spring封装的spring-mail组件; 项目开发中我们选择sprng中封装的mail组件,使用简单方便。
-
添加mail启动器
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
-
yml中配置登录邮箱,授权码,端口,ssl等。
spring: mail: protocol: smtp host: smtp.163.com port: 465 username: [email protected] password: SYRZLRNOCSLFQJKA properties: mail: smtp: auth: true ssl: enable: true
-
测试邮件发送
import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import javax.annotation.Resource; import javax.mail.internet.MimeMessage; import java.io.File; @SpringBootTest public class TestEmail { @Resource private JavaMailSender mailSender; @Resource private MailProperties mailProperties; //发送简单文本邮箱 @Test public void springJavaSendMail() throws Exception { String to="[email protected]"; MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper h = new MimeMessageHelper(msg); h.setFrom(mailProperties.getUsername()); h.addTo(to); h.addCc(mailProperties.getUsername()); h.setSubject("纯文本邮件发送测试"); h.setText("使用Springboot-JvaMailSenderImpl工具类来发送文本邮件"); mailSender.send(msg); } //发送html文本,不带图片 @Test public void sendSimpleHtmlEmail() throws Exception { String to="[email protected]"; MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper h = new MimeMessageHelper(msg); h.setFrom(mailProperties.getUsername()); h.addTo(to); h.addCc(mailProperties.getUsername()); h.setSubject("html文本邮件发送测试"); String content="使用Springboot-JvaMailSenderImpl工具类来发送文本邮件" + "<br>" + "<h1>标题</h1>"+ "<div style='width:50%;height:100px;border:1px solid black'>我是div标签</div>"; h.setText(content,true); mailSender.send(msg); } //发送html文本,带网络图片 @Test public void sendSimpleHtmlEmailAndImg() throws Exception { String to="[email protected]"; MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper h = new MimeMessageHelper(msg); h.setFrom(mailProperties.getUsername()); h.addTo(to); h.addCc(mailProperties.getUsername()); h.setSubject("html文本邮件发送带图片"); //图片地址两种写法:网络图片;本地图片 String content="<h1>使用Springboot-JvaMailSenderImpl工具类来发送文本邮件</h1>" + "<div style='width:50%;height:100px;border:1px solid black'>我是div标签</div>" + "<img src='https://t7.baidu.com/it/u=1881842538,2998806722&fm=193&f=GIF'/>"; h.setText(content,true); mailSender.send(msg); } //发送html文本,带本地图片 @Test public void sendSimpleHtmlEmailAndImg2() throws Exception { String to="[email protected]"; MimeMessage msg = mailSender.createMimeMessage(); //支持文件上传 MimeMessageHelper h = new MimeMessageHelper(msg,true); h.setFrom(mailProperties.getUsername()); h.addTo(to); h.addCc(mailProperties.getUsername()); h.setSubject("html文本邮件发送带图片"); //图片地址两种写法:网络图片;本地图片 String content="使用Springboot-JvaMailSenderImpl工具类来发送文本邮件" + "<br>" + "<div style='width:50%;height:100px;border:1px solid black'>我是div标签</div>" + "<img src='cid:ei'/>"; h.setText(content,true); //自动把本地图片上传的服务器,作为网络图片 h.addInline("ei",new File("E:/test2.jpg")); mailSender.send(msg); } //发送html文本,带本地图片,带附件 @Test public void sendSimpleHtmlEmailAndImg2AndAttach() throws Exception { String to="[email protected]"; MimeMessage msg = mailSender.createMimeMessage(); //支持文件上传 MimeMessageHelper h = new MimeMessageHelper(msg,true); h.setFrom(mailProperties.getUsername()); h.addTo(to); h.addCc(mailProperties.getUsername()); h.setSubject("html文本邮件发送带图片"); //图片地址两种写法:网络图片;本地图片 String content="使用Springboot-JvaMailSenderImpl工具类来发送文本邮件" + "<br>" + "<div style='width:50%;height:100px;border:1px solid black'>我是div标签</div>" + "<img style='width:50%;height:50%' src='cid:ei'/>"; h.setText(content,true); //自动把本地图片上传的服务器,作为网络图片 h.addInline("ei",new File("E:/test2.jpg")); File f = new File("E:/demo.txt"); h.addAttachment(f.getName(),f); mailSender.send(msg); } }
封装工具类
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; @Component public class EmailUtil { private final static Logger log = LogManager.getLogger(EmailUtil.class); @Resource private JavaMailSender mailSender; @Resource private MailProperties mailProperties; public void sendEmail(String email, String title, String count) { sendEmail(email, title, count, null); } public void sendEmail(String email, String title, String count, File... files) { MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper h = new MimeMessageHelper(msg); try { h.setFrom(mailProperties.getUsername()); h.addTo(email); h.addCc(mailProperties.getUsername()); h.setSubject(title); h.setText(count,true); if (files != null && files.length > 0) { for (File f : files) { //如果是图片,单独上传显示 if (isImage(f)) { h.addInline("ei",f); } //图片也单独再上传为附件 h.addAttachment(f.getName(), f); } } mailSender.send(msg); } catch (MessagingException e) { log.error(e); } } //判断文件是否是图片类型 private boolean isImage(File file) { try { Image image = ImageIO.read(file); return image != null; } catch (IOException e) { return false; } } }
使用thymeleaf引擎重置密码邮件
-
添加thymeleaf启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
-
在templates目录下添加html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>点击如下链接重置密码,此链接有效期10分钟,如过期,请回到主页重新点击忘记密码!</h3>
<h3 th:text="${参数名}"></h3>
<!--服务端页面;前端vue页面-->
<a th:href="@{http://localhost:8080/resetpwd(t=${token})}">点我重置</a>
</body>
</html>
-
使用Thymeleaf引擎对象解析resetPwdEmail.html模板
@Resource
private TemplateEngine engine;
//基于thymeleaf模板引擎,解析html模板,生成html文本,
@Test
public void sendSimpleHtmlEmail2() throws Exception {
Context c = new Context();
c.setVariable("参数名","值");
c.setVariable("token", "xxxxxxx");
String html = engine.process("html文件名", c);
}
-
把解析后的html字符串发送指定邮箱即可