栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

Spring boot email(2)

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring boot email(2)

Sending an email with images
public void sendInlineResourceMail(String to, String subject, String content,
    String rscPath, String rscId) throws MessagingException {
 MimeMessage message = mailSender.createMimeMessage();
 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);
    }
@Test
public void senInlineResourceMail() throws MessagingException {
    String imgPath = "";
    String rscId = "***";
    String content = " + rscId
     + "'>";
    mailService.sendInlineResourceMail("***", "test", content, imgPath, rscId);
}
Sending a template email with thymeleaf

Step 1: import dependency.

  • Notice: Do not import thymeleaf until you really start using it.

    org.springframework.boot
    spring-boot-starter-thymeleaf

Step 2: Create an html template




    
    Email


    Hello! Activate account!
    Activate account


Step 3: Send this email

@Test
public void templateMail() throws MessagingException {
    Context context = new Context();
// context.setVariable("id", "006");
    String emailTemplate = templateEngine.process("emailTemplate", context);
    mailService.sendHTMLMail("send to", "test", emailTemplate);
}
Exception handler

Sending an email is usually an asynchronous request. We need to handle the exceptions in the try catch.
So we add a logger in the service.

Step 1: Add Logger as an instance variable.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private final Logger logger = LoggerFactory.getLogger(this.getClass());

Step 2: try catch and print log

public void sendInlineResourceMail(String to, String subject, String content,
String rscPath, String rscId) {
    logger.info("Sending email start: {},{},{},{},{}", to, subject, content, rscPath, rscId);
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    try {
 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("Sending email success!");
    } catch (MessagingException e) {
 logger.error("Sending email failed:",e);
    }
}

Step 3: test

Run the same test method, and we can see the log in the terminal.

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号