Springboot2 整合mail 發送郵件

引入依賴
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
編寫 application.properties 文件
#郵箱服務器
#關於服務器設置 https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=369
spring.mail.host=smtp.qq.com
#郵箱賬戶
[email protected]
#QQ郵箱第三方授權碼
spring.mail.password=第三方授權碼
#編碼類型
spring.mail.default-encoding=UTF-8
具體代碼
package me.yundongis.service.impl;

import me.yundongis.service.MailService;
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 MailServiceImpl implements MailService {

    //注入application.properties中指定的用戶名
    @Value("${spring.mail.username}")
    private String from;

    //用於發送文件
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 發送普通文本郵件
     *
     * @param to      收件人
     * @param subject 主題
     * @param content 內容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);//收信人
        message.setSubject(subject);//主題
        message.setText(content);//內容
        message.setFrom(from);//發信人
        mailSender.send(message);
    }

    /**
     * 發送HTML郵件
     *
     * @param to      收件人
     * @param subject 主題
     * @param content 內容(可以包含<html>等標籤)
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        //使用MimeMessage,MIME協議
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        //MimeMessageHelper幫助我們設置更豐富的內容
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            //true代表支持html
            helper.setText(content, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 發送帶附件的郵件
     *
     * @param to       收件人
     * @param subject  主題
     * @param content  內容
     * @param filePath 附件路徑
     */
    @Override
    public void sendAttachmentMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            //true代表支持多組件,如附件,圖片等
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);//添加附件,可多次調用該方法添加多個附件
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 發送帶圖片的郵件
     *
     * @param to      收件人
     * @param subject 主題
     * @param content 文本
     * @param rscPath 圖片路徑
     * @param rscId   圖片ID,用於在<img>標籤中使用,從而顯示圖片
     */
    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            // 添加圖片
            helper.addInline(rscId, res);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Controller
package me.yundongis.controller;

import me.yundongis.service.impl.MailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class MailController {

    //發送操作
    @Autowired
    private MailServiceImpl mailServiceimpl;

    /**
     * 發送普通郵件
     */
    @RequestMapping("/sendSimpleMail")
    public Object sendSimpleMail() {
        mailServiceimpl.sendSimpleMail("[email protected]", "hello", "this is send mail test");
        return "OK";
    }

    /**
     * 發送HTML郵件
     */
    @RequestMapping("/sendHtmlMail")
    public Object sendHtmlMail() {
        String html = "<h1>Hello</h1>";
        mailServiceimpl.sendHtmlMail("[email protected]", "hello", html);
        return "OK";
    }

    /**
     * 發送帶附件的郵件
     */
    @RequestMapping("/sendAttachmentMail")
    public Object sendAttachmentMail() {
        String html = "<h1>Hello</h1>";
        mailServiceimpl.sendAttachmentMail("[email protected]", "hello", html, "/Users/annie/Documents/ViewSonic VX2478-4K-525.icc");
        return "OK";
    }

    /**
     * 發送帶圖片的郵件
     */
    @RequestMapping("/sendInlineResourceMail")
    public Object sendInlineResourceMail() {
        String rscPath = "/Users/annie/Documents/37401462.jpg";
        String rscId = "001";
        // 這裏的 cid 必須要加
        String content = "<img src='cid:" + rscId + "'>";
        mailServiceimpl.sendInlineResourceMail("[email protected]", "hello", content, rscPath, rscId);
        return "OK";
    }


}


擴展內容
github
個人博客

發佈了30 篇原創文章 · 獲贊 7 · 訪問量 3293
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章