邮件发送关键点
- 使用spring boot 项目,我们可以节约很多的工作,spring boot将一些基础的配置都帮我们约束好了,我们只需要按照标准去配置即可。
- 项目主配置文件配置(application.yml ),这里我将演示三种不同类型的邮箱账号发送邮件:
- QQ 企业邮箱
# QQ企业邮箱 spring: mail: host: smtp.exmail.qq.com # 对应各邮箱官方提示 username: tangz***g@wei***ada.net # 账号 password: ETQpK***gxYGd # 企业邮箱为 客户端专用密码 properties: mail: smtp: auth: true # 使用 starttls: # 使用 SSL 安全协议,必须配置如下 enable: true required: true port: 465 # 端口 protocol: smtps # 协议 # 配置常量 mail: fromMail: addr: tang***ng@w***.net # 发送人 receptionMail: addr: 332***4141@qq.com # 接收人 复制代码
- QQ 普通邮箱 复制代码
# 普通QQ邮箱 spring: mail: host: smtp.qq.com username: 191***933@qq.com # 邮箱账号 password: twuhvbfgndkwbgbf # 授权码(下面将会告诉你怎么申请) properties: mail: smtp: auth: true starttls: enable: true required: true mail: fromMail: addr: 191****33@qq.com 复制代码
- 网易 163 邮箱 复制代码
# 网易 163 邮箱 spring: mail: host: smtp.163.com username: 1****61@163.com # 邮箱登录账号 password: ****. # 邮箱登录密码 mail: fromMail: addr: 1****61@163.com 复制代码
QQ企业邮箱客户端专用码申请(关于申请 QQ企业邮箱不做多的介绍)
- 第一步:登录企业邮箱后点击
设置
并找到客户端设置
确定开启了POP/SMTP
服务。
- 第二步:开启安全登录,并生产
客户端专用密码
。
QQ普通邮箱开启授权码
- 第一步:点击
设置
>账户
,向下拉,找到POOP/SMTP
服务并开启。
- 第二步:点击
生成授权码
,按照官方的提示完成验证即可生成授权码
。
项目pom.xml文件准备
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!--spring boot mail 集成jar--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <!-- 模板引擎 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> 复制代码
mail 服务接口定义
public interface MailService { /** * 发送纯文本邮件 * @param toAddr 发送给谁 * @param title 标题 * @param content 内容 */ public void sendTextMail(String toAddr, String title, String content); /** * 发送 html 邮件 * @param toAddr * @param title * @param content 内容(HTML) */ public void sendHtmlMail(String toAddr, String title, String content); /** * 发送待附件的邮件 * @param toAddr * @param title * @param content * @param filePath 附件地址 */ public void sendAttachmentsMail(String toAddr, String title, String content, String filePath); /** * 发送文本中有静态资源(图片)的邮件 * @param toAddr * @param title * @param content * @param rscPath 资源路径 * @param rscId 资源id (可能有多个图片) */ public void sendInlineResourceMail(String toAddr, String title, String content, String rscPath, String rscId); } 复制代码
服务接口的实现
@Component public class MailServiceImpl implements MailService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JavaMailSender mailSender; // 注入常量 @Value("${mail.fromMail.addr}") private String from; /** * 发送文本邮件 * @param toAddr * @param title * @param content */ @Override public void sendTextMail(String toAddr, String title, String content) { // 纯文本邮件对象 SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(toAddr); message.setSubject(title); message.setText(content); try { mailSender.send(message); logger.info("Text邮件已经发送。"); } catch (Exception e) { logger.error("发送Text邮件时发生异常!", e); } } /** * 发送html邮件 * @param toAddr * @param title * @param content */ @Override public void sendHtmlMail(String toAddr, String title, String content) { // html 邮件对象 MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(toAddr); helper.setSubject(title); helper.setText(content, true); mailSender.send(message); logger.info("html邮件发送成功"); } catch (MessagingException e) { logger.error("发送html邮件时发生异常!", e); } } /** * 发送带附件的邮件 * @param toAddr * @param title * @param content * @param filePath */ public void sendAttachmentsMail(String toAddr, String title, String content, String filePath){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(toAddr); helper.setSubject(title); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); //helper.addAttachment("test"+fileName, file); mailSender.send(message); logger.info("带附件的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送带附件的邮件时发生异常!", e); } } /** * 发送正文中有静态资源(图片)的邮件 * @param toAddr * @param title * @param content * @param rscPath * @param rscId */ public void sendInlineResourceMail(String toAddr, String title, String content, String rscPath, String rscId){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(toAddr); helper.setSubject(title); helper.setText(content, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); logger.info("嵌入静态资源的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送嵌入静态资源的邮件时发生异常!", e); } } } 复制代码
测试类
@RunWith(SpringRunner.class) @SpringBootTest public class BasemailApplicationTests { @Value("${mail.receptionMail.addr}") private String receptionMailAddr; @Autowired private MailService mailService; @Autowired private TemplateEngine templateEngine; /** * 测试 文本邮件 * @throws Exception */ @Test public void testSimpleMail() throws Exception { mailService.sendTextMail(receptionMailAddr,"测试文本邮箱发送","你好你好!"); } /** * 测试 html 邮箱 * @throws Exception */ @Test public void testHtmlMail() throws Exception { String content="<html>\n" + "<body>\n" + " <h3>hello world ! 这是一封html邮件!</h3>\n" + "</body>\n" + "</html>"; mailService.sendHtmlMail(receptionMailAddr,"test simple mail",content); } @Test public void sendAttachmentsMail() { String filePath="C:\\\\Users\\\\Administrator\\\\Desktop\\\\java并发学习.txt"; mailService.sendAttachmentsMail(receptionMailAddr, "主题:带附件的邮件", "有附件,请查收!", filePath); } @Test public void sendInlineResourceMail() { String rscId = "neo006"; String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>"; String imgPath = "C:\\\\Users\\\\Administrator\\\\Desktop\\\\testMail.png"; mailService.sendInlineResourceMail(receptionMailAddr, "主题:这是有图片的邮件", content, imgPath, rscId); } @Test public void sendTemplateMail() { //创建邮件正文 Context context = new Context(); context.setVariable("id", "006"); // 传递 emailTemplate.html 模板需要的值,并将模板转换为 String String emailContent = templateEngine.process("emailTemplate", context); mailService.sendHtmlMail(receptionMailAddr,"主题:这是模板邮件",emailContent); } }