Java发送邮件
2022-11-25 23:01
2022-11-25 23:03
3
0
一、准备工作
1.开启SMTP,获取授权码
2.添加依赖
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
二、Java 发送邮件代码示例
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SendEmail {
// 邮箱配置
private static final String SMTP_HOST = "smtp.163.com";// QQ邮箱smtp.qq.com
private static final String SMTP_PORT = "465"; // 或 994(IMAP),但 SMTP 用 465 或 587
private static final String FROM_EMAIL = "yourname@163.com";// yourname@qq.com
private static final String AUTH_CODE = "your_authorization_code"; // 授权码,不是密码
public static void sendSimpleEmail(String to, String subject, String content) {
// 设置邮件服务器属性
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true"); // 使用 SSL
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
// 创建认证器
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM_EMAIL, AUTH_CODE);
}
};
// 获取 Session 对象
Session session = Session.getInstance(props, authenticator);
session.setDebug(true); // 打印调试信息
try {
// 创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM_EMAIL));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setContent(content, "text/html;charset=UTF-8"); // 支持 HTML 内容
// 发送邮件
Transport.send(message);
System.out.println("邮件发送成功!");
} catch (MessagingException e) {
e.printStackTrace();
System.out.println("邮件发送失败:" + e.getMessage());
}
}
// 测试
public static void main(String[] args) {
sendSimpleEmail(
"recipient@example.com",
"测试邮件",
"<h3>这是一封来自 Java 的测试邮件!</h3>"
);
}
}