import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* qq邮箱发送邮件工具bean
*
* pulic 发送方法
* 发件人邮箱
* 授权码
* 收件人
* 内容
*
* 初始化,丢构造函数里
*/
@Component
@PropertySource(value = {"classpath:mail.properties"})
public class EmailSender {
@Value("${mail.username}")
private String username;
@Value("${mail.password}")
private String password;
private Session session;
public void send(String recipient, String subject, String content){
try {
// 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username)); // 设置发件人邮箱
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); // 设置收件人邮箱
message.setSubject(subject); // 设置邮件主题
message.setText(content); // 设置邮件内容
// 设置邮件内容为html
message.setContent(content,"text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
System.out.println("邮件发送成功!"); // 打印成功信息
} catch (MessagingException e) {
e.printStackTrace(); // 打印异常堆栈信息
}
}
public EmailSender() {
// this.username = username;
// this.password = password;
// 设置邮件服务器属性
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.qq.com"); // 设置邮件服务器主机名
properties.put("mail.smtp.port", "587"); // 设置邮件服务器端口号
properties.put("mail.smtp.auth", "true"); // 启用身份验证
properties.put("mail.smtp.starttls.enable", "true"); // 启用 TLS
//properties.put("mail.smtp.socketFactory.port", "465"); // 设置 SSL 端口
//properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // 设置 SSL Socket Factory
//properties.put("mail.smtp.socketFactory.fallback", "false"); // 禁用 SSL 回退
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
// 在这里填写发送邮件的邮箱地址和密码/授权码
// return new PasswordAuthentication(from, "your-qq-email-authorization-code"); // 使用QQ邮箱授权码进行身份验证
}
};
// 创建会话对象
session = Session.getDefaultInstance(properties,authenticator );
}
}