这里以QQ邮箱为例:
1.进入qq邮箱首页
2.设置
3.开启【POP3/SMTP服务】获得授权码
4.在你的项目pom.xml中添加依赖
<!-- 支持发送邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
5.在你的项目配置文件application.properties中配置
# JavaMailSender 邮件发送的配置
spring.mail.host=smtp.qq.com
spring.mail.username=XXXXXX@qq.com #你的qq邮箱
spring.mail.password=xxxxxxxxxx #你的授权码,非登录密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
6.创建测试类测试邮箱发送
package com.yixiao;
import org.junit.Test;
import org.junit.runner.RunWith;
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.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* Created by Administrator on 2020/3/20.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailTest {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String sender;
@Test
public void sendSimpleMailTest() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sender);
message.setTo(sender); //邮件接收人
message.setSubject("这是邮件主题");
message.setText("这是邮件内容");
mailSender.send(message);
}
@Test
public void sendHtmlMailTest() {
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(sender);
helper.setSubject("标题:发送Html内容");
StringBuffer sb = new StringBuffer();
sb.append("<h1>大标题-h1</h1>");
sb.append("<p style='text-align:right'>右对齐</p>");
helper.setText(sb.toString(), true);
} catch (Exception e) {
e.printStackTrace();
}
mailSender.send(message);
}
@Test
public void sendAttachmentsTest() {
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(sender);
helper.setSubject("主题:带附件的邮件");
helper.setText("带附件的邮件内容");
//注意项目路径问题,自动补用项目路径
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/emailTest.png"));
//加入邮件
helper.addAttachment("emailTest.jpg", file);
} catch (Exception e) {
e.printStackTrace();
}
mailSender.send(message);
}
}