Bootstrap

Spring Boot 之通过JavaMailSender发送邮件

1.导入mail依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. 添加配置
spring:
  mail:
    host: smtp.qq.com 
    username: [email protected] #你的邮箱
    password: 你的授权码 #在邮箱中开启stmp服务获取授权码
3.编写service接口和实现类
package com.example.demo_email.service;
public interface ISendMailService {
     void sendSimpleMail();
     void sendMimeMail();
}
package com.example.demo_email.service.impl;

import com.example.demo_email.service.ISendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class SendMailServiceImpl implements ISendMailService {
    private String from = "[email protected]"; //发送邮箱
    private String to = "[email protected]"; //接收邮箱
    private String subject = "测试信息"; //标题
    private String context = "<img src='https://www.baidu.com/img/pc_675fe66eab33abff35a2669768c43d95.png'><a href='https://www.baidu.com'>进入百度</a>测试内容,我是通过JavaMailSender发送过来的数据"; //内容


    @Autowired
    JavaMailSender javaMailSender;

    @Override
    public void sendSimpleMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from + "(神秘人)");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(context);
        javaMailSender.send(message);
    }

    @Override
    public void sendMimeMail() {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            //第一个参数将message传入 第二个参数指定是否能上传附件
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from + "(神秘人)");
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(context,true);

            String filePath = "F:\\JAVA\\Study-Spring Boot\\demo\\demo_email\\src\\main\\java\\com\\example\\demo_email\\service\\impl\\SendMailServiceImpl.java";
            File f1 = new File(filePath);
            File f2 = new File("c:\\logo.png");
            
            helper.addAttachment(f1.getName(),f1);
            helper.addAttachment("logo.png",f2); //若不指定后缀名则在邮件中不能预览
            javaMailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4.测试
@SpringBootTest
class DemoEmailApplicationTests {
	@Autowired
	SendMailServiceImpl sendMailService;
	@Test
	void contextLoads() {
		sendMailService.sendSimpleMail();
		sendMailService.sendMimeMail();
	}
}
;