import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.annotation.Resource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
public class mail {
@Resource
private JavaMailSender javaMailSender;
private static final Logger logger = LoggerFactory.getLogger(mail.class);
private static final String TO_EMAIL = "XXXX@qq.com"; // 接收人邮箱地址
private static final String SMTP_HOST = "smtp.qq.com"; // SMTP服务器
private static final String USERNAME = "XXXX@qq.com"; // 发送人邮箱用户名
private static final String PASSWORD = "emsnkzpbifiibeab"; // 发送人邮箱授权码
public static void sendEmail(String to, String subject, String body) {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", SMTP_HOST); // SMTP服务器
properties.put("mail.smtp.auth", "true");// 是否启用身份验证
properties.put("mail.smtp.port", "465"); // SMTP服务器的端口号 465 587
MailSSLSocketFactory sf = null; // sf 是一个信任所有主机的 SSL 工厂实例,用于处理 SSL 握手和加密通信
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true); // 信任所有主机
} catch (GeneralSecurityException e) {
logger.error("Error creating SSL socket factory", e);
return;
}
properties.put("mail.smtp.ssl.enable", "true"); // 开启SSL
properties.put("mail.smtp.ssl.socketFactory", sf); // 设置SSL工厂
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // 设置SSL工厂类
properties.put("mail.smtp.socketFactory.fallback", "false"); // 不使用回退机制
Session session = Session.getDefaultInstance(properties, new Authenticator() { // 创建会话
@Override
protected PasswordAuthentication getPasswordAuthentication() { // 身份验证
return new PasswordAuthentication(USERNAME, PASSWORD); // 发送人邮箱用户名和授权码
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(USERNAME)); // 发送人邮箱地址
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 接收人邮箱地址
message.setSubject(subject); // 邮件主题
message.setText(body); // 邮件正文
Transport.send(message); // 发送邮件
logger.info("Sent message successfully");
} catch (MessagingException e) {
logger.error("Error sending email", e);
}
}
public static void main(String[] args) {
sendEmail(TO_EMAIL, "This is the Subject Line!", "This is actual message");
}
完整代码,不会的可以看注释
参考网址Java 网络编程 | 菜鸟教程