阿里云默认禁用25端口,官网建议使用465端口发送邮件
代码
public static void main(String[] args) throws Exception {
try {
// 邮件主题
String subject = "邮箱验证";
//1. 用于存放 SMTP 服务器地址等参数
Properties properties = new Properties();
Resource resource = new ClassPathResource("config.properties");
File file = resource.getFile();
properties.load(new FileInputStream(file));
// 使用JavaMail发送邮件的5个步骤
// 2. 创建session
Session session = Session.getDefaultInstance(properties, new EmailAccountVo(properties.getProperty("mail.account"), properties.getProperty("mail.password")));
// 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
//session.setDebug(true);
// 3. 创建邮件
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 邮件的标题
message.setSubject(subject);
// 邮件发送日期
message.setSentDate(new Date());
// 指明邮件的发件人
message.setFrom(new InternetAddress(properties.getProperty("mail.address")));
// 指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("xxx@xxx.com", "xxx@xxx.com"));
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentBodyPart = new MimeBodyPart();
// 邮件内容
String result = "尊敬的用户,您好:</br>" +
" 您正在进行公司邮箱验证,本次邮箱验证码为:121212,验证码" + Constants.EMAIL_CODE_EXPIRES_HOUR + "小时内有效。" +
"如果您未做过此操作并认为有未经授权的人员访问了您的帐户。请您尽快更改Z13平台登录密码。\n";
contentBodyPart.setContent(result, "text/html;charset=UTF-8");
multipart.addBodyPart(contentBodyPart);
message.setContent(multipart);
for (int i = 0; i < 2; i++) {
// 4. 发送邮件,Transport每次发送成功程序帮忙关闭
Transport.send(message, message.getAllRecipients());
System.out.println("send mail result:success");
}
} catch (Exception e) {
e.printStackTrace();
}
}
配置文件config.properties
#邮箱配置
mail.smtp.host=smtp.163.com
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.ssl.enable=true
mail.smtp.socketFactory.fallback=true
#163邮箱账号
mail.account=xxxxx@163.com
#163邮箱授权码(不是密码 是授权码)
mail.password=xxxxxx
mail.address=xxxxx@163.com
mail.port=465
mail.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.socketFactory.fallback=false
mail.socketFactory.port=465