java web郵件收發

來源:互聯網
上載者:User

標籤:

1.網上方法要匯入兩個包    

mail.jar&activation.jar
package com.zjh.shopping.util;import java.util.Date;  import java.util.Properties;   import javax.activation.DataHandler;  import javax.activation.FileDataSource;  import javax.mail.Authenticator;  import javax.mail.Multipart;  import javax.mail.PasswordAuthentication;  import javax.mail.internet.InternetAddress;  import javax.mail.internet.MimeBodyPart;  import javax.mail.internet.MimeMultipart;  import javax.mail.internet.MimeUtility;    public class JavaMailSendUtil {            public  void sendmail(String subject, String from, String[] to,              String text, String[] filenames, String mimeType) {          try {              Properties props = new Properties();               String smtp = "smtp.163.com"; // 設定發送郵件所用到的smtp              String servername = "*******";  //郵箱帳號名            String serverpaswd = "******";  //郵箱密碼             javax.mail.Session mailSession = null; // 郵件會話對象              javax.mail.internet.MimeMessage mimeMsg = null; // MIME 郵件對象               props = java.lang.System.getProperties(); // 獲得系統屬性對象              props.put("mail.smtp.host", smtp); // 設定SMTP主機              props.put("mail.smtp.auth", "true"); // 是否到伺服器使用者名稱和密碼驗證              // 到伺服器驗證發送的使用者名稱和密碼是否正確              SmtpAuthenticator myEmailAuther = new SmtpAuthenticator(servername,                      serverpaswd);              // 設定郵件會話 注意這裡將認證資訊放進了Session的建立參數裡              mailSession = javax.mail.Session.getInstance(props,                      (Authenticator) myEmailAuther);              // 設定傳輸協議              javax.mail.Transport transport = mailSession.getTransport("smtp");             // 設定from、to等資訊             mimeMsg = new javax.mail.internet.MimeMessage(mailSession);             if (null != from && !"".equals(from)) {                 InternetAddress sentFrom = new InternetAddress(from);                 mimeMsg.setFrom(sentFrom); // 設定發送人地址             }              InternetAddress[] sendTo = new InternetAddress[to.length];             for (int i = 0; i < to.length; i++) {                 System.out.println("發送到:" + to[i]);                 sendTo[i] = new InternetAddress(to[i]);             }              mimeMsg.setRecipients(                     javax.mail.internet.MimeMessage.RecipientType.TO, sendTo);             mimeMsg.setSubject(subject, "gb2312");              MimeBodyPart messageBodyPart1 = new MimeBodyPart();             // messageBodyPart.setText(UnicodeToChinese(text));             messageBodyPart1.setContent(text, mimeType);              // 附件傳輸格式             Multipart multipart = new MimeMultipart();             multipart.addBodyPart(messageBodyPart1);              for (int i = 0; i < filenames.length; i++) {                 MimeBodyPart messageBodyPart2 = new MimeBodyPart();                  String filename = filenames[i].split(";")[0];                 String displayname = filenames[i].split(";")[1];                 // 得到資料來源                 FileDataSource fds = new FileDataSource(filename);                 // BodyPart添加附件本身                 messageBodyPart2.setDataHandler(new DataHandler(fds));                 // BodyPart添加附件檔案名稱                 messageBodyPart2.setFileName(MimeUtility                         .encodeText(displayname));                 multipart.addBodyPart(messageBodyPart2);             }             mimeMsg.setContent(multipart);             // 設定信件頭的發送日期             mimeMsg.setSentDate(new Date());             mimeMsg.saveChanges();             // 發送郵件             transport.send(mimeMsg);             transport.close();             System.out.println("發送到成功!!!");         } catch (Exception e) {             e.printStackTrace();         }     }          public static void main(String[] args) throws Exception {         String title = "測試郵件";// 所發送郵件的標題         String from = "************@163.com";// 從那裡發送         String sendTo[] = { "********@qq.com" };// 發送到那裡         // 郵件的常值內容,可以包含html標記則顯示為html頁面         String content = "test java send mail !!!!!!<br><a href="http://sjsky.javaeye.com/">My blog</a>";       // 所包含的附件,及附件的重新命名       String fileNames[] = { "d:\\test.jpg;test.jpg" };       JavaMailSendUtil test = new JavaMailSendUtil();       try {           // MailSender mailsender = new MailSender();           test.sendmail(title, from, sendTo, content, fileNames,                   "text/html;charset=gb2312");       } catch (Exception ex) {           ex.printStackTrace();       }   }      class SmtpAuthenticator extends Authenticator {       String username = null;       String password = null;             public SmtpAuthenticator(String username, String password) {           super();           this.username = username;           this.password = password;       }             public PasswordAuthentication getPasswordAuthentication() {           return new PasswordAuthentication(this.username, this.password);         }     }  }  

2.自己用的

package com.gree.mail.mailsend;import java.util.Properties;import javax.mail.Message;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.naming.InitialContext;import javax.naming.NamingException;import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;public class Mailsend2 {        public static Session getSession() {    Session session = null;    //      session = (Session)new InitialContext().lookup("MailSession");            Properties props = new Properties();      props.put("mail.smtp.host", "10.1.1.168");      props.put("mail.smtp.auth", "false");      session = Session.getDefaultInstance(props, null);        return session;}public static void sendMessage(String from, String[] to, String[] cc, String subject, String content,                                 String mimeType) throws javax.mail.MessagingException {    Message message = new MimeMessage(getSession());    if (!StringUtils.isEmpty(from)) {      InternetAddress sentFrom = new InternetAddress(from);      message.setFrom(sentFrom);    }    InternetAddress[] sendTo = new InternetAddress[to.length];    for (int i = 0; i < to.length; i++) {      sendTo[i] = new InternetAddress(to[i]+"@gree.com.cn");    }    if ( (cc.length > 0) && (cc[0] != null)) {      InternetAddress[] copyTo = new InternetAddress[cc.length];      for (int i = 0; i < cc.length; i++) {        copyTo[i] = new InternetAddress(cc[i]+"@gree.com.cn");      }      message.setRecipients(Message.RecipientType.CC, copyTo);    }    message.setRecipients(Message.RecipientType.TO, sendTo);    //System.out.println("發送人員:"+message.getRecipients(Message.RecipientType.TO));    //System.out.println("抄送人員:"+message.getRecipients(Message.RecipientType.CC))    message.setSubject(subject);    message.setContent(content, mimeType);    Transport.send(message); } public void sendHTMLMessage(String[] to, String[] cc, String title, String content)throws MessagingException {            try {        sendMessage("SCBWEB", to, cc, title+"-模具管理系統資訊", content, "text/html;Charset=gb2312");    } catch (javax.mail.MessagingException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }         // System.out.println("2="+content);}public static void main(String[] args) {    String [] to= new String[] {"180172"};    String [] cc= new String[] {"180158"};    String title="ceshi";    String content="晚上小天請我們吃烤魚,8號門對面,大概67點左右,等下下班別走開";    try {        Mailsend2.sendMessage("[email protected]", to, cc, title, content, "text/html;Charset=utf-8");    } catch (javax.mail.MessagingException e) {        // TODO Auto-generated catch block        e.printStackTrace();}    }}
myeclipse中發送郵件出現Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream

出現這個問題的原因是jar包版本不統一,解決方案如下:
我在項目匯入了jar包

與myeclipse內建jar衝突了

刪除Java EE 5 Libraries/javaee.jar/mail裡的包有東西.

具體操作:

進入myeclipse的安裝目錄:我安裝的是myeclipse blue 8.5 具體路徑如下

E:\development_tools\myeclipse_8.5\install_d\common\plugins\com.genuitec.eclipse.j2eedt.core_8.5.0.me201003231033\data\libraryset\EE_5

找到javaee.jar,開啟後刪除mail檔案夾即可(需要先關閉運行著的myeclipse,否則無法刪除)

java web郵件收發

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.