spring-boot邮件集成

2022-04-21  本文已影响0人  Restart白蓝
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  # 邮箱服务
  mail:
    # 163
    host: smtp.163.com
    port:
    username: xxxxx@163.com
    password: QVPXDNBWKTHKZPJS
    protocol: smtp
    default-encoding: UTF-8
    properties:
      mail.smtp.auth: true
      mail.smtp.socketFactory.port: 465
      mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
      mail.smtp.socketFactory.fallback: false
package com.creo.web.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author weidl
 * @date 2022年4月21日16:26:07
 */
@SpringBootTest
public class EmailTestController {

    @Autowired
    private JavaMailSender mailSender;



    @Value("${spring.mail.username}")
    private String from;


    @Test
    public void sendAttachmentsMail() throws Exception {

        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo("123456@qq.com");
        helper.setSubject("主题:有附件");
        helper.setText("有附件的邮件");

        FileSystemResource file = new FileSystemResource(new File("D:/123.png"));
        helper.addAttachment("附件-1.png", file);
        helper.addAttachment("附件-2.png", file);

        mailSender.send(mimeMessage);

    }

}

上一篇下一篇

猜你喜欢

热点阅读