这篇文章主要介绍了spring boot如何加入mail邮件支持,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
一、添加依赖
org.springframework.boot spring-boot-starter-mail
二、添加mail.properties配置文件
#设置邮箱主机 spring.mail.host=smtp.qq.com #设置用户名 spring.mail.username=xxxxxxx #设置密码 #QQ邮箱->设置->账户->POP3/SMTP服务:开启服务后会获得QQ的授权码 spring.mail.password=xxxxxxxxxxxxxxxx #端口 spring.mail.port=465 #协议 #spring.mail.protocol=smtp #设置是否需要认证,如果为true,那么用户名和密码就必须的, #如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。 spring.mail.properties.mail.smtp.auth=true #STARTTLS[1] 是对纯文本通信协议的扩展。它提供一种方式将纯文本连接升级为加密连接(TLS或SSL),而不是另外使用一个端口作加密通信。 spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
三、添加MailConfig.java
package com.spring.config;
import java.io.File;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
@Configuration
public class MailConfig {
@Resource
private JavaMailSenderImpl mailSender;
@Value("${spring.mail.username}")
private String username;
public void sendTextMail(String toEmail, String title, String content) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom(username);
msg.setTo(toEmail);
msg.setSubject(title);
msg.setText(content);
mailSender.send(msg);
}
public void sendHtmlMail(String toEmail, String title, String htmlContent) throws MessagingException {
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, false, "utf-8");
helper.setFrom(username);
helper.setTo(toEmail);
helper.setSubject(title);
helper.setText(htmlContent, true);
mailSender.send(msg);
}
public void sendAttachmentMail(String toEmail, String title, String content, List
四、使用MailConfig
@Autowired private MailConfig mailConfig;
使用MailConfig里面的方法发送即可以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



