基于spring boot项目发送邮件,只需要完成下面的三个步骤即可完成
开发步骤
一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
二、添加配置信息(以QQ邮箱为例)
其他邮箱类似
spring:
mail:
port: 465
host: smtp.qq.com
username: zbqsuper@foxmail.com #邮箱地址
password: xxxxxxxxx #授权码(不是QQ邮箱密码)
default-encoding: UTF-8
properties:
mail:
smtp:
ssl:
enable: true
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory
auth: true
starttls:
enable: true
required: true
三、为了方便和清晰,这里我就直接使用固定的信息,写一个Test测试用例
注意:这里需要引入我们需要的一个Bean对象;和获取配置信息中的邮箱地址
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
@PostMapping("sendMailHtml")
public void testsendattch(){
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = null;
try {
mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo("2538691793@qq.com");
mimeMessageHelper.setSubject("发送附件邮件");
mimeMessageHelper.setText("<!DOCTYPE html>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>服装店</title>\n" +
"<html>\n" +
"\n" +
"\t<body>\n" +
"\t\t<font id=\"ft\" color=\"aqu\"></font>\n" +
"\t\t<h2 style=\"color: red;\">服装1</h2>\n" +
"\t\t<h2 style=\"color: red;\">服装22</h2>\n" +
"\t\t<h2 style=\"color: red;\">服装3</h2>\n" +
"\t\t<h2 style=\"color: red;\">服装4</h2>\n" +
"\t\t<h2 style=\"color: red;\">服装5</h2>\n" +
"\t</body>\n" +
"</html>\n",true);
try {
javaMailSender.send(mimeMessage);
} catch (MailException e) {
e.printStackTrace();
}
}