Springboot 快速實(shí)現(xiàn)郵件發(fā)送功能


本文主要介紹如何使用SpringBoot自帶的spring-boot-starter-mail實(shí)現(xiàn)郵件發(fā)送功能
(支持文本格式郵件、html格式郵件、帶有多附件的郵件、帶有多資源的郵件)

1. 引入依賴(lài)包

在pom.xml中引入spring-boot-starter-mail依賴(lài)包

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

2. 配置郵件發(fā)送參數(shù)

在application.properties中加入如下參數(shù):

spring.mail.host=smtp.xxx.com
spring.mail.username=xxx@xxx.com
spring.mail.password=xxxxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

如果是application.yml,如下:

spring:
  mail:
    host: smtp.xxx.com
    username: xxx@xxx.com
    password: xxxxxx
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

3. 添加代碼發(fā)送郵件

/**
 * 注入MailSender
 */
@Autowired
private JavaMailSender mailSender;

/**
 * 讀取配置文件中的發(fā)送用戶(hù)信息
 */
@Value("${spring.mail.username}")
private String fromEmail;

發(fā)送文本格式郵件:

SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromEmail);

/**
 * 收件人郵件地址
 */
message.setTo(toEmail);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);

發(fā)送Html格式/帶有多附件/帶有多資源的郵件:

MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromEmail);
helper.setTo(toEmail);
helper.setSubject(subject);
helper.setText(mailBody, true);

/**
 * 判斷附件是否為空
 */
if(!StringUtils.isEmpty(photos)){
    /**
     * 多附件處理
     */
    photos.entrySet().forEach(entry->{
        try {
            FileSystemResource file = new FileSystemResource(new File(entry.getValue()));
            
            if(isAttachment) {
                helper.addAttachment(entry.getKey(), file);
            }else {
                helper.addInline(entry.getKey(),file);
            }
        } catch (MessagingException e) {
            e.printStackTrace();
            mailSenderModal.setCode(-2);
            mailSenderModal.setMsg(e.getMessage());
        }
        
    });
    
}

mailSender.send(message);

源碼參考地址:

https://github.com/futurebox/SpringBoot/tree/master/MailSender

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容