今天学了springboot如何发送邮件,做了以下的内容总结,方便自己日后复习和查看!
1.pom文件maven的引入
<!-- send mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- thymeleaf模板引入,之前的章节已经讲过这块的使用方法了 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.properties文件的配置
这里有一个重点的内容,就是下面一会会提到的发送邮箱的账户和密码,密码并不是我们平时登录邮箱的密码,而是需要在相关的邮箱上进行一个设置,才能使用!
###########send mail################
spring.mail.host=smtp.sina.com.cn
spring.mail.username=snowvssun@sina.com
#password 这一项,并不是我们日常使用的登录密码,我们需要开启我们的认证密码(客户端授权密码)。
spring.mail.password=24fdb134f7207393
spring.mail.default-encoding=UTF-8
####thymeleaf配置,可以省略,因为都有默认的配置####
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
以我的邮箱,新浪邮箱为例子,来给大家稍微说一下怎么设置吧!
3.发送邮件的代码Service
我把发送邮件的三个方法都写到这个service里面,你们可以根据自己的需求进行选取使用,当然了这里都是一些简单的使用,在企业中我们往往需要复杂的操作等,模板一般用的比较多,也会封装很多公用的方法,这里就不说的那么详细了,俗话说师傅引进门修行靠自己!想要拓展方法自己去拓展吧!
package com.lengmo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
@Service
public class SendMailService {
protected Logger logger = LoggerFactory.getLogger(SendMailService.class);
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private TemplateEngine templateEngine;
@Value("${spring.mail.username}")
private String fromMail;
/**
*SimpleMailMessage发送简单的邮件
* @param toAddress 接受地址
* @param subject 主题
* @param context 邮件内容
*/
public void sendSimpleMail(String toAddress ,String subject,String context){
SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
simpleMailMessage.setFrom(fromMail);
simpleMailMessage.setTo(toAddress);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(context);
try {
javaMailSender.send(simpleMailMessage);
logger.info("Successfully!!!!!!");
} catch (Exception e) {
logger.info("Filed!!!!!!"+ e);
}
}
/**
*MimeMessage发送带附件的邮件
* @param toAddress 接受地址
* @param subject 主题
* @param context 邮件内容
*/
public void sendAttchMail(String toAddress ,String subject,String context){
try {
MimeMessage mimeMessage=javaMailSender.createMimeMessage();
//下面的这个方法很重要啊,如果需要加附件传递,记得开启multipart为true
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(fromMail);
helper.setTo(toAddress);
helper.setSubject(subject);
helper.setText(context);
//添加附件
String filePath = "E:\\helloworld.txt";
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
javaMailSender.send(mimeMessage);
logger.info("Successfully!!!!!!");
} catch (Exception e) {
logger.info("Filed!!!!!!"+ e);
}
}
/**
*sendThymeleafMail以模板的形式发送邮件并带附件
* @param toAddress 接受地址
* @param subject 主题
* @param context 邮件内容
*/
public void sendThymeleafMail(String toAddress ,String subject,String context){
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromMail);
helper.setTo(toAddress);
helper.setSubject(subject);
Context conThyme = new Context();
Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("id", 214);
hashMap.put("code", "DYA12R");
conThyme.setVariables(hashMap);
String emailContext = templateEngine.process("emailTest", conThyme);
helper.setText(emailContext, true);
//添加附件
String filePath = "E:\\helloworld.txt";
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
javaMailSender.send(message);
logger.info("Successfully!!!!!!");
} catch (MessagingException e) {
logger.info("Filed!!!!!!"+ e);
}
}
}
4.老规矩,代码验证
package com.lengmo.controller;
import com.lengmo.service.ApacheHtmlEmailService;
import com.lengmo.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/mail")
public class SendMailController {
@Autowired
private SendMailService sendMailService;
@Autowired
private ApacheHtmlEmailService apacheHtmlEmailService;
@RequestMapping("/send")
public void sendMail(){
//sendMailService.sendSimpleMail("591507760@qq.com","我是简单的发送","sendSimpleMail hellow world");
//sendMailService.sendAttchMail("591507760@qq.com","我带附件","sendAttchMail hellow world");
sendMailService.sendThymeleafMail("591507760@qq.com","我模板并带附件","sendThymeleafMail hellow world");
// apacheHtmlEmailService.sendSimpleMailByHtmlEmail("591507760@qq.com","我是简单的发送","sendSimpleMailByHtmlEmail hellow world");
}
}