发送邮件代码:
public void sendEmail(EmailData data) {
if(data.getAttachmentList().size() <= 0) {
logger.error("[EmailService] [sendEmail] attachment is empty!!")
return
}
logger.info("[EmailService] [sendEmail] [form:{}] [pass:{}] [to:{}] [subject:{}]",
data.getFromUser(), data.getFromPass(), data.getToUsers(), data.getSubject())
Session session = getSession(data.getFromUser(), data.getFromPass())
MimeMessage message = new MimeMessage(session)
try {
//加载发件人地址
message.setFrom(new InternetAddress(data.getFromUser()))
//加载收件人地址
String[] arr = data.getToUsers().split(",")
int receiverCount = arr.length
if(receiverCount > 0) {
InternetAddress[] address = new InternetAddress[receiverCount]
for (int i = 0
address[i] = new InternetAddress(arr[i])
logger.info("[EmailService] [sendEmail] [to address:{}]", arr[i])
}
message.addRecipients(Message.RecipientType.TO, address)
}
//加载标题
message.setSubject(data.getSubject())
//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart()
//设置邮件的文本内容
BodyPart contentPart = new MimeBodyPart()
contentPart.setText("")
multipart.addBodyPart(contentPart)
//添加附件信息
addAttachments(multipart, data.getAttachmentList())
//将multipart对象放到message中
message.setContent(multipart)
//发送邮件
Transport.send(message)
logger.info("[EmailService] [sendEmail] [email send success!!]")
} catch (Exception e) {
logger.error("", e)
}
}
获取Session,并进行验证:
/**
* 获取Session
* @param username 发件人邮箱
* @param password 发件人密码
* @date 2017年4月13日
*/
private Session getSession(final String username, final String password) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.exmail.qq.com");
props.put("mail.smtp.port", 465);
props.put("mail.smtp.auth", "true");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
return session;
}
添加附件至邮件中:
/**
* 将附件信息添加至邮件中
* @param list
* @date 2017年4月11日
*/
private void addAttachments(Multipart multipart, List<Attachment> attachmentList) throws MessagingException {
for(Attachment attachment : attachmentList) {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment.getPath());
messageBodyPart.setDataHandler(new DataHandler(source));
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
multipart.addBodyPart(messageBodyPart);
}
}