邮件发送
发送邮件是一个很重要的服务,比如注册验证,忘记密码或者其他运营信息。之前使用javaMail API发送,在boot发送邮件已经做了封装。
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.application.properties配置
#mail
spring.mail.default-encoding=utf-8
spring.mail.host=smtp.qq.com
spring.mail.protocol=smtp
spring.mail.username=xxx
spring.mail.password=xx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
3.邮件发送类和模板
- 发送纯文本
- 发送html文件 (带图片,附件)
- 使用模板发送
@Component
public class MailUtil {
private static final Logger logger = LoggerFactory.getLogger(MailUtil.class);
@Value("${spring.mail.username}")
private String user;
@Autowired
private JavaMailSender mailSender;
@Autowired
public Configuration configuration;
/**
*
* @param receiver
* @param subject
* @param content
* @throws Exception
*/
public void send(String receiver,String subject,String content) throws Exception{
logger.info("收件人:"+receiver);
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(user);
message.setTo(receiver);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
public void sendHtml(String receiver,String subject,String content) throws Exception{
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom(user);
helper.setTo(receiver);
helper.setSubject(subject);
helper.setText(content,true);
//图片
File file = ResourceUtils.getFile("classpath:images/mail/a.png");
helper.addInline("MyImg",file);
// 发送附件
file = ResourceUtils.getFile("classpath:attach/a.txt");
helper.addAttachment("荒野",file);
mailSender.send(message);
}
public void sendFreemark(String receiver,String subject,String tmp) throws Exception{
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom(user);
helper.setTo(receiver);
helper.setSubject(subject);
Map<String,Object> data = new HashMap<>();
data.put("text","freemark test");
data.put("author","lg");
Template template = configuration.getTemplate(tmp);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template,data);
helper.setText(text,true);
mailSender.send(message);
}
}
4.测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailTest {
@Autowired
private MailUtil mailUtil;
@Test
public void send() throws Exception{
mailUtil.send("xxx","springboot mail test","boot 邮件测试");
}
@Test
public void sendHtml() throws Exception{
String content = "<html><body><h3>发送html测试</h3><img src=\"cid:MyImg\"></body></html>";
mailUtil.sendHtml("xxx","mail html test",content);
}
@Test
public void sendFreemark() throws Exception{
mailUtil.sendFreemark("xxx","mail html test","mail.flt");
}
}