首页 > 代码库 > 发送邮件

发送邮件

  1 package com.mall.information.pushemail;  2   3 import java.net.URL;  4 import java.net.URLEncoder;  5 import java.util.Date;  6 import java.util.Properties;  7   8 import javax.activation.DataHandler;  9 import javax.activation.DataSource; 10 import javax.activation.FileDataSource; 11 import javax.activation.URLDataSource; 12 import javax.mail.BodyPart; 13 import javax.mail.Message; 14 import javax.mail.MessagingException; 15 import javax.mail.Multipart; 16 import javax.mail.Session; 17 import javax.mail.Transport; 18 import javax.mail.internet.InternetAddress; 19 import javax.mail.internet.MimeBodyPart; 20 import javax.mail.internet.MimeMessage; 21 import javax.mail.internet.MimeMultipart; 22 import javax.mail.internet.MimeUtility; 23  24  25 import org.apache.commons.lang.StringUtils; 26 import org.apache.log4j.Logger; 27  28 public class EmailSender { 29      30     private static final Logger log = Logger.getLogger(EmailSender.class); 31      32     /** 33      * 获取附件名字 34      *  35      * @param fileName 36      * @return 37      */ 38     private static String getLastName(String fileName) { 39         int pos = fileName.lastIndexOf("\\"); 40         if (pos > -1) { 41             fileName = fileName.substring(pos + 1); 42         } 43         pos = fileName.lastIndexOf("/"); 44         if (pos > -1) { 45             fileName = fileName.substring(pos + 1); 46         } 47         return fileName; 48  49     } 50  51     /** 52      * 邮件批量发送 53      * @throws MessagingException  54      * @throws Exception  55      */ 56     public static boolean sendMail(String from, String pwd, String smtp, String mailTo, String mailSubject,String mailBody,String appendUrl,String apptitle,String nickname) { 57         // 发送email 58         Transport transport = null; 59         try { 60             String smtpServer = smtp;// smtp服务器地址 61             // String smtpServer = "smtp.163.com"; //smtp服务器地址 62             String From = from; // 来源的mail 63             String Subject = mailSubject; 64             String Text = mailBody; 65             //Properties props = System.getProperties(); 66             Properties props = new Properties(); 67             props.put("mail.smtp.host", smtpServer); 68             props.put("mail.smtp.auth", "true"); 69             log.info("正在创建mailsession......"); 70             Session sendMailSession = Session.getDefaultInstance(props); 71             // sendMailSession.setDebug(true); 72             log.info("正在创建MimeMessage......"); 73              74             Message newMessage = new MimeMessage(sendMailSession); 75              76 //            newMessage.setFrom(new InternetAddress(From));//无昵称 77             newMessage.setFrom(new InternetAddress(From,nickname)); 78              79             newMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(mailTo)); 80             newMessage.setSubject(Subject); 81             newMessage.setSentDate(new Date()); 82             if(StringUtils.isEmpty(appendUrl)){ 83                 //无附件 84                 log.info("创建无附件邮件....."); 85                 newMessage.setContent(Text, "text/html;charset=UTF-8"); 86                 newMessage.saveChanges(); 87             }else{ 88                 //带附件 89                 log.info("创建带附件邮件....."); 90                 Multipart multipart = new MimeMultipart("mixed");  91                  //设置邮件的文本内容 92                 BodyPart contentPart = new MimeBodyPart(); 93                 contentPart.setContent(mailBody,"text/html; charset=utf-8");   94                 multipart.addBodyPart(contentPart); 95                  96                 //添加附件 97                 BodyPart messageBodyPart= new MimeBodyPart(); 98                  99                 //设置信件的附件1(本地文件作为附件)100                 //DataSource source = new FileDataSource(appendUrl);101                 102                 //设置信件的附件2(用远程文件作为附件)103                 contentPart=new MimeBodyPart();104                 URL urlfj=new URL(appendUrl);105                 URLDataSource source=new URLDataSource(urlfj);106                 107                 //添加附件的内容108                 messageBodyPart.setDataHandler(new DataHandler(source));109                 //添加附件的标题110                 //String apptitle = appendUrl.substring(appendUrl.lastIndexOf(‘/‘)+1);111                 //这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码112 //                sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();113 //                messageBodyPart.setFileName(MimeUtility.encodeText("性能测试准备阶段调研清单20140122.doc"));114 //                String a = java.net.URLEncoder.encode("性能测试准备阶段调研清单20140122.doc", "UTF-8");115 //                messageBodyPart.setFileName(java.net.URLDecoder.decode(a,"utf-8"));116 //                messageBodyPart.setFileName(apptitle);117                 messageBodyPart.setFileName(MimeUtility.encodeText(apptitle, "GBK", null));118                 119 //                System.out.println(messageBodyPart.getFileName());120 //                messageBodyPart.setFileName("=?UTF-8?"+enc.encode(apptitle.getBytes())+"?=");121                 //sun.misc.BASE64Encoder bs64en = new sun.misc.BASE64Encoder();122                 //String save = bs64en.encode(apptitle.getBytes());123                 //String save_utf8 = URLEncoder.encode(save,"utf-8");124                 125                 //messageBodyPart.setFileName(save_utf8);126                 127                 multipart.addBodyPart(messageBodyPart);      128                 //将multipart对象放到message中129                 newMessage.setContent(multipart);130                 //保存邮件131                 newMessage.saveChanges();132             }133 134             log.info("正在联接smtp......");135             136             transport = sendMailSession.getTransport("smtp");137             transport.connect(smtpServer, from, pwd);138             log.info("Transport is connected : " + transport.isConnected());139 140             log.info("正在发送......" + mailTo + "   "141                     + newMessage.getAllRecipients() + "----------------");142             transport.sendMessage(newMessage, newMessage.getAllRecipients());143             System.out.println("发送成功......");144             transport.close();145         } catch (Exception mailEx) {146             log.info("Send Mail Error:" + mailEx.getMessage());147             mailEx.printStackTrace();148             log.info("================Send Mail Error:===========" + mailEx.getMessage());149             return false;150         } finally {151             try {152                 transport.close();153                 154             } catch (MessagingException e) {155                 e.printStackTrace();156             }157         }158         return true;159     }160 161     /**162      * 测试方法163      * 164      * @param args165      */166     public static void main(String[] args) {167         //D:\space\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\MallManager\space/1394514922266.doc168         //169 //        String url = "D:\\性能测试准备阶段调研清单20140122.doc";170 //        String appendUrl = "D:\\space\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp1\\wtpwebapps\\MallManager\\space/1395387816920.txt";171         String appendUrl = "http://***/manager/space/2014/4/23/1.TXT";172 //        System.out.println(url);173 //        System.out.println(url.substring(url.lastIndexOf(‘\\‘)+1));174 //        String from, String pwd, String smtp, String mailTo, String mailSubject,String mailBody175 //        String apptitle = appendUrl.substring(appendUrl.lastIndexOf(‘/‘)+1);   mail.ecitic.com176177 //        sendMail("***01@163.com","***","smtp.163.com","***03@163.com","!!!反反复复","qqq!!!@S反反复复<br type=‘_moz‘ />",appendUrl,"测试中文附件!@q11.js","测试昵称");178 //        sendMail("**01@163.com","***","smtp.163.com","***03@163.com","!!!反反复复","qqq!!!@S反反复复<br type=‘_moz‘ />","","","测试昵称");179     }180 }