前提:
账号和密码准备好,
注意:163和QQ邮箱的密码是授权码(授权码设置在文章最后。。。)
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
application.yml
spring: mail: host: smtp.163.com password: STMDCLUJRRVQQSAY username: xxxx@163.com default-encoding: utf-8 port: 25
SendHtml.java
package com.springbootemaildemo.send; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.internet.MimeMessage; @Service public class SendHtml { @Autowired private JavaMailSender mailSender; @Value("${spring.mail.username}") private String form; String to = "xxxx@qq.com"; /** * 发送html格式的邮件 * * @param subject 主题 * @param content 内容 */ public void sendHtmlMail(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(测试类)
package com.springbootemaildemo; import com.springbootemaildemo.excel.c.StudentService; import com.springbootemaildemo.send.SendHtml; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.ResourceUtils; import com.springbootemaildemo.service.MailService; import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; @RunWith(SpringRunner.class) @SpringBootTest public class MailApplicationTests { @Autowired SendHtml sendHtml; /** * 测试发送html邮件 */ @Test public void sendHtmlMessage() {
String sc = "<html> " +
"<body> " +
"<p id="mailUuid" style="display: none">" + bodys + "</p> " +
"<p id="uuid" style="">" + bodys2 + "</p> " +
"<p>CDE</p> " +
"</body> " +
"</html>";
sendHtml.sendHtmlMail("邮件测试", sc); } }
html文件:
<!DOCTYPE html> <html> <body> <p id="mailUuid" style="display: none">ABC</p> <p id="uuid" style="">ABCDDDD</p> <p>CDE</p> </body> </html>
结果:
授权码设置
QQ:
163邮箱: