packagecom.thinkgem.jeesite.common.utils;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importjava.util.Date;importjava.util.Enumeration;importjava.util.Properties;importjava.util.Vector;import javax.activation.*;importjavax.mail.Authenticator;importjavax.mail.Message;importjavax.mail.Multipart;importjavax.mail.PasswordAuthentication;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeBodyPart;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeMultipart;importjavax.mail.internet.MimeUtility;/***
* Title: 使用javamail发送邮件
*
*/
public classMailUtils {private static Logger logger = LoggerFactory.getLogger(MailUtils.class);
String to= "";//收件人
String toCC = "";//抄送
String toBcc = "";//密送
String from = "";//发件人
String host = "";//smtp主机
String port = "";
String username= "";
String password= "";
String filename= "";//附件文件名
String subject = "";//邮件主题
String content = "";//邮件正文
String imagepath = "";//图片路径
Vector file = new Vector();//附件文件集合
publicString getImagepath() {returnimagepath;
}public voidsetImagepath(String imagepath) {this.imagepath =imagepath;
}/***
* 方法说明:默认构造器
* 输入参数:
* 返回类型:*/
publicMailUtils() {
}/***
* 方法说明:构造器,提供直接的参数传入
* 输入参数:
* 返回类型:*/
publicMailUtils(String to, String from, String smtpServer,
String username, String password, String subject, String content) {this.to =to;this.from =from;this.host =smtpServer;this.username =username;this.password =password;this.subject =subject;this.content =content;
}public voidsetPort(String port){this.port =port;
}/***
* 方法说明:设置邮件服务器地址
* 输入参数:String host 邮件服务器地址名称
* 返回类型:*/
public voidsetHost(String host) {this.host =host;
}/***
* 方法说明:设置登录服务器校验密码
* 输入参数:
* 返回类型:*/
public voidsetPassWord(String pwd) {this.password =pwd;
}/***
* 方法说明:设置登录服务器校验用户
* 输入参数:
* 返回类型:*/
public voidsetUserName(String usn) {this.username =usn;
}/***
* 方法说明:设置邮件发送目的邮箱
* 输入参数:
* 返回类型:*/
public voidsetTo(String to) {this.to =to;
}/*** 设置抄送者
*
**/
public voidsetToCC(String to){this.toCC =to;
}public voidsetToBcc(String to){this.toBcc =to;
}/***
* 方法说明:设置邮件发送源邮箱
* 输入参数:
* 返回类型:*/
public voidsetFrom(String from) {this.from =from;
}/***
* 方法说明:设置邮件主题
* 输入参数:
* 返回类型:*/
public voidsetSubject(String subject) {this.subject =subject;
}/***
* 方法说明:设置邮件内容
* 输入参数:
* 返回类型:*/
public voidsetContent(String content) {this.content =content;
}/***
* 方法说明:把主题转换为中文
* 输入参数:String strText
* 返回类型:*/
publicString transferChinese(String strText) {try{
strText= MimeUtility.encodeText(new String(strText.getBytes("UTF-8"),"UTF-8"), "UTF-8", "B");
}catch(Exception e) {
e.printStackTrace();
}returnstrText;
}/***
* 方法说明:往附件组合中添加附件
* 输入参数:
* 返回类型:*/
public voidattachfile(String fname) {
file.addElement(fname);
}/***
* 方法说明:发送邮件
* 输入参数:
* 返回类型:boolean 成功为true,反之为false*/
public booleansendMail() {
logger.info("------开始发邮件------");//构造mail session
Properties props = newProperties() ;
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");if(port != "")
props.put("mail.smtp.port", port);
Session session=Session.getDefaultInstance(props,newAuthenticator() {publicPasswordAuthentication getPasswordAuthentication() {return newPasswordAuthentication(username, password);
}
});//Session session = Session.getDefaultInstance(props);//Session session = Session.getDefaultInstance(props, null);
try{//构造MimeMessage 并设定基本的值
MimeMessage msg = newMimeMessage(session);//MimeMessage msg = new MimeMessage();
msg.setFrom(newInternetAddress(from));//msg.addRecipients(Message.RecipientType.TO, address);//这个只能是给一个人发送email//设置接收者
if(!Empty2String(to))
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)) ;//设置抄送者
if(!Empty2String(toCC))
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(toCC)) ;//设置密送者
if(!Empty2String(toBcc))
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(toBcc)) ;
subject=transferChinese(subject);
msg.setSubject(subject);//构造Multipart
Multipart mp = newMimeMultipart();//向Multipart添加正文
MimeBodyPart mbpContent = newMimeBodyPart();
mbpContent.setContent(content,"text/html;charset=gb2312");//向MimeMessage添加(Multipart代表正文)
mp.addBodyPart(mbpContent);//向Multipart添加附件
Enumeration efile =file.elements();while(efile.hasMoreElements()) {
MimeBodyPart mbpFile= newMimeBodyPart();
filename=efile.nextElement().toString();
FileDataSource fds= newFileDataSource(filename);
mbpFile.setDataHandler(newDataHandler(fds));////这个方法可以解决附件乱码问题。
String filename= new String(fds.getName().getBytes(),"ISO-8859-1");
mbpFile.setFileName(filename);//向MimeMessage添加(Multipart代表附件)
mp.addBodyPart(mbpFile);
}
file.removeAllElements();//向Multipart添加MimeMessage
msg.setContent(mp);
msg.setSentDate(newDate());
msg.saveChanges() ;//发送邮件
Transport transport= session.getTransport("smtp");
transport.connect(host, username, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}catch(Exception mex) {
mex.printStackTrace();
logger.info("---发邮件报错信息----"+mex.getMessage());//Exception ex = null;//if ((ex = mex.getNextException()) != null) {//ex.printStackTrace();//}
return false;
}return true;
}/***
* 发送带有图片的邮件
*@return
*/
public booleansendPicMail() {
logger.info("------开始发邮件------");//构造mail session
Properties props = newProperties() ;
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");if(port != "")
props.put("mail.smtp.port", port);
Session session=Session.getDefaultInstance(props,newAuthenticator() {publicPasswordAuthentication getPasswordAuthentication() {return newPasswordAuthentication(username, password);
}
});//Session session = Session.getDefaultInstance(props);//Session session = Session.getDefaultInstance(props, null);
try{//构造MimeMessage 并设定基本的值
MimeMessage msg = newMimeMessage(session);//MimeMessage msg = new MimeMessage();
msg.setFrom(newInternetAddress(from));//msg.addRecipients(Message.RecipientType.TO, address);//这个只能是给一个人发送email//设置接收者
if(!Empty2String(to))
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)) ;//设置抄送者
if(!Empty2String(toCC))
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(toCC)) ;//设置密送者
if(!Empty2String(toBcc))
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(toBcc)) ;
subject=transferChinese(subject);
msg.setSubject(subject);//构造Multipart
MimeMultipart mp = new MimeMultipart("related");//向Multipart添加正文
MimeBodyPart mbpContent = newMimeBodyPart();
mbpContent.setContent(content,"text/html;charset=gb2312");//向MimeMessage添加(Multipart代表正文)
mp.addBodyPart(mbpContent);//second part (the image)
MimeBodyPart imageBodyPart = newMimeBodyPart();
DataSource imageds= newFileDataSource(imagepath);
imageBodyPart.setDataHandler(newDataHandler(imageds));
imageBodyPart.setHeader("Content-ID","");
imageBodyPart.setHeader("Content-Type", "image/png");
imageBodyPart.setDisposition(MimeBodyPart.INLINE);
imageBodyPart.setFileName("attach.png");//add it
mp.addBodyPart(imageBodyPart);//向Multipart添加附件
Enumeration efile =file.elements();while(efile.hasMoreElements()) {
MimeBodyPart mbpFile= newMimeBodyPart();
filename=efile.nextElement().toString();
FileDataSource fds= newFileDataSource(filename);
mbpFile.setDataHandler(newDataHandler(fds));////这个方法可以解决附件乱码问题。
String filename= new String(fds.getName().getBytes(),"ISO-8859-1");
mbpFile.setFileName(filename);//向MimeMessage添加(Multipart代表附件)
mp.addBodyPart(mbpFile);
}
file.removeAllElements();//向Multipart添加MimeMessage
msg.setContent(mp);
msg.setSentDate(newDate());
msg.saveChanges() ;//发送邮件
Transport transport= session.getTransport("smtp");
transport.connect(host, username, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}catch(Exception mex) {
mex.printStackTrace();
logger.info("---发邮件报错信息----"+mex.getMessage());//Exception ex = null;//if ((ex = mex.getNextException()) != null) {//ex.printStackTrace();//}
return false;
}return true;
}public static booleanEmpty2String(String str){return str == null || "".equals(str) || "null".equals(str) || "NULL".equals(str);
}/***
* 方法说明:主方法,用于测试
* 输入参数:
* 返回类型:*/
public static voidmain(String[] args) {
MailUtils sendmail= newMailUtils();
sendmail.setHost("smtp.cmge.com");
sendmail.setUserName("system.omss@cmge.com");
sendmail.setFrom("system.omss@cmge.com");
sendmail.setPassWord("XXXXX");
sendmail.setTo("lu.shiqin@cmge.com,system.omss@cmge.com");//sendmail.setToCC("");
sendmail.setSubject("你好22,这是测ddddd试!");
sendmail.setContent("
你好这是一个带多附件多人发送的的测试!~~~~~~~~~~~~~~~~~~~~~~~~~
"+"
");