溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot?Mail郵件任務怎么配置

發(fā)布時間:2022-05-23 09:12:32 來源:億速云 閱讀:344 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“SpringBoot Mail郵件任務怎么配置”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

    一、引言

    發(fā)送郵件應該是網(wǎng)站的必備功能之一,什么注冊驗證,忘記密碼或者是給用戶發(fā)送營銷信息。最早期的時候我們會使用JavaMail相關(guān)api來寫發(fā)送郵件的相關(guān)代碼,后來spring退出了JavaMailSender更加簡化了郵件發(fā)送的過程,在之后springboot對此進行了封裝就有了現(xiàn)在的spring-boot-starter-mail。

    二、簡單使用

    1、pom包配置

    pom包里面添加spring-boot-starter-mail包引用

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

    2、在application.properties中添加郵箱配置

    spring.mail.host=smtp.1234.163.com //郵箱服務器地址
    spring.mail.username=5678@oo.com //用戶名
    spring.mail.password=09876 //密碼
    spring.mail.default-encoding=UTF-8
    mail.fromMail.addr=65432@oo.com //以誰來發(fā)送郵件

    3、編寫mailService,這里只提出實現(xiàn)類。

    @Component
    public class MailServiceImpl implements MailService{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private JavaMailSender mailSender;
    @Value("${mail.fromMail.addr}")
    private String from;
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    try {
    mailSender.send(message);
    logger.info("簡單郵件已經(jīng)發(fā)送。");
    } catch (Exception e) {
    logger.error("發(fā)送簡單郵件時發(fā)生異常!", e);
    }
    }
    }

    4、編寫test類進行測試

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class MailServiceTest {
    @Autowired
    private MailService MailService;
    @Test
    public void testSimpleMail() throws Exception {
    MailService.sendSimpleMail("123456w@126.com","test simple mail"," hello this is simple mail");
    }
    }

    至此一個簡單的文本發(fā)送就完成了。

    三、加點料

    但是在正常使用的過程中,我們通常在郵件中加入圖片或者附件來豐富郵件的內(nèi)容,下面講介紹如何使用springboot來發(fā)送豐富的郵件。

    3、發(fā)送html格式郵件

    其它都不變在MailService添加sendHtmlMail方法.

    public void sendHtmlMail(String to, String subject, String content) {
    MimeMessage message = mailSender.createMimeMessage();
    try {
    //true表示需要創(chuàng)建一個multipart message
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    
    mailSender.send(message);
    logger.info("html郵件發(fā)送成功");
    } catch (MessagingException e) {
    logger.error("發(fā)送html郵件時發(fā)生異常!", e);
    }
    }

    在測試類中構(gòu)建html內(nèi)容,測試發(fā)送:

    @Test
    public void testHtmlMail() throws Exception {
    String content="<html>\n" +
    "<body>\n" +
    " <h4>hello world ! 這是一封Html郵件!</h4>\n" +
    "</body>\n" +
    "</html>";
    MailService.sendHtmlMail("ityouknow@126.com","test simple mail",content);
    }

    3、發(fā)送帶附件的郵件

    在MailService添加sendAttachmentsMail方法.

    public void sendAttachmentsMail(String to, String subject, String content, String filePath){
    MimeMessage message = mailSender.createMimeMessage();
    try {
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    
    FileSystemResource file = new FileSystemResource(new File(filePath));
    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    helper.addAttachment(fileName, file);
    
    mailSender.send(message);
    logger.info("帶附件的郵件已經(jīng)發(fā)送。");
    } catch (MessagingException e) {
    logger.error("發(fā)送帶附件的郵件時發(fā)生異常!", e);
    }
    }

    添加多個附件可以使用多條 helper.addAttachment(fileName, file)

    4、在測試類中添加測試方法

    @Test
    public void sendAttachmentsMail() {
    String filePath="e:\\tmp\\application.log";
    mailService.sendAttachmentsMail("ityouknow@126.com", "主題:帶附件的郵件", "有附件,請查收!", filePath);
    }

    5、發(fā)送帶靜態(tài)資源的郵件

    郵件中的靜態(tài)資源一般就是指圖片,在MailService添加sendAttachmentsMail方法.

    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
    MimeMessage message = mailSender.createMimeMessage();
    try {
    MimeMessageHelper 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);
    logger.info("嵌入靜態(tài)資源的郵件已經(jīng)發(fā)送。");
    } catch (MessagingException e) {
    logger.error("發(fā)送嵌入靜態(tài)資源的郵件時發(fā)生異常!", e);
    }
    }

    在測試類中添加測試方法:

    @Test
    public void sendInlineResourceMail() {
    String rscId = "12345";
    String content="<html><body>這是有圖片的郵件:<img src=\'cid:" + rscId + "\' ></body></html>";
    String imgPath = "C:\\Users\\summer\\Pictures\\favicon.png";
    mailService.sendInlineResourceMail("ityouknow@126.com", "主題:這是有圖片的郵件", content, imgPath, rscId);
    }

    添加多個圖片可以使用多條 <img src='cid:" + rscId + "' > 和 helper.addInline(rscId, res) 來實現(xiàn)
    到此所有的郵件發(fā)送服務已經(jīng)完成了。

    郵件系統(tǒng):

    上面發(fā)送郵件的基礎(chǔ)服務就這些了,但是如果我們要做成一個郵件系統(tǒng)的話還需要考慮以下幾個問題:

    郵件模板:

    我們會經(jīng)常收到這樣的郵件:
    尊敬的neo用戶:
    恭喜您注冊成為xxx網(wǎng)的用戶,,同時感謝您對xxx的關(guān)注與支持并歡迎您使用xx的產(chǎn)品與服務。
    ...
    其中只有neo這個用戶名在變化,其它郵件內(nèi)容均不變,如果每次發(fā)送郵件都需要手動拼接的話會不夠優(yōu)雅,并且每次模板的修改都需要改動代碼的話也很不方便,因此對于這類郵件需求,都建議做成郵件模板來處理。模板的本質(zhì)很簡單,就是在模板中替換變化的參數(shù),轉(zhuǎn)換為html字符串即可,這里以thymeleaf為例來演示。

    四、pom中導入thymeleaf的包

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

    五、在resorces/templates下創(chuàng)建emailTemplate.html

    <!DOCTYPE html>
    <html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8"/>
    <title>Title</title>
    </head>
    <body>
    您好,這是驗證郵件,請點擊下面的鏈接完成驗證,
    
    <a href="#" rel="external nofollow"  th:href="@{ http://www.i123456w.com/neo/{id}(id=${id}) }" rel="external nofollow" >激活賬號</a>
    </body>
    </html>

    六、解析模板并發(fā)送

    @Test
    public void sendTemplateMail() {
    //創(chuàng)建郵件正文
    Context context = new Context();
    context.setVariable("id", "006");
    String emailContent = templateEngine.process("emailTemplate", context);
    
    mailService.sendHtmlMail("ityouknow@126.com","主題:這是模板郵件",emailContent);
    }

    1、發(fā)送失敗

    因為各種原因,總會有郵件發(fā)送失敗的情況,比如:郵件發(fā)送過于頻繁、網(wǎng)絡(luò)異常等。在出現(xiàn)這種情況的時候,我們一般會考慮重新重試發(fā)送郵件,會分為以下幾個步驟來實現(xiàn):

    • 1、接收到發(fā)送郵件請求,首先記錄請求并且入庫。

    • 2、調(diào)用郵件發(fā)送接口發(fā)送郵件,并且將發(fā)送結(jié)果記錄入庫。

    • 3、啟動定時系統(tǒng)掃描時間段內(nèi),未發(fā)送成功并且重試次數(shù)小于3次的郵件,進行再次發(fā)送

    七、異步發(fā)送

    很多時候郵件發(fā)送并不是我們主業(yè)務必須關(guān)注的結(jié)果,比如通知類、提醒類的業(yè)務可以允許延時或者失敗。這個時候可以采用異步的方式來發(fā)送郵件,加快主交易執(zhí)行速度,在實際項目中可以采用MQ發(fā)送郵件相關(guān)參數(shù),監(jiān)聽到消息隊列之后啟動發(fā)送郵件。

    “SpringBoot Mail郵件任務怎么配置”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI