1. 程式人生 > >SpringBoot配置傳送郵件

SpringBoot配置傳送郵件

Java程式碼

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;
import java.util.Date;

@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String from; // 發件人

    @Value("${spring.mail.to}")
    private String toStr; // 收件人

    @Value("${spring.mail.cc}")
    private String ccStr; // 抄送人

    /**
     * 傳送純文字郵件
     * @param subject 標題
     * @param content 內容
     */
    public void sendSimpleMail(String subject, String content) {

        String[] to = toStr.split(",");
        String[] cc = ccStr == null || "".equals(ccStr) ? null : ccStr.split(",");

        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(from);
        message.setTo(to);
        if (cc != null && cc.length > 0) {
            message.setCc(cc);
        }
        message.setSubject(subject);
        message.setText(content);

        sender.send(message);

    }

    /**
     * 傳送帶html的郵件
     * @param subject 標題
     * @param text html片段
     * @param imgPath html片段中圖片路徑
     */
    public void senderHtmlMail(String subject, String text, String imgPath) throws MessagingException {

        String[] to = toStr.split(",");
        String[] cc = ccStr == null || "".equals(ccStr) ? null : ccStr.split(",");

        MimeMessage msg = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true);

        helper.setFrom(from);
        helper.setTo(to);
        if (cc != null && cc.length > 0) {
            helper.setCc(cc);
        }
        helper.setSubject(subject);
        helper.setSentDate(new Date());
        helper.setText(text, true);

        if (imgPath != null && !"".equals(imgPath)) {
            FileSystemResource res = new FileSystemResource(new File(imgPath));
            helper.addInline("imagePicId", res);
        }

        sender.send(msg);

    }
}
html模版(使用freemark)

引入依賴

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

Java程式碼

// 郵件html拼接
Map<String, Object> model = new HashMap<>();
model.put("timeSpanStr", year + "年 第" + weekNum + "周 " + timeSpan);
//讀取 html 模板
Template template = freeMarkerConfigurer.getConfiguration().getTemplate("mail.html");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); // html片段
EmailUtil.senderHtmlMail(... ... // 呼叫傳送郵件方法
配置檔案
#郵件配置
spring.mail.host= smtp.126.comspring.mail.username= elf***@126.com
spring.mail.password= *** ***
spring.mail.default-encoding= UTF-8
spring.mail.port= 25
spring.mail.to= elf***@126.com
spring.mail.cc=

注意:部分郵箱需要設定開啟POP3/SMTP授權服務,在郵箱設定中進行設定

部分SpringBoot的jar中已整合mail,如未引入jar需在pom.xml中引入依賴

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