1. 程式人生 > 其它 >SpringBoot 傳送郵件

SpringBoot 傳送郵件

1、引入依賴

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

2、配置地址

spring:
  mail:
    # 配置 SMTP 伺服器地址
    host: mail.xxxx.com
    # 傳送者郵箱
    username: [email protected]
    # 配置密碼,注意不是真正的密碼,而是剛剛申請到的授權碼
    password: xxxxxxx
    # 埠號465或587
    port: 
25 # 預設的郵件編碼為UTF-8 default-encoding: UTF-8 # 配置SSL 加密工廠 properties: mail: smtp: socketFactoryClass: javax.net.ssl.SSLSocketFactory #表示開啟 DEBUG 模式,這樣,郵件傳送過程的日誌會在控制檯打印出來,方便排查錯誤 debug: true

3、編寫郵件類

package com.hiscene.has.sys.mail.service.impl;

import com.hiscene.has.sys.mail.service.MailService;
import com.hiscene.util.ThreadPoolUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;


import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.concurrent.ThreadPoolExecutor;

@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    ResourceLoader resourceLoader;
    @Value(
"${spring.mail.username}") private String sender; @SneakyThrows @Override public Boolean sendSimpleMail(String receiver, String subject, String username, String pwd) { try { //建立message MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper
= new MimeMessageHelper(message, true); // //發件人 helper.setFrom( "發郵件中文名稱"+" <"+sender+">"); //收件人 helper.setTo(receiver); //標題 helper.setSubject(subject); HashMap map = new HashMap(); map.put("username", username); //解析模板並替換動態資料,最終username將替換模板檔案中的${username}標籤。 String contents = "<html><body>"+username+"<br>"+ pwd + "</body></html>"; helper.setText(contents, true); //傳送郵件 javaMailSender.send(message); return true; } catch (Exception e) { return false; } } }