欢迎添加微信交流Java问题:17625089935
pom
<!--邮件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置文件:
# 字符集编码 默认 UTF-8
spring.mail.default-encoding=UTF-8
# SMTP 服务器 host qq邮箱的为 smtp.qq.com 端口 465 587
spring.mail.host=smtp.qq.com
# SMTP 服务器端口 不同的服务商不一样
spring.mail.port=465
# SMTP 服务器使用的协议
spring.mail.protocol=smtp
#发送者的邮箱账号
spring.mail.username=1263944101@qq.com
#发送者的邮箱密码
spring.mail.password=qhqgurcvrcpkicff
#开启ssl
spring.mail.properties.mail.smtp.ssl.enable=true
package nbpt.ts.zhaf.util.email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class EmailUtil {
private static JavaMailSender javaMailSender;
private static String from;
@Value("${spring.mail.username}")
private void setFrom(String from) {
this.from = from;
}
/**
*
* @param to 发送给谁
* @param title 标题
* @param text 内容
*/
public static void sendMail(String to, String title, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(title);
message.setText(text);
javaMailSender.send(message);
}
@Autowired
public EmailUtil(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
}
使用:
EmailUtil.sendMail("发送目标qq邮箱地址", "标题","内容");