/*** 发送邮件 可以带附件 内容可为HTML
*
*@parammailEntity
*@return*@throwsGeneralSecurityException*/
public static booleansendMail(MailEntity mailEntity)throwsGeneralSecurityException {//发件人电子邮箱
final String from =mailEntity.getMailFromAddress();//发件人电子邮箱密码
final String pass =mailEntity.getMailFromPwd();//指定发送邮件的主机为 smtp.qq.com
String host = mailEntity.getMailFromHost(); //邮件服务器
String port=mailEntity.getPort();//获取系统属性
Properties properties =System.getProperties();//设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port",port);
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf= newMailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "false");
properties.put("mail.smtp.ssl.socketFactory", sf);//获取默认session对象
Session session = Session.getDefaultInstance(properties, newAuthenticator() {public PasswordAuthentication getPasswordAuthentication() { //qq邮箱服务器账户、第三方登录授权码
return new PasswordAuthentication(from, pass); //发件人邮件用户名、密码
}
});try{//创建默认的 MimeMessage 对象
MimeMessage message = newMimeMessage(session);//Set From: 头部头字段
message.setFrom(newInternetAddress(from));//Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO, newInternetAddress(mailEntity.getMailReceiverAddress()));//Set Subject: 主题文字
String subject = MimeUtility.encodeWord(mailEntity.getMailSubject(), "UTF-8", "Q");
message.setSubject(subject);//创建消息部分
BodyPart messageBodyPart = newMimeBodyPart();//消息//messageBodyPart.setText(mailEntity.getMailContent());
messageBodyPart.setContent(mailEntity.getMailContent(), "text/html;charset=utf-8");//创建多重消息
Multipart multipart = newMimeMultipart();//设置文本消息部分
multipart.addBodyPart(messageBodyPart);if (mailEntity.getFilePaths() != null && mailEntity.getFilePaths().size() > 0) {for(String filePath : mailEntity.getFilePaths()) {//附件部分
messageBodyPart = newMimeBodyPart();
String suffix= "";
String oldPath= "";if (filePath.indexOf(".") >0){
suffix= filePath.substring(filePath.indexOf(".")+1);
oldPath= filePath.substring(0,filePath.indexOf("."));
DataSource source= newFileDataSource(oldPath);
File file=((FileDataSource) source).getFile();
file.renameTo(new File(oldPath + "." +suffix));
source= newFileDataSource(filePath);
messageBodyPart.setDataHandler(newDataHandler(source));
}else{//设置要发送附件的文件路径
DataSource source = newFileDataSource(filePath);
messageBodyPart.setDataHandler(newDataHandler(source));
}//设置要发送附件的文件路径//messageBodyPart.setFileName(filename);//处理附件名称中文(附带文件路径)乱码问题
messageBodyPart.setFileName(MimeUtility.encodeText(filePath));
multipart.addBodyPart(messageBodyPart);
}
}//发送完整消息
message.setContent(multipart);//发送消息
Transport.send(message);
logger.info("Sent mail successfully....");return true;
}catch(MessagingException e) {
logger.debug(e.getMessage());
}catch(UnsupportedEncodingException e) {
logger.debug(e.getMessage());
}return false;
}