SpringBoot实战一:发送邮件

来进行一个SpringBoot项目的实战,发送一下邮件,这里我们先了解一下邮件的协议

邮件协议

  1. SMTP协议:简单邮件传输协议 (Simple Mail Transfer Protocol),邮件从一台服务器传送到另一台服务器
  2. POP3协议:邮局协议版本3(Post Office Protocol - Version 3),将邮件从服务器下载下来,服务器端邮件删除
  3. IMAP协议:邮件访问协议(Internet Mail Access Protocol),将邮件从服务器下载下来,服务器端邮件保留,并且和客户端状态保持一致
  4. Mime协议:多用途互联网邮件扩展类型(Multipurpose Internet Mail Extensions),使二进制传输变简单

引入邮件包

使用Maven引入mail包

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

创建邮件类和测试类,写yml文件

创建一个邮件类:MailService,在类上右键,Go To Test就可以创建测试类了。内容待会慢慢讲,我们先来配置一下配置文件,默认的是application.properties,我比较喜欢yml,所以改为yml,如下:

spring:
  mail:
    host: smtp.qq.com
    username: shuyunquan@qq.com
    password: *******************
    default-encoding: utf-8

host就是啥邮箱,如果是网易的话就自己改为smtp.163.com,其他的就自己改

username就是你的邮箱账号

password是授权码,不是你邮箱的密码,是授权码,在邮箱里面可以获取到,我打码了

最后的编码格式没啥讲的

文本邮件,HTML邮件,附件邮件,图片邮件

package com.vae.springboot.study.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.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 MailService {

    @Value("${spring.mail.username}")
    private String form;

    @Autowired
    private JavaMailSender mailSender;

    //文本邮件
    public void  sendSimpleMail(String to,String subject,String content){
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        simpleMailMessage.setFrom(form);
        mailSender.send(simpleMailMessage);
    }

    //HTML邮件
    public void sendHTMLMail(String to,String subject,String content) throws MessagingException {
        MimeMessage mimeMessage=mailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);
        helper.setFrom(form);
        mailSender.send(mimeMessage);
    }

    //附件邮件
    public void sendAttachmentMail(String to,String subject,String content,String filePath) throws MessagingException {
        MimeMessage mimeMessage=mailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);
        helper.setFrom(form);
        FileSystemResource file=new FileSystemResource(new File(filePath));
        String fileName=file.getFilename();
        helper.addAttachment(fileName,file);
        //helper.addAttachment(fileName+"02",file);  如果是多个附件的话,可以这样写。但是开发中一般都是把filepath做成一个数组,这样在这里遍历就可以了
        //helper.addAttachment(fileName+"03",file);

        mailSender.send(mimeMessage);
    }

    //图片邮件
    public void sendInlineResourceMail(String to,String subject,String content,String rscPath,String rscId) throws MessagingException {
        MimeMessage mimeMessage=mailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);
        helper.setFrom(form);
        FileSystemResource file=new FileSystemResource(new File(rscPath));
        helper.addInline(rscId,file);

        mailSender.send(mimeMessage);
    }
}

都写在这里了,没什么好讲的,测试类也很简单

package com.vae.springboot.study.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    @Resource
    MailService mailService;

    @Test
    public void MailTest(){
        mailService.sendSimpleMail("发给别人@qq.com","文本","这是文本邮件");
    }

    @Test
    public void HtmlMailTest() throws MessagingException {
        String content="<html><body><h3>我是html邮件</h3></body></html>";
        mailService.sendHTMLMail("发给别人@qq.com","HTML",content);
    }

    @Test
    public void AttachmentsMailTest() throws MessagingException {
        String filePath="D:\\error.2019-02-10.log";
        mailService.sendAttachmentMail("发给别人@qq.com","附件","这个是附件邮件",filePath);
    }

    @Test
    public void InlineResourceMailTest() throws MessagingException {
        String imagePath="D:\\Vae.JPG";
        String rscId="Vae";
        String content="<html><body>这是图片邮件<img src=\'cid:"+rscId+"\'></img></body></html>";
        mailService.sendInlineResourceMail("发给别人@qq.com","图片",content,imagePath,rscId);
    }

}

模板邮件

邮件模板这里使用到了thymeleaf技术,上次学的技术终于有一个用处用到了,我们在templates文件夹下面新建一个名为EmailTemplate.html的文件,内容如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>邮件模板</title>
</head>
<body>
      您好,感谢您的注册,这是一封验证邮件,请点击下方链接进行激活,感谢您的支持<br>
      <a href="#" th:href="@{https://www.cnblogs.com/yunquan/?id={id}(id=${id})}">激活账户</a>
</body>
</html>

Nice啊,然后直接在测试类中开战吧,部分代码如下:

    @Resource
    TemplateEngine templateEngine;
    @Test
    public void EmailTemplateTest() throws MessagingException {
        Context context=new Context();
        context.setVariable("id","001");
        String emailContent=templateEngine.process("EmailTemplate",context);
        mailService.sendHTMLMail("她的邮箱@qq.com","模板邮件",emailContent);
    }

点击测试方法运行,结果Nice啊

异常处理

上面写的代码里面我都是把异常直接抛出去了,我之前讲过,异常的throw和return是一样的,都是抛给了上一级,我们的邮件异常不应该抛给上一级的,你错了不能影响我主要程序的运行,有啥错误自己处理就好了。这里我们可以使用try,catch然后错误的详细情况使用日志系统记录下来就可以了,这里不写代码了,很简单

posted @ 2019-02-10 23:58  蜀云泉  阅读(645)  评论(0编辑  收藏  举报