SpringBoot send mail function to achieve

background

There is a small partner asked me before you send mail function how to get. Then I gave him found a demo, just have to write about this, for everyone to share.

Sort out the pain points

Send e-mail, we can think about, a place where the pit?
I think it was three.
First: Mail whitelist problem.
Second: the mail-out problems.
Third: e-mail with an attachment problem.
The following demo I will describe these problems and solutions.

Implementation

Ready to work

We need to prepare a mail can be sent, I have here in my 163 mailbox, for example, now send regular mail asking you to enter something called an authorization code, note that this thing is not password.
The step of obtaining authorization code:



When ON is selected, can be obtained after the verification by the verification code. Reset selected codes can also be obtained. 17 years ago when he wrote a demo, now 19 years and opened a, because the previous forgot.

SpringBoot project to introduce e-mail package

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

yml configure mail-related

spring:
  mail:
    # 邮件服务地址
    host: smtp.163.com
    # 端口,可不写默认
    port: 25
    # 编码格式
    default-encoding: utf-8
    # 用户名
    username: [email protected]
    # 授权码,就是我们刚才准备工作获取的代码
    password: xxx
    # 其它参数
    properties:
      mail:
        smtp:
          # 如果是用 SSL 方式,需要配置如下属性,使用qq邮箱的话需要开启
          ssl:
            enable: true
            required: true
          # 邮件接收时间的限制,单位毫秒
          timeout: 10000
          # 连接时间的限制,单位毫秒
          connectiontimeout: 10000
          # 邮件发送时间的限制,单位毫秒
          writetimeout: 10000

For timeout problems in the above mentioned, capture timeout exception can be resolved.

Send Mail Tools

Mainly to meet the needs java to send mail through the following tools. When we were good yml configuration, SpringBoot will help us to automatically configure JavaMailSender us through this java class can be achieved operating java to send mail. Here are several common mail.

@Service
public class MailService {
    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    private static final String SENDER = "[email protected]";

    /**
     * 发送普通邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendSimpleMailMessge(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(SENDER);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常!", e);
        }
    }

    /**
     * 发送 HTML 邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendMimeMessge(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(SENDER);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            logger.error("发送MimeMessge时发生异常!", e);
        }
    }

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件路径
     */
    @Override
    public void sendMimeMessge(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(SENDER);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);

            mailSender.send(message);
        } catch (MessagingException e) {
            logger.error("发送带附件的MimeMessge时发生异常!", e);
        }
    }

    /**
     * 发送带静态文件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param rscIdMap 需要替换的静态文件
     */
    @Override
    public void sendMimeMessge(String to, String subject, String content, Map<String, String> rscIdMap) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(SENDER);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            for (Map.Entry<String, String> entry : rscIdMap.entrySet()) {
                FileSystemResource file = new FileSystemResource(new File(entry.getValue()));
                helper.addInline(entry.getKey(), file);
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            logger.error("发送带静态文件的MimeMessge时发生异常!", e);
        }
    }
}

Send mail demo

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbooEmailDemoApplicationTests {

    @Autowired
    private MailService mailService;

    private static final String TO = "[email protected]";
    private static final String SUBJECT = "测试邮件";
    private static final String CONTENT = "test content";

    /**
     * 测试发送普通邮件
     */
    @Test
    public void sendSimpleMailMessage() {
        mailService.sendSimpleMailMessge(TO, SUBJECT, CONTENT);
    }

    /**
     * 测试发送html邮件
     */
    @Test
    public void sendHtmlMessage() {
        String htmlStr = "<h1>Test</h1>";
        mailService.sendMimeMessge(TO, SUBJECT, htmlStr);
    }

    /**
     * 测试发送带附件的邮件
     * @throws FileNotFoundException
     */
    @Test
    public void sendAttachmentMessage() throws FileNotFoundException {
        File file = ResourceUtils.getFile("classpath:test.txt");
        String filePath = file.getAbsolutePath();
        mailService.sendMimeMessge(TO, SUBJECT, CONTENT, filePath);
    }

    /**
     * 测试发送带附件的邮件
     * @throws FileNotFoundException
     */
    @Test
    public void sendPicMessage() throws FileNotFoundException {
        String htmlStr = "<html><body>测试:图片1 <br> <img src=\'cid:pic1\'/> <br>图片2 <br> <img src=\'cid:pic2\'/></body></html>";
        Map<String, String> rscIdMap = new HashMap<>(2);
        rscIdMap.put("pic1", ResourceUtils.getFile("classpath:pic01.jpg").getAbsolutePath());
        rscIdMap.put("pic2", ResourceUtils.getFile("classpath:pic02.jpg").getAbsolutePath());
        mailService.sendMimeMessge(TO, SUBJECT, htmlStr, rscIdMap);
    }
}

Whitelist problem

If the mailbox is transmitted to the fixed, may be disposed directly in the mail inside the fixed whitelist, if a plurality of frequently sent to a mailbox, it is preferable to set the following transmission time interval, not continuously transmitted to a particular mailbox.

to sum up

So far SpringBoot send mail introductions, you can directly use the code to send.

Guess you like

Origin www.cnblogs.com/jichi/p/12015254.html