Java 发送邮件 —— SpringBoot 集成 Java Mail

用途:此文仅供,自己今后的小程序通过邮件,批量通知用户。

简单记录了一些发送基本邮件的操作。


项目(SpringBoot版本为2.1.2.RELEASE):

核心依赖(其他相关依赖,在其使用的地方具体说明):

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

application.yml——邮件发送相关配置:

spring:
  mail:
    host: smtp.qq.com
    username: ***@qq.com
    password: ***  #qq邮箱开启POP3/SMTP服务后,生成的授权码
    receiver: ***@qq.com
    protocol: smtp
    default-encoding: utf-8

邮件实体类(使用Lombok的注解简化实体构造):

import lombok.Data;
import org.springframework.core.io.FileSystemResource;

@Data
public class MailBean {
    private String subject;

    private String text;

    private FileSystemResource file;

    private String attachmentFilename;

    private String contentId;
}

简单封装邮件发送的工具类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;

@Component
public class MailUtil {
    private final JavaMailSender mailSender;

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

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

    @Autowired
    public MailUtil(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendMailSimple() {
        SimpleMailMessage mimeMessage = new SimpleMailMessage();
        mimeMessage.setFrom(sender);
        mimeMessage.setTo(receiver);
        mimeMessage.setSubject("主题");
        mimeMessage.setText("正文");
        mailSender.send(mimeMessage);
    }

    private void sendMail(MailBean mailBean, boolean html, boolean multipart) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart);
            helper.setFrom(sender);
            helper.setTo(receiver);
            helper.setSubject(mailBean.getSubject());
            helper.setText(mailBean.getText(), html);

            if (mailBean.getFile() != null) {
                helper.addAttachment(mailBean.getAttachmentFilename(), mailBean.getFile());
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        mailSender.send(mimeMessage);
    }

    public void sendMail(MailBean mailBean) {
        sendMail(mailBean, true, true);
    }

    public void sendMailText(MailBean mailBean) {
        sendMail(mailBean, false, false);
    }

    public void sendMailHtml(MailBean mailBean) {
        sendMail(mailBean, true, false);
    }

    public void sendMailInline(MailBean mailBean) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        try {
            helper.setFrom(sender);
            helper.setTo(receiver);
            helper.setSubject(mailBean.getSubject());

            helper.setText(mailBean.getText(), true);
            helper.addInline(mailBean.getContentId(), mailBean.getFile());
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        mailSender.send(mimeMessage);
    }
}

单元测试就不写了,忘记怎么写了。发送测试:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;

@RestController
public class MailController {
    private final MailUtil mailUtil;
    private final TemplateEngine templateEngine;

    @Autowired
    public MailController(MailUtil mailUtil, TemplateEngine templateEngine) {
        this.mailUtil = mailUtil;
        this.templateEngine = templateEngine;
    }

    @GetMapping("/simple")
    public void simple() {
        MailBean mailBean = new MailBean();
        mailBean.setSubject("简单纯文本邮件测试");
        mailBean.setText("内容");
        mailUtil.sendMailText(mailBean);
//        mailUtil.sendMailSimple();
    }

    @GetMapping("/html")
    public void html() {
        MailBean mailBean = new MailBean();
        mailBean.setSubject("简单html代码,邮件测试");
        mailBean.setText("<h1>表达个意思</h1>");
        mailUtil.sendMailHtml(mailBean);
    }

    @GetMapping("/attachment")
    public void attachment() {
        String path = "classpath:反.jpg";
        try {
            File file = ResourceUtils.getFile(path);
            FileSystemResource fileSystemResource = new FileSystemResource(file);

            MailBean mailBean = new MailBean();
            mailBean.setSubject("主题");
            mailBean.setText("内容");
            mailBean.setAttachmentFilename(file.getName());
            mailBean.setFile(fileSystemResource);
            mailUtil.sendMail(mailBean);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    使用模板引擎,此处为thymeleaf
     */
    @GetMapping("/template")
    public void template() {
        MailBean mailBean = new MailBean();
        mailBean.setSubject("主题");

        Context context = new Context();
        context.setVariable("username", "pinecone");
        String content = templateEngine.process("template", context);
        mailBean.setText(content);
        mailUtil.sendMail(mailBean);
    }
}

 

posted @ 2019-02-06 18:26  不抛弃,不放弃  阅读(1197)  评论(0编辑  收藏  举报