STRUTS2 Integrated JavaMail e-mail sample detailed

Source: Internet
Author: User
Tags auth mail

  This article mainly introduces the STRUTS2 integrated JavaMail Email example, you need friends can refer to the following

One, code preview these two days on doing struts2 on the mail sent. Previous projects were useful to spring, and the mail support classes provided with spring were handy for this function, but now with STRUTS2, there are a series of problems.   Please first download the Mail.jar, and Activation.jar add to the classpath     code as follows: Package com.nerve.cloudoffice.common.util;   Import java.util.List; Import java.util.Properties;   Import Javax.activation.DataHandler; Import Javax.activation.FileDataSource; Import javax.mail.Address; 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;   public class Emailsender {     /**      * email to user      */  &NBS P Private static final long serialversionuid = 1L;       private mimemessage mimemsg; MIME Mail objects       private Session session; Mail Session object       private Properties props; System Properties       Private Boolean needauth = false; SMTP requires authentication       Private String username = ""; SMTP authenticated user name and password       private String password = "";       Private Multipart MP; Multipart object, mail content, title, attachment, etc. are added to the following to generate       private String log;       Public Emailsender () {     }       public emailsender (String SMTP) {         setsmtphost (SMTP);         createmimemessage ();    }       public void Setsmtphost (String hostName) {        SYSTEM.OUT.PRI NTLN ("Set system properties: Mail.smtp.host =" + HostName);         if (props = null)             props = system.getproperties (); Get the System Properties object         props.put ("Mail.smtp.host", hostName); Set SMTP host     &NBSp   Props.put ("Mail.smtp.localhost", "localhostadress");    }       public boolean createmimemessage () {        try {            SYSTEM.OUT.PRINTLN ("Ready to get mail Session Object!") ");             session = session.getdefaultinstance (props, null); Get mail Session object        } catch (Exception e) {            log = "Get mail Session Object An error has occurred! "+ e.tostring ();             SYSTEM.ERR.PRINTLN (log);             return false;        }         try {            mimemsg = new Mi Memessage (session); Create MIME mail object             MP = new Mimemultipart (); MP a Multipart object            //Multipart is a container this holds multiple body parts.             RETurn true;        } catch (Exception e) {            log = "Failed to create MIME mail Object!") "+ E;             SYSTEM.ERR.PRINTLN (log);             return false;        }     {      public void Setneedauth (Boolean need) {    & nbsp   SYSTEM.OUT.PRINTLN ("Set SMTP identity authentication: Mail.smtp.auth =" + need);         if (props = null)             props = system.getproperties ();         if (need) {            props.put ("Mail.smtp.auth", "true"); &NB Sp      } else {            props.put ("Mail.smtp.auth", "false");   &NBSP ;    }    }       public void Setnamepass (String name, String Pass) {    &NB Sp   SYSTEM.OUT.PRINTLN ("program gets username and password");         username = name;         password = pass;    }       public boolean setsubject (String mailsubject) {        System.ou T.PRINTLN ("Set message subject!") ");         try {            Mimemsg.setsubject (Mimeutility.encodetext Mail Subject, "Utf-8", "B"));             return true;        } catch (Exception e) {            log = "Set Message subject Error!" "+E;             SYSTEM.ERR.PRINTLN (log);             return false;        }     {      public boolean setbody (String mailbody) {        try {            SYSTEM.OUT.PRINTLN ("Set up mail Format");             BodyPart bp = new MimeBodyPart ();            //conversioninto Chinese format             bp.setcontent (                &NB Sp   "<meta Http-equiv=content-type content=text/html; Charset=utf-8> "                            + mai Lbody, "Text/html;charset=utf-8");             Mp.addbodypart (BP);             return true;        } catch (Exception e) {            log = "Error setting message body"! "+ E;             SYSTEM.ERR.PRINTLN (log);             return false;        }     {      public boolean setfiles (list<string> files) {&nbs P       try{            for (String s:files) {        &NBSP ;       MimeBodyPart mbp=new MimeboDypart ();                   Filedatasource fds=new Filedatasource (s); Get data source                   Mbp.setdatahandler (new DataHandler (FDS)); Get the attachment itself and into the bodypart                   Mbp.setfilename (Fds.getname ());  //get filename Same to enter BodyPart                   Mp.addbodypart (MBP);                         return true;        }catch (Exception e) {            log = "Error adding attachment:" +E;   &nbs P         e.printstacktrace ();             return false;        }     {      public boolean addfile (string path, string name) {&nbsp ;       try{            MimeBodyPart mbp=new MimebOdypart ();               Filedatasource fds=new filedatasource (path); Get data source               Mbp.setdatahandler (new DataHandler (FDS)); Get the attachment itself and into the bodypart               Mbp.setfilename (mimeutility.encodetext name, " Utf-8 "," B "));             Mp.addbodypart (MBP);             return true;        }catch (Exception e) {            log = "Error adding attachment:" +E;   &nbs P         e.printstacktrace ();             return false;        }     {      public boolean setfrom (String from) {    &NB Sp   SYSTEM.OUT.PRINTLN ("Set sender!") ");         try {            Mimemsg.setfrom (new InternetAddress (from)); Set up sender            return true;        } catch (Exception e) {            log = "Set the sender error:" +E;             return false;        }     {      public boolean setto (String to) {        SYSTEM.OUT.PRINTLN ("Set up the addressee");         if (to = = null)             return false;         try {            mimemsg.setrecipients (Message.RecipientType.TO , internetaddress                     Parse (to);             return true;        } catch (Exception e) {            return false;        }    }       public boolean setcopyto (String copyto) {        if (CopyTo = null) &NBsp           return false;         try {            mimemsg.setrecipients (Message.RecipientType.CC ,                     (address[]) Internetaddress.parse (CopyTo));             return true;        } catch (Exception e) {            return false;        }    }       public boolean sendout () {        try {  & nbsp         Mimemsg.setcontent (MP);             mimemsg.savechanges ();             SYSTEM.OUT.PRINTLN ("Sending mail ...");             Session mailsession = session.getinstance (props, null);             Transport transport = Mailsession.gettransport ("SMTP");            Transport.connect ((String) props.get ("Mail.smtp.host"), username,                     password);             Transport.sendmessage (mimemsg, mimemsg                    . Getrecipients (Message.RecipientType.TO));            //Transport.send (MIMEMSG);             SYSTEM.OUT.PRINTLN ("Send mail success!") ");             transport.close ();             return true;        } catch (Exception e) {            log = "message sent failed! "+ E;             SYSTEM.ERR.PRINTLN (log);             return false;        }     {      public String GetLog () {        RET Urn log; &nbSp  }     II, problem summary   2.1   Local execution times wrong   I use the Java EE 5,jdk1.6, when running locally, there will be ClassNotFound exception, but these The class is also mail.jar inside. The reason for this is because our own added jar pack inside the class and javaee5 inside the conflict, I recommend the solution is to javaee5 inside the activation package and mail package deleted.   practices are as follows:   Find Eclipse Reference Javaee5 package, open with RAR software, find activation and mail package, delete save on it. (Remember to refresh the reference package in the IDE)   2.2 javax.mail.messagingexception:501 syntax:helo hostname   After the local test passed, I deployed to the Linux server, But to meet the javax.mail.messagingexception:501 syntax:helo hostname anomaly, Google found the following reasons:   Javamail in the extraction of local hostname will dig Change the hostname, and then send the message by IP.   Due to hostname IP address, Linux can not be resolved (if Windows does not have this problem, Windows uses the NetBIOS protocol to obtain the host's IP address) to the native hostname IP, resulting in Java Mail cannot invoke send IP. Postfix receive this type of mail will reject the delivery, resulting in a 501 error.   said that can be modified by the server's hosts file resolution, but I found that can also be directly in the code to resolve (only need to add a line of code, which is greatly convenient AH), that is, in the Setsmtphost () method, add the following line:   code as follows: Props.put ("Mail.smtp.localhost", "localhostadress");     2.3 Annex Chinese name garbled if the attachment has Chinese name, Direct SetName () will be garbled, through the following methods can be resolved:     code is as follows: Mbp.setfilename (mimeutility. Encodetext (Name, "Utf-8", "B"));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.