Java 發送郵件 —— SpringBoot 集成 Java Mail

用途:此文僅供,本身從此的小程序經過郵件,批量通知用戶。html

簡單記錄了一些發送基本郵件的操做。java


項目(SpringBoot版本爲2.1.2.RELEASE):web

核心依賴(其餘相關依賴,在其使用的地方具體說明):spring

<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的註解簡化實體構造):app

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;
}

簡單封裝郵件發送的工具類:spring-boot

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);
    }
}
相關文章
相關標籤/搜索