前提:
账号和密码准备好,
注意:163和QQ邮箱的密码是授权码(授权码设置在文章最后。。。)
pom.xml
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-mail
application.yml
spring:
mail:
host: smtp.163.com
password: STMDCLUJRRVQQSAY
username: xxxx@163.com
default-encoding: utf-8
port: 25
SendHtml.java
packagecom.springbootemaildemo.send;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.mail.javamail.JavaMailSender;importorg.springframework.mail.javamail.MimeMessageHelper;importorg.springframework.stereotype.Service;importjavax.mail.internet.MimeMessage;
@Servicepublic classSendHtml {
@AutowiredprivateJavaMailSender mailSender;
@Value("${spring.mail.username}")privateString form;
String to= "xxxx@qq.com";/*** 发送html格式的邮件
*
*@paramsubject 主题
*@paramcontent 内容*/
public voidsendHtmlMail(String subject, String content) {
MimeMessage message=mailSender.createMimeMessage();try{//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(form);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
mailSender.send(message);
System.out.println("html格式邮件发送成功");
}catch(Exception e) {
System.out.println("html格式邮件发送失败");
}
}
}
MailApplicationTests(测试类)
packagecom.springbootemaildemo;importcom.springbootemaildemo.excel.c.StudentService;importcom.springbootemaildemo.send.SendHtml;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringRunner;importorg.springframework.util.ResourceUtils;importcom.springbootemaildemo.service.MailService;importjava.io.File;importjava.io.FileNotFoundException;importjava.util.HashMap;importjava.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTestpublic classMailApplicationTests {
@Autowired
SendHtml sendHtml;/*** 测试发送html邮件*/@Testpublic voidsendHtmlMessage() {
String sc = "
" +
"
" +
"
" + bodys + "
" +
"
" + bodys2 + "
" +
"
CDE
" +
"
" +
"";
sendHtml.sendHtmlMail("邮件测试", sc);
}
}
html文件:
ABC
ABCDDDD
CDE
结果:
授权码设置
QQ:
163邮箱: