得到的AccessKey AccessSecret 作用于–调用单一发信 API-----SingleSendMail
设置的SMTP密码作用于–SMTP 协议发信----(可添加附件)
public void pushEmail(File file) {
// 配置发送邮件的环境属性
final Properties props = new Properties();
// 表示SMTP发送邮件,需要进行身份验证
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", ALIDM_SMTP_HOST);
props.put("mail.smtp.port", ALIDM_SMTP_PORT);
props.put("mail.user", user);
// 访问SMTP服务时需要提供的密码
props.put("mail.password", password);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
try {
// 设置发件人
InternetAddress fromAddress = new InternetAddress(user);
message.setFrom(fromAddress);
Address[] a = new Address[1];
a[0] = new InternetAddress(senderEmail);
message.setReplyTo(a);
// 设置收件人
InternetAddress to = new InternetAddress(recipientEmail);
message.setRecipient(MimeMessage.RecipientType.TO, to);
// 设置邮件标题
message.setSubject(title);
// 设置邮件的内容体
//创建附件
MimeBodyPart attch = new MimeBodyPart();
DataHandler dh1 = new DataHandler(new FileDataSource(file));
attch.setDataHandler(dh1);
String filename1 = dh1.getName();
// MimeUtility 是一个工具类,encodeText()用于处理附件字,防止中文乱码问题
attch.setFileName(MimeUtility.encodeText(filename1));
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(attch);
message.setContent(mm);
//保存修改
message.saveChanges();
// 发送邮件
Transport.send(message);
} catch (MessagingException e) {
String err = e.getMessage();
// 在这里处理message内容, 格式是固定的
log.error("{}", err);
} catch (UnsupportedEncodingException e) {
log.error("{}", e);
}
}
阿里云配置邮箱服务器