引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
注册邮箱
163
,126
,qq
都行,这边测试126
邮箱;
- 开启
IMAP/SMTP
服务;
- 获取
授权密码
,注意保存.
配置application.yaml
spring:
mail:
username: xxxxxx@126.com
password: XXXXXXXXXXXXXXX
host: smtp.126.com
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
测试发送
@Service
public class MailService {
@Autowired
JavaMailSender mailSender;
public void send(){
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom("XXXXX@126.com");
simpleMailMessage.setTo("1154365135@qq.com");
simpleMailMessage.setSubject("测试主题~~");
simpleMailMessage.setText("测试内容~~");
mailSender.send(simpleMailMessage);
}
public void sendHtml() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("authservice@126.com");
helper.setTo("1154365135@qq.com");
helper.setSubject("测试HTML~~");
helper.setText("<html>\n" +
"<head>\n" +
"<meta charset=\"utf-8\">\n" +
"<title>菜鸟教程(runoob.com)</title>\n" +
"</head>\n" +
"<body>\n" +
" <h1>我的第一个标题</h1>\n" +
" <p style=\"color: blue;\">我的第一个段落。</p>\n" +
"</body>\n" +
"</html>", true);
mailSender.send(mimeMessage);
}
public void sendAttachmentMail(String to,String subject,String content,String filePath) throws MessagingException {
MimeMessage mimeMessage=mailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
helper.setFrom(form);
FileSystemResource file=new FileSystemResource(new File(filePath));
String fileName=file.getFilename();
helper.addAttachment(fileName,file);
mailSender.send(mimeMessage);
}
public void sendInlineResourceMail(String to,String subject,String content,String rscPath,String rscId) throws MessagingException {
MimeMessage mimeMessage=mailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
helper.setFrom(form);
FileSystemResource file=new FileSystemResource(new File(rscPath));
helper.addInline(rscId,file);
mailSender.send(mimeMessage);
}
}