一、授权码、发送服务器的获取
- 发送服务器
- 授权码获取
二、业务代码
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SSLMailSender {
public static void main(String[] args) {
// 阿里云邮箱SMTP服务器地址
String host = "smtp.qiye.aliyun.com";
// 阿里云邮箱的账号(用户名)
String username = "发件人邮箱";
// 阿里云邮箱的授权码(不是登录密码)
String password = "授权码";
// 发件人邮箱
String from = "发件人邮箱";
// 收件人邮箱
String to = "收件人邮箱";
// 邮件主题
String subject = "Test Email from Aliyun with SSL";
// 邮件正文
String content = "Hello, this is a test email sent from Aliyun email using SSL.";
// 发送邮件
sendEmail(host, username, password, from, to, subject, content);
}
public static void sendEmail(String host, String username, String password, String from, String to, String subject, String content) {
// 获取系统属性
Properties props = new Properties();
// 设置邮件服务器
props.put("mail.smtp.host", host);
// 设置启用SSL加密
props.put("mail.smtp.ssl.enable", "true");
// 设置SMTP端口,通常SSL端口是465
props.put("mail.smtp.port", "465");
// 设置SMTP是否需要认证
props.put("mail.smtp.auth", "true");
// 获取默认session对象
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建默认的 MimeMessage 对象
Message message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(from));
// 设置收件人
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// 设置邮件主题
message.setSubject(subject);
// 设置邮件正文
message.setText(content);
// 发送邮件
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
三、测试