spring boot 发送邮件

spring boot 发送邮件

在实际的业务中尤其是一些监控报警的模块中是免不了有各种提醒的,最常见的就是报警邮件功能,Spring框架提供了一个简单的抽象,用于使用该JavaMailSender接口发送电子邮件, 并且Spring Boot为其提供自动配置以及启动器模块。

简介:org.springframework。邮件包的根级别的包是Spring框架的电子邮件支持。中央接口发送邮件是MailSender接口
一个简单的值对象封装的属性一个简单的邮件如和(+其他)是SimpleMailMessage类
这个包还包含一个受控异常层次结构提供更高层次的抽象在低水平根异常是MailException邮件系统异常

org.springframework.mail.javamail。JavaMailSender界面添加专业JavaMail特性如MIME消息支持MailSender接口(继承)
JavaMailSender还提供了制备JavaMail MIME消息的回调接口,称为org.springframework.mail.javamail.MimeMessagePreparator

1.使用前的准备工作

1.1  pom文件的依赖引入:

例子中采用了模版生成正文的情况,故此需要引入另一个依赖,thymeleaf模版引擎(具体使用参考我的另一篇文章)

1.2  配置文件的基本配置

2.  具体实现代码:(文本发送、带有静态资源(如图片)、带有附件、利用模版生成邮件内容、html格式等)

2.1  email的实现类

package com.zxl.examples.email;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * Created by Administrator on 2017/7/26.
 */
@Component("emailService")
public class EmailServiceImpl {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

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

    /**
     * 发送文本邮件
     * @param to
     * @param subject
     * @param content
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        try {
            mailSender.send(message);
            logger.info("简单邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常!", e);
        }

    }

    /**
     * 发送html邮件
     * @param to
     * @param subject
     * @param content
     */
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            logger.info("html邮件发送成功");
        } catch (MessagingException e) {
            logger.error("发送html邮件时发生异常!", e);
        }
    }


    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            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);
            //helper.addAttachment("test"+fileName, file);

            mailSender.send(message);
            logger.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送带附件的邮件时发生异常!", e);
        }
    }


    /**
     * 发送正文中有静态资源(图片)的邮件
     * @param to
     * @param subject
     * @param content  ""
     * @param rscPath
     * @param rscId     identifier1234
     */
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
        MimeMessage message = mailSender.createMimeMessage();


        /**
         *
         *  String rscId = "zxl001";
         String content="this is a imgage:

2.2  email的调用类,这里采用的controller方式调用

package com.zxl.examples.controller;

import com.zxl.examples.email.EmailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

/**
 * Created by Administrator on 2017/7/26.
 */
@RestController
public class EmailController {

    @Autowired
    EmailServiceImpl emailService;

    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping("/email/sendSimpleMail")
    public void sendSimpleMail(){
        emailService.sendSimpleMail("zhangxiaolong@weimingedu.com","title","this is a simple email for test.");
    }

    @GetMapping("/email/sendHtmlMail")
    public void sendHtmlMail(){
        String content="\n" +
                "\n" +
                "    

this is a simple email for test.

\n" + "\n" + ""; emailService.sendHtmlMail("zhangxiaolong@weimingedu.com","title",content); } @GetMapping("/email/sendAttachmentsMail") public void sendAttachmentsMail(){ emailService.sendAttachmentsMail("zhangxiaolong@weimingedu.com","title","this is a have attachments email for test.","d:\\桌面.jpg"); } @GetMapping("/email/sendInlineResourceMail") public void sendInlineResourceMail(){ String rscId = "zxl001"; String content="this is a imgage:

2.3  email正文的模版



    
        
   
   
        Title
    
    
        this is a email template,
百度



小提示:1.特别地,某些默认超时值是无限的,您可能需要更改,以避免线程被无响应的邮件服务器阻塞:
spring.mail.properties.mail.smtp.connectiontimeout = 5000
spring.mail.properties.mail.smtp.timeout = 3000
spring.mail.properties.mail.smtp.writetimeout = 5000

2.发送带有内联的静态资源的邮件时有两个地方需要做到一一对应,如下图:

参考资料:http://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/htmlsingle/#mail



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JAVA小男子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值