1.依赖
<!-- Email -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.EmailUtil工具类
package com.demo.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.stereotype.Service;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class EmailUtil {
@Value("${spring.mail.username}")
private String username;
@Autowired
private JavaMailSender mailSender;
//文本邮件
public void sendSimpleEmail() {
// 构造Email消息
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(username);
message.setTo("1452593769@qq.com");
message.setSubject("邮件主题");
message.setText("邮件内容");
//添加附件,第一个参数表示添加到 Email 中附件的名称,第二个参数是图片资源
// message("boot.png", new ClassPathResource("public/images/boot.png"));
mailSender.send(message);
}
//Html
public void sendHtmlMail(String Sender) {
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(username);
helper.setTo(Sender);
helper.setSubject("标题:发送Html内容");
StringBuffer sb = new StringBuffer();
sb.append("<h1>大标题-h1</h1>")
.append("<p style='color:#F00'>红色字</p>")
.append("<p style='text-align:right'>右对齐</p>");
helper.setText(sb.toString(), true);
} catch (Exception e) {
e.printStackTrace();
}
mailSender.send(message);
}
//资源邮件
public void sendInlineMail(String Sender) {
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(username);
helper.setTo(Sender);
helper.setSubject("主题:带静态资源的邮件");
//第二个参数指定发送的是HTML格式,同时cid:是固定的写法
helper.setText("<html><body>带静态资源的邮件内容 图片:<img src='cid:picture' /></body></html>", true);
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/image/picture.jpg"));
helper.addInline("picture",file);
} catch (Exception e){
e.printStackTrace();
}
mailSender.send(message);
}
}
3.测试
@Autowired
private EmailUtil emailUtil;
@RequestMapping("/")
public String start(){
emailUtil.sendSimpleEmail();
return "Success";
}