SpringBoot的邮件发送
非常简单的东西, SpringBoot 提供了开箱即用的starter
starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
yml
自动配置类 org.springframework.boot.autoconfigure.mail.MailProperties
spring:
mail:
host: smtp服务器
username: 登录用户名
password: 登录密码
port: 服务断开
default-encoding: 编码
protocol: 协议
# 其他选项
properties:
mail:
smtp:
connectiontimeout: 5000
timeout: 3000
writetimeout: 5000
auth: true
starttls:
enable: true
required: true
使用
import java.io.UnsupportedEncodingException;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
@Component
public class EmailHelper {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String account;
/**
* 发送html邮件
* @param from 发件人名称
* @param to 收件邮箱
* @param title 标题
* @param content 内容
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void sendHTMLMail(String from, String to, String title, String content)throws MessagingException, UnsupportedEncodingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 发件人:from <account>
helper.setFrom(new InternetAddress(MimeUtility.encodeText(from) + "<" + this.account + ">"));
helper.setTo(to);
helper.setSubject(title);
helper.setText(content, true); //设置内容,第二个boolean参数表示内容是否为 html 格式的文件。
javaMailSender.send(message);
}
}