赞
踩
springboot项目,集成阿里云企业邮箱,进行邮件发送,附带文件
public class AliyunMail {
public static final String ALIDM_SMTP_HOST = "smtp.qiye.aliyun.com";
public static final String ALIDM_SMTP_PORT = "25";
/**
* @param sendAddress 发件人地址
* @param sendPassword 发件人密码
* @param subject 标题
* @param content 内容
* @param filePath 附件地址
* @throws Exception
* @throws AddressException
*/
public void sendMail(String sendAddress,String sendPassword,String subject,String content,String internetAddress,String filePath) throws AddressException, Exception {
//设置SSL连接、邮件环境
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", ALIDM_SMTP_HOST);
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
//设置端口
props.setProperty("mail.smtp.port", ALIDM_SMTP_PORT);
//启用调试
props.setProperty("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtp.auth", "true");
//建立邮件会话
Session session = Session.getDefaultInstance(props, new Authenticator() { //身份认证
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人账号、密码
return new PasswordAuthentication(sendAddress, sendPassword);
}
});
//建立邮件对象
MimeMessage message = new MimeMessage(session);
//设置邮件的发件人、收件人、主题
//附带发件人名字
// message.setFrom(new InternetAddress("from_mail@qq.com", "optional-personal"));
//发件人账号
message.setFrom(new InternetAddress(sendAddress));
//收件人账号
message.setRecipients(Message.RecipientType.TO, internetAddress);
//标题
//邮件标题
message.setSubject(subject);
//内容
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
//邮件内容
contentPart.setContent(content, "text/html;charset=utf-8");
multipart.addBodyPart(contentPart);
//附件部分
if (StringUtils.isNotBlank(filePath)) {
BodyPart attachPart = new MimeBodyPart();
//附件地址
FileDataSource fileDataSource = new FileDataSource(filePath);
attachPart.setDataHandler(new DataHandler(fileDataSource));
attachPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
multipart.addBodyPart(attachPart);
}
message.setContent(multipart);
// //抄送地址
// if (StringUtils.isNotBlank(CC)) {
// InternetAddress[] internetAddressCC = new InternetAddress().parse(CC);
// message.setRecipients(Message.RecipientType.CC, internetAddressCC);
// }
//发送邮件
Transport.send(message);
}
}
public static final String ALIDM_SMTP_HOST = "smtp.qiye.aliyun.com";
public static final String ALIDM_SMTP_PORT = "25";
这两个是阿里云企业邮箱服务地址和端口,一般不变。
附件部分,需要注意附件大小,这个有发件邮箱设置而来。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。