/**
- 发送email
/
public class EmailUtil {
/*-
toEmail 接收邮箱
-
subject 主题
-
content 内容
-
userName 发送邮箱账号
-
password 发送邮箱密码 (163是授权码)
-
fileList 附件
-
fromEmail 发送邮箱
*/
public static void sendAttachmentMail(String toEmail, String subject, String content, String userName, String password, String[] fileList, String fromEmail)
throws MessagingException, UnsupportedEncodingException {
try {
String host = “smtp.163.com”; //host
String port = “465”; //端口Properties props = System.getProperties(); //设置用户的认证方式 props.setProperty("mail.smtp.auth", "true"); //设置传输协议 props.setProperty("mail.transport.protocol", "smtp"); //设置发件人的SMTP服务器地址 props.setProperty("mail.smtp.host", host); //端口 props.setProperty("mail.smtp.port", port); //debug,一般不配置这个参数,调试的时候用 props.setProperty("mail.debug", "true"); //使用ssl需要加如下参数 props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); Session session = Session.getInstance(props, null); //附件处理 Multipart multipart = new MimeMultipart(); MimeBodyPart messageBodyPart1 = new MimeBodyPart(); //正文,可以是html文档 messageBodyPart1.setContent(content, "text/html;charset=utf-8"); multipart.addBodyPart(messageBodyPart1);
-
// MimeBodyPart messageBodyPart2 = new MimeBodyPart();
// 邮件中包含本地附件
// String path = “F:\fff.docx”;
// // 1、得到数据源
// FileDataSource fds = new FileDataSource(path);
// // 2、得到附件本身并至入BodyPart
// messageBodyPart2.setDataHandler(new DataHandler(fds));
// //3、设置附件名
// messageBodyPart2.setFileName(“fff.docx”);
// multipart.a*/ddBodyPart(messageBodyPart2);
//邮件中包含网络附件
if (fileList != null && fileList.length > 0) {
DataHandler dataHandler = null;
String fileName = "";
MimeBodyPart messageBodyPart = new MimeBodyPart();
for (int i = 0; i < fileList.length; i++) {
dataHandler = new DataHandler(new URL(fileList[i]));
messageBodyPart.setDataHandler(dataHandler);
fileName = fileList[i].substring(fileList[i].lastIndexOf(File.separator) + 1);
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
}
}
MimeMessage replyMessage = new MimeMessage(session);
//发件箱,大部分与邮箱账号一致
InternetAddress mailFrom = new InternetAddress(fromEmail);
//收件箱,有一段时间申请的QQ邮箱好像默认关闭了 pop3和smtp,所以qq邮箱可能会收不到邮件
InternetAddress mailTo = new InternetAddress(toEmail);
replyMessage.setFrom(mailFrom);
replyMessage.setContent(multipart);
replyMessage.setSubject(subject);
replyMessage.setReplyTo(new Address[]{mailFrom});
replyMessage.setRecipient(javax.mail.Message.RecipientType.TO, mailTo);
replyMessage.setSender(mailFrom);
Transport transport = session.getTransport("smtp");
try {
transport.connect(host, userName, password);
//发送邮件
transport.sendMessage(replyMessage, new Address[]{mailTo});
} catch (Exception e) {
} finally {
transport.close();
}
System.out.println("success");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}