Java 技术:SpringBoot 实现邮件发送功能
作者:天使不哭
- 2022 年 8 月 09 日 江苏
本文字数:4128 字
阅读完需:约 14 分钟

目录
1、创建一个基本的SpringBoot项目,pom文件导入发送邮件的依赖
2、application.yml 文件配置配置邮件发送信息
3、创建IEmailService 接口文件,定义邮件发送的接口
4、创建IEmailService接口的实现类EmailService.java 文件
邮件发送功能基本是每个完整业务系统要集成的功能之一,今天小编给大家介绍一下 SpringBoot 实现邮件发送功能,希望对大家能有所帮助!
今天主要给大家分享简单邮件发送、HTML 邮件发送、包含附件的邮件发送三个例子,具体源码链接在文章末尾,有需要的朋友可以自己下载学习一下。
1、创建一个基本的 SpringBoot 项目,pom 文件导入发送邮件的依赖
<!--邮件发送依赖包--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency><!--freemarker制作Html邮件模板依赖包--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>
复制代码
2、application.yml 文件配置配置邮件发送信息
spring:mail:host: smtp.qq.comusername: xxx@qq.com #发件人邮箱password: xxxxx #授权码protocol: smtpproperties.mail.smtp.auth:trueproperties.mail.smtp.port:465#发件邮箱端口properties.mail.display.sendmail: xiaoMingproperties.mail.display.sendname: xiaomingproperties.mail.smtp.starttls.enable:trueproperties.mail.smtp.starttls.required:trueproperties.mail.smtp.ssl.enable:true#是否启用ssldefault-encoding: utf-8#编码格式 freemarker:cache:falsesettings:classic_compatible:truesuffix: .htmlcharset: UTF-8template-loader-path: classpath:/templates/
复制代码
3、创建 IEmailService 接口文件,定义邮件发送的接口
package com.springboot.email.email.service;
import javax.mail.MessagingException;import java.util.List;
public interface IEmailService { /** * 发送简单文本邮件 */ void sendSimpleMail(String receiveEmail, String subject, String content); /** * 发送HTML格式的邮件 */ void sendHtmlMail(String receiveEmail, String subject, String emailContent) throws MessagingException; /** * 发送包含附件的邮件 */ void sendAttachmentsMail(String receiveEmail, String subject, String emailContent, List<String> filePathList) throws MessagingException;}
复制代码
4、创建 IEmailService 接口的实现类 EmailService.java 文件
package com.springboot.email.email.service.impl;
import com.springboot.email.email.service.IEmailService;import org.springframework.beans.factory.annotation.Value;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 javax.annotation.Resource;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import java.io.File;import java.util.List;@Servicepublic class EmailServiceImpl implements IEmailService { @Resource private JavaMailSender mailSender;
@Value("${spring.mail.username}") private String fromEmail;
/** * 发送简单文本邮件 */ public void sendSimpleMail(String receiveEmail, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(fromEmail); message.setTo(receiveEmail); message.setSubject(subject); message.setText(content); mailSender.send(message); } /** * 发送Html格式的邮件 */ public void sendHtmlMail(String receiveEmail,String subject,String emailContent) throws MessagingException { init(receiveEmail, subject, emailContent, mailSender, fromEmail); }
public static void init(String receiveEmail, String subject, String emailContent, JavaMailSender mailSender, String fromEmail) throws MessagingException { MimeMessage message= mailSender.createMimeMessage(); MimeMessageHelper helper=new MimeMessageHelper(message,true); helper.setFrom(fromEmail); helper.setTo(receiveEmail); helper.setSubject(subject); helper.setText(emailContent,true); mailSender.send(message); }
/** * 发送包含附件的邮件 */ public void sendAttachmentsMail(String receiveEmail, String subject, String emailContent, List<String> filePathList) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); //带附件第二个参数true MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(fromEmail); helper.setTo(receiveEmail); helper.setSubject(subject); helper.setText(emailContent, true); //添加附件资源 for (String item : filePathList) { FileSystemResource file = new FileSystemResource(new File(item)); String fileName = item.substring(item.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); } //发送邮件 mailSender.send(message); }}
复制代码
5、新建邮件发送模板 email.html
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"/> <title></title> <style> td { border: black 1px solid; } </style></head><body><h1>工资条</h1><table style="border: black 1px solid;width: 750px"> <thead> <td>序号</td> <td>姓名</td> <td>基本工资</td> <td>在职天数</td> <td>奖金</td> <td>社保</td> <td>个税</td> <td>实际工资</td> </thead> <tbody> <tr> <td>${salary.index}</td> <td>${salary.name}</td> <td>${salary.baseSalary}</td> <td>${salary.inDays}</td> <td>${salary.reward}</td> <td>${salary.socialSecurity}</td> <td>${salary.tax}</td> <td>${salary.actSalary}</td> </tr> </tbody></table></body></html>
复制代码
6、新建测试类,主要代码如下
/** * 测试简单文本文件 */@Testpublic void EmailTest() { emailService.sendSimpleMail("hgmyz@outlook.com", "测试邮件", "springboot 邮件测试");}
@Testpublic void HtmlEmailTest() throws MessagingException { String receiveEmail = "hgmyz@outlook.com"; String subject = "Spring Boot 发送Html邮件测试"; String emailContent = "<h2>您好!</h2><p>这里是一封Spring Boot 发送的邮件,祝您天天开心!<img " + "src='https://p3.toutiaoimg.com/origin/tos-cn-i-qvj2lq49k0/a43f0608912a4ecfa182084e397e4b81?from=pc' width='500' height='300' /></p>" + "<a href='https://programmerblog.xyz' title='IT技术分享设社区' targer='_blank'>IT技术分享设社区</a>"; emailService.sendHtmlMail(receiveEmail, subject, emailContent);}
@Testpublic void templateEmailTest() throws IOException, TemplateException, MessagingException { String receiveEmail = "hgmyz@outlook.com"; String subject = "Spring Boot 发送Templete邮件测试"; //添加动态数据,替换模板里面的占位符 SalaryVO salaryVO = new SalaryVO(1, "小明", 2, 9000.00, 350.06, 280.05, 350.00, 7806.00); Template template = freeMarkerConfigurer.getConfiguration().getTemplate("email.html"); //将模板文件及数据渲染完成之后,转换为html字符串 Map<String, Object> model = new HashMap<>(); model.put("salary", salaryVO); String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); emailService.sendHtmlMail(receiveEmail, subject, templateHtml);}
@Testpublic void emailContailAttachmentTest() throws IOException, TemplateException, MessagingException { String receiveEmail = "hgmyz@outlook.com"; String subject = "Spring Boot 发送包含附件的邮件测试"; //添加动态数据,替换模板里面的占位符 SalaryVO salaryVO = new SalaryVO(1, "小王", 2, 9000.00, 350.06, 280.05, 350.00, 7806.00); Template template = freeMarkerConfigurer.getConfiguration().getTemplate("email.html"); //将模板文件及数据渲染完成之后,转换为html字符串 Map<String, Object> model = new HashMap<>(); model.put("salary", salaryVO); String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); List<String> fileList = new ArrayList<>(); fileList.add("F:\\邮件测试.docx"); fileList.add("F:\\5.png"); fileList.add("F:\\db.jpg"); emailService.sendAttachmentsMail(receiveEmail, subject, templateHtml, fileList);}
复制代码
7、效果截图
简单文版邮件
html 文件
包含附件的邮件
划线
评论
复制
发布于: 刚刚阅读数: 3
版权声明: 本文为 InfoQ 作者【天使不哭】的原创文章。
原文链接:【http://xie.infoq.cn/article/328f647e83c3f9e809fdd6382】。文章转载请联系作者。
天使不哭
关注
热爱技术的程序员 2018.11.08 加入
热爱生活的程序员










评论