Email邮件应用类

来源:互联网 发布:js pageyoffset 编辑:程序博客网 时间:2024/06/16 13:41
package com.jswhzl.lease.common.util;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.Multipart;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.mail.internet.MimeUtility;import com.jswhzl.lease.common.config.Constants;import com.jswhzl.lease.entity.SendEmail;import com.sun.mail.util.MailSSLSocketFactory;import java.io.File;import java.io.UnsupportedEncodingException;import java.util.List;import java.util.Properties;/*@Service*/public  class   Email {  private static Email email = null;  /**      *       * @function:获得单例      */      public static Email getInstance()      {          if(email==null)          {              synchronized (Email.class)               {                  if(email==null) {                  email = new Email();                  }              }          }          return email;      }   /** * 发送邮件 *  * @param mailTo *            收件人 * @param title *            邮件主题 * @param content *            邮件内容 换行采用\n * @param attachment *            附件文件,可为null * @throws Exception */public void send(SendEmail send, File attachment) throws Exception {Properties props = new Properties();props.setProperty("mail.transport.protocol", Constants.EMAIL_PROTOCOL_TYPE); // 使用的协议(JavaMail规范要求)props.setProperty("mail.smtp.host", "smtp."+Constants.SENDER_EMAIL_SMTP_HOST+".com"); // 发件人的邮箱的// SMTP// 服务器地址props.setProperty("mail.smtp.auth", "true"); // 需要请求认证MailSSLSocketFactory sf = new MailSSLSocketFactory();sf.setTrustAllHosts(true);props.put("mail.smtp.ssl.enable", "true");props.put("mail.smtp.ssl.socketFactory", sf);// 用刚刚设置好的props对象构建一个sessionSession session = Session.getDefaultInstance(props);// 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使// 用(你可以在控制台(console)上看到发送邮件的过程)session.setDebug(true);// 用session为参数定义消息对象MimeMessage message = new MimeMessage(session);try {String nick = "";try {nick = javax.mail.internet.MimeUtility.encodeText(send.getName());} catch (UnsupportedEncodingException e) {e.printStackTrace();}message.setFrom(new InternetAddress(nick + " <" + send.getUserName() + ">"));// 加载发件人地址// message.setFrom(new InternetAddress(from));if (send.getRecipients() == null || send.getRecipients().size() == 0) {throw new Exception("收件人不能为空");}if (send.getSubject() == null || "".equals(send.getSubject())) {throw new Exception("主题不能为空");}if (send.getContent() == null || "".equals(send.getContent())) {throw new Exception("邮件正文不能为空");}/* * // 加载收件人地址 message.addRecipients(Message.RecipientType.TO, * InternetAddress.parse(getMailList(mailTo))); //抄送 if(cs!=null && * cs.length>0) { message.setRecipients(Message.RecipientType.CC, * InternetAddress.parse(getMailList(cs))); // 抄送人 } */if (send.getRecipients() != null && send.getRecipients().size() > 0) {message.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(getMailList(send.getRecipients()))); // 密送人}// 加载标题message.setSubject(send.getSubject());// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件Multipart multipart = new MimeMultipart();// 设置邮件的文本内容BodyPart contentPart = new MimeBodyPart();contentPart.setContent(send.getContent(), "text/html;charset=gb2312");// contentPart.setText(content);multipart.addBodyPart(contentPart);if (attachment != null) {BodyPart attachmentBodyPart = new MimeBodyPart();DataSource source = new FileDataSource(attachment);attachmentBodyPart.setDataHandler(new DataHandler(source));// 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码// MimeUtility.encodeWord可以避免文件名乱码attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));multipart.addBodyPart(attachmentBodyPart);}// 将multipart对象放到message中message.setContent(multipart);// 保存邮件message.saveChanges();// 发送邮件Transport transport = session.getTransport("smtp");// 连接服务器的邮箱System.out.println(send.getUserName() + "_--------" + send.getPassword());transport.connect("smtp."+Constants.SENDER_EMAIL_SMTP_HOST+".com", send.getUserName(), send.getPassword());// 把邮件发送出去transport.sendMessage(message, message.getAllRecipients());transport.close();} catch (Exception e) {e.printStackTrace();throw e;}}private String getMailList(List<String> mailArray) {StringBuffer toList = new StringBuffer();int length = mailArray.size();if (mailArray != null && length < 2) {toList.append(mailArray.get(0));} else {for (int i = 0; i < length; i++) {toList.append(mailArray.get(i));if (i != (length - 1)) {toList.append(",");}}}return toList.toString();}       }