springboot(六)Email demo

项目中经常使用邮件发送提醒功能,比如说更新安全机制,发送邮件通知用户等

一、简单邮件发送

导入依赖:

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

application配置信息

#邮件发送
#邮箱服务器地址
spring.mail.host=smtp.163.com
# 设置用户名
spring.mail.username=xxxxxx@qq.com
# 设置密码
spring.mail.password=XXXXXXX
spring.mail.default-encoding=UTF-8
mail.from=${spring.mail.username}
mail.to=xxxxxx@qq.com

163的服务器信息如下:需要登录163设置个人邮箱配置打开SMTP

接收服务器pop3.163.com
发送服务器smtp.163.com

简单邮件发送:

@Slf4j
@Component
public class JavaSimpleEmailSend {


    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${mail.from}")
    private String from;

    @Value("${mail.to}")
    private String to;

    public void sendSimpleMail(String subject, String content) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        javaMailSender.send(mailMessage);
        log.info("sendSimpleMail 已发送!");
    }

Test:

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

    @Autowired
    JavaSimpleEmailSend simpleEmailSend;

    @Test
    public void simpleEmailSend(){
        simpleEmailSend.sendSimpleMail("Springboot test sendSimpleMail","hello! myselef!");
    }

带HTMl邮件发送

public void sendHtmlMail(String subject, String content) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            javaMailSender.send(message);
            log.info("html邮件发送成功");
        } catch (MessagingException e) {
            log.error("sendHtmlMail发送html邮件时发生异常!", e);
        }
    }

test:

@Test
    public void sendHtmlMail(){
        String context = "<html>
" +
                                "<body>
" +
                                    "<h3>hello! myselef!</h3>
" +
                                "</body>
" +
                        "</html>";
        simpleEmailSend.sendHtmlMail("Springboot test sendHtmlMail",context);
    }

带附件的邮件发送

public void sendAttachmentsMail(String subject, String content,String filePath) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            //根据文件路径获取文件
            FileSystemResource file = new FileSystemResource(new File(filePath));
            //获取文件名
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);//添加附件
            //添加附件2
            String fileName2 = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName2, file);//添加附件2
            javaMailSender.send(message);
            log.info("带附件的邮件已经发送成功");
        } catch (MessagingException e) {
            log.error("sendAttachmentsMail发送带附件的邮件时发生异常!", e);
        }
    }

test:

@Test
    public void sendAttachmentsMail(){
        String context = "<html>
" +
                "<body>
" +
                "<h3>hello! myselef!</h3>
" +
                "</body>
" +
                "</html>";
        String filePath = "D:\img\D0145151.img";
        simpleEmailSend.sendAttachmentsMail("Springboot test sendAttachmentsMail",context,filePath);
}

带静态资源的邮件发送

public void sendInlineResourceMail(String subject, String content,String filePath,String contentId) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            //根据文件路径获取文件
            FileSystemResource file = new FileSystemResource(new File(filePath));
            helper.addInline(contentId,file);//添加静态资源

            //添加多个静态资源
            FileSystemResource file2 = new FileSystemResource(new File(filePath));
            helper.addInline(contentId,file2);//添加静态资源

            javaMailSender.send(message);
            log.info("嵌入静态资源的邮件已经发送成功");
        } catch (MessagingException e) {
            log.error("sendInlineResourceMail发送嵌入静态资源的邮件时发生异常!", e);
        }
    }

test:

@Test
    public void sendInlineResourceMail(){
        String context = "<html>
" +
                "<body>
" +
                "<h3>hello! myselef!</h3>
" +
                "</body>
" +
                "</html>";
        String filePath = "D:\img\D0145151.img";
        String contentId= "D0145151";
        simpleEmailSend.sendInlineResourceMail("Springboot test sendInlineResourceMail",context,filePath,contentId);
}

邮件系统

上面发送邮件的基础服务就这些了,但是如果我们要做成一个邮件系统的话还需要考虑以下几个问题:

邮件模板

我们会经常收到这样的邮件:

尊敬的XXX用户:
                  
              恭喜您注册成为xxx网的用户,,同时感谢您对xxx的关注与支持并欢迎您使用xxX的产品与服务。
        ...

其中只有XXX这个用户名在变化,其它邮件内容均不变,如果每次发送邮件都需要手动拼接的话会不够优雅,并且每次模板的修改都需要改动代码的话也很不方便,因此对于这类邮件需求,都建议做成邮件模板来处理。模板的本质很简单,就是在模板中替换变化的参数,转换为html字符串即可,这里以 thymeleaf为例来演示。

1、pom中导入thymeleaf的包

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

2、在resorces/templates下创建emailTemplate.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
        您好,这是验证邮件,请点击下面的链接完成验证,<br/>
        <a href="#" th:href="@{https://www.cnblogs.com/flgb/p/{id}(id=${id}).html }">验证账号</a>
</body>
</html>

3、解析模板并发送

@Autowired
    private TemplateEngine templateEngine;
    @Test
    public void sendTemplateMail()
    {
        //创建邮件正文
        Context context = new Context();
        context.setVariable ("id", "12866522");
        String emailContent = templateEngine.process("emailTemplate", context);
        simpleEmailSend.sendHtmlMail("Springboot test sendTemplateMail", emailContent);
}

发送失败

因为各种原因,总会有邮件发送失败的情况,比如:邮件发送过于频繁、网络异常等。在出现这种情况的时候,我们一般会考虑重新重试发送邮件,会分为以下几个步骤来实现:

  • 1、接收到发送邮件请求,首先记录请求并且入库。
  • 2、调用邮件发送接口发送邮件,并且将发送结果记录入库。
  • 3、启动定时系统扫描时间段内,未发送成功并且重试次数小于3次的邮件,进行再次发送

异步发送

很多时候邮件发送并不是我们主业务必须关注的结果,比如通知类、提醒类的业务可以允许延时或者失败。这个时候可以采用异步的方式来发送邮件,加快主交易执行速度,在实际项目中可以采用MQ发送邮件相关参数,监听到消息队列之后启动发送邮件。

sendTemplateMail
原文地址:https://www.cnblogs.com/flgb/p/12866522.html