首頁 > 軟體

Spring Boot整合郵箱傳送郵件範例

2022-02-18 16:00:14

1. 準備工作

登入進自己的 qq 郵箱獲取授權碼

設定 – 賬戶 – POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務

點選開始獲取授權碼,將授權碼儲存下來,下面程式碼整合的時候需要使用

2. 程式碼整合

建立一個 Spring Boot 專案,引入以下依賴

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

組態檔

server:
  port: 8080
spring:
  # email 設定
  mail:
    # SMTP 伺服器地址
    host: smtp.qq.com
    username: # 你的qq 郵箱地址
    password: # 授權碼,上面從 qq 郵箱官網得到的授權碼
    port: 587
    protocol: smtp
    default-encoding: UTF-8

建立一個郵件收件人資訊的實體類

/**
 * @author lishisen
 * @description 郵件收件人資訊
 * @date 2022/1/9 9:37
 **/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class EmailModel implements Serializable {

    // 收件人郵箱地址
    private String receiveEmailAddress;
    // 郵箱主題
    private String emailTheme;
    // 郵件內容
    private String emailContent;

}

建立一個服務提供類,SendEmailService.java

/**
 * @author lishisen
 * @description 郵件傳送服務類
 * @date 2022/1/9 9:40
 **/
@Slf4j
@Component
public class SendEmailService {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private JavaMailSenderImpl javaMailSenderImpl;

    // 傳送者地址
    private String posterAddress = "1876419736@qq.com";
    // 傳送者名稱
    private String posterName = "測試郵件傳送";

    /**
     * 文字傳送
     **/
    public void sendEmailAsText(final EmailModel emailModel) {
        System.out.println(emailModel.toString());
        MimeMessagePreparator mimeMessagePreparator = mimeMessage -> {
            mimeMessage.setFrom(posterAddress);
            mimeMessage.setRecipients(Message.RecipientType.TO, emailModel.getReceiveEmailAddress());
            mimeMessage.setText("傳送者地址:" + posterAddress + 'n'
                    + "傳送者名稱:" + posterName + 'n'
                    + "內容:" + emailModel.getEmailContent());
        };
        try {
            this.javaMailSender.send(mimeMessagePreparator);
            log.info("郵箱已返送至[{}]郵箱!", emailModel.getReceiveEmailAddress());
        } catch (MailException e) {
            log.error("郵箱異常:{}", e);
        }
    }

    /**
     * html 網頁傳送
     * 該方法為同步方法
     **/
    public void sendEmailAsSysExceptionHtml(final EmailModel emailModel, String info) {
        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
        MimeMessageHelper mimeMessageHelper;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(posterAddress);
            mimeMessageHelper.setTo(emailModel.getReceiveEmailAddress());
            mimeMessageHelper.setSubject(emailModel.getEmailTheme());
            mimeMessageHelper.setText(
                    "<!DOCTYPE html>n" +
                            "<html lang="en">n" +
                            "<head>n" +
                            "    <meta charset="UTF-8">n" +
                            "    <title>Title</title>n" +
                            "</head>n" +
                            "<body>n" +
                            "<h2>" + info + "</h2>n" +
                            "<h3>您的驗證碼為:<span style='color: red'" + ">" +
                            emailModel.getEmailContent() +
                            "</span> " + ",請在 5 分鐘內進行驗證</h3>n" +
                            "</body>n" +
                            "</html>"
                    , true);
            this.javaMailSender.send(mimeMessage);
            log.info("郵箱已返送至[{}]郵箱!", emailModel.getReceiveEmailAddress());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

測試使用

@Autowired
private SendEmailService sendEmailService;
@Test
public void sendMailTest() {
    // 建立收件人實體類,封裝收件人的資訊
    EmailModel emailModel = new EmailModel();
    emailModel.setReceiveEmailAddress("18xxxxxqq.com");
    emailModel.setEmailTheme("測試傳送");
    emailModel.setEmailContent("測試傳送郵箱主體資訊內容");
    // 呼叫傳送服務方法執行傳送任務
    sendEmailService.sendEmailAsText(emailModel);
    System.out.println("郵件傳送成功");
}

總結

到此這篇關於Spring Boot整合郵箱傳送郵件範例的文章就介紹到這了,更多相關Spring Boot郵箱傳送內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com