private Properties mailP = null;
public static final String EMAIL_CONTENT_TYPE_TEXT = "text";
public static final String EMAIL_CONTENT_TYPE_HTML = "html";
public static final String EMAIL_CONTENT_TYPE_PDF = "pdf";
try {
Authenticator authenticator=new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//身份验证address(发送人邮箱地址)mailPwd(密码)
}
};
smtp(simple mail transfer protocol 简单邮箱协议)邮箱身份自动验证
mailP.put("mail.smtp.auth","true");
//进行身份验证
Session session=Session.getDefaultInstance(mailP, authenticator);MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(adressMail));
InternetAddress[] address = InternetAddress.parse(to);
MimeMultipart multi = new MimeMultipart();
BodyPart textBodyPart = new MimeBodyPart();
/ 添加邮件附件
for (File file : attachments) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(MimeUtility.encodeWord(file
.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
// 选择发送内容的格式
if (type.equalsIgnoreCase(EMAIL_CONTENT_TYPE_HTML)) {textBodyPart.setContent(content, "text/html;charset=\"utf-8\"");
} else if (type.equalsIgnoreCase(EMAIL_CONTENT_TYPE_TEXT)) {
textBodyPart.setText(content);
} else if (type.equalsIgnoreCase(EMAIL_CONTENT_TYPE_PDF)) {
addAttachment(multi, content);
textBodyPart.setText("");
}
multi.addBodyPart(textBodyPart);
//添加发送地址(注意:多个发送邮箱,邮箱地址逗号隔开)
msg.setRecipients(Message.RecipientType.TO, address);
//cc(抄送人)判断是否有抄送人
if (cc != null && !"".equals(cc.trim())) {msg.setRecipients(Message.RecipientType.CC, cc);
}
msg.setSubject(title);
msg.setContent(multi);
//开始发送
Transport.send(msg);Log.log("Mail send Success!");