package web.iframe.javaMail;
import impl.omreport.util.EmailCfgCplain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.;
import javax.mail.internet.;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
/**
-
Created by ycl on 2018/11/16.
*/
public class EmailSender {
private static Logger log = LoggerFactory.getLogger(EmailSender.class) ;
public static boolean sendMail(EmailCfgCplain mailInfo, File file, String title, String content) {
boolean sendStatus = false;//发送状态
String mailtype = “text/html;charset=GBK”;
// 判断是否需要身份认证
EmailAuthenticator authenticator = null;
Properties pro = new Properties();
pro.put(“mail.smtp.host”, “mail.ultrapower.com.cn”);
pro.put(“mail.smtp.port”, 587);
pro.put(“mail.smtp.auth”, “true” );
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new EmailAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getInstance(pro, authenticator);
//【调试时使用】开启Session的debug模式
sendMailSession.setDebug(true);
try {
// 根据session创建一个邮件消息
MimeMessage mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFrom());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
List toAddress=mailInfo.getList();
Address[] tos=new Address[toAddress.size()];
for(int i=0;i<toAddress.size();i++){
Address to = new InternetAddress(toAddress.get(i));
tos[i]=to;
}
mailMessage.setRecipients(Message.RecipientType.TO,tos);
// 设置邮件消息的主题
mailMessage.setSubject(title, “UTF-8”);// 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); //文字部分 MimeMultipart multipart = new MimeMultipart("mixed"); BodyPart msgBodyPart = new MimeBodyPart(); msgBodyPart.setContent(content, mailtype); multipart.addBodyPart(msgBodyPart); //附件部分 BodyPart attBodyPart = new MimeBodyPart(); DataSource ds= new FileDataSource(file); attBodyPart.setDataHandler(new DataHandler(ds)); attBodyPart.setFileName(MimeUtility.encodeText(ds.getName())); multipart.addBodyPart(attBodyPart); mailMessage.setContent(multipart); // 发送邮件 Transport.send(mailMessage); sendStatus = true; } catch (MessagingException ex) { log.error("以文本格式发送邮件出现异常", ex); return sendStatus; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return sendStatus;
}
}