Struts2 integrates javamail mail (with attachment) practice records

Source: Internet
Author: User

I. Code Preview

In the past two days, emails are sent to struts2. The previous project was useful to spring. It was very convenient to use the mail support class provided by spring to complete this function. However, if we only use struts2, we encountered a series of problems.

The code is copied from the Internet, and then I improved some of the code, and added the attachment sending function. Let's take a look at the main code (Please download your own mail first. jar, and activation. add jar to classpath)

 

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. mim EBodyPart; import javax. mail. internet. mimeMessage; import javax. mail. internet. mimeMultipart; import javax. mail. internet. mimeUtility; public class EMailSender {/*** send an email to the user */private static final long serialVersionUID = 1L; private MimeMessage mimeMsg; // MIME mail object private Session session; // mail session object private Properties props; // system attribute private boolean needAuth = false; // whether smtp needs to authenticate private String usern Ame = ""; // smtp authentication username and password private String password = ""; private Multipart mp; // Multipart object, mail content, title, add the attachment and other content to it, and then generate the private String log; public EMailSender () {} public EMailSender (String smtp) {setSmtpHost (smtp); createMimeMessage ();} public void setSmtpHost (String hostName) {System. out. println ("set system properties: mail. smtp. host = "+ hostName); if (props = null) props = System. getProperties (); // obtain system attributes Object props. put ("mail. smtp. host ", hostName); // set SMTP host props. put ("mail. smtp. localhost "," localHostAdress ");} public boolean createMimeMessage () {try {System. out. println ("prepare to get the mail session object! "); Session = Session. getDefaultInstance (props, null); // get the mail session object} catch (Exception e) {log =" An error occurred while obtaining the mail Session object! "+ E. toString (); System. err. println (log); return false;} try {mimeMsg = new MimeMessage (session); // create a MIME mail object mp = new MimeMultipart (); // mp a multipart object // Multipart is a container that holds multiple body parts. return true;} catch (Exception e) {log = "An error occurred while creating the MIME mail object! "+ E; System. err. println (log); return false ;}} public void setNeedAuth (boolean need) {System. out. println ("set smtp authentication: mail. smtp. auth = "+ need); if (props = null) props = System. getProperties (); if (need) {props. put ("mail. smtp. auth "," true ");} else {props. put ("mail. smtp. auth "," false ") ;}} public void setNamePass (String name, String pass) {System. out. println ("the program obtains the user name and password"); username = name; Password = pass;} public boolean setSubject (String mailSubject) {System. out. println ("set email subject! "); Try {mimeMsg. setSubject (MimeUtility. encodeText (mailSubject, "UTF-8", "B"); return true;} catch (Exception e) {log = "An error occurred when setting the email subject! "+ E; System. err. println (log); return false ;}} public boolean setBody (String mailBody) {try {System. out. println ("set the mail body format"); BodyPart bp = new MimeBodyPart (); // convert it to the Chinese format bp. setContent ("<meta http-equiv = Content-Type content = text/html; charset = UTF-8>" + mailBody, "text/html; charset = UTF-8"); mp. addBodyPart (bp); return true;} catch (Exception e) {log = "An error occurred when setting the mail body! "+ E; System. err. println (log); return false ;}} public boolean setFiles (List <String> files) {try {for (String s: files) {MimeBodyPart mbp = new MimeBodyPart (); fileDataSource fds = new FileDataSource (s); // obtain the data source mbp. setDataHandler (new DataHandler (fds); // obtain the attachment and input the BodyPart mbp. setFileName (fds. getName (); // get the same name to the BodyPart mp file. addBodyPart (mbp);} return true;} catch (Exception e) {log = "An error occurred when adding an attachment:" + e; e. PrintStackTrace (); return false ;}} public boolean addFile (String path, String name) {try {MimeBodyPart mbp = new MimeBodyPart (); FileDataSource fds = new FileDataSource (path ); // obtain the data source mbp. setDataHandler (new DataHandler (fds); // obtain the attachment and input the BodyPart mbp. setFileName (MimeUtility. encodeText (name, "UTF-8", "B"); mp. addBodyPart (mbp); return true;} catch (Exception e) {log = "An error occurred while adding the attachment:" + e; e. printStackTrace (); r Eturn false ;}} public boolean setFrom (String from) {System. out. println ("set the sender! "); Try {mimeMsg. setFrom (new InternetAddress (from); // set sender return true;} catch (Exception e) {log = "set sender error:" + e; return false ;}} public boolean setTo (String to) {System. out. println ("set recipient"); 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) return false; try {mimeMsg. setRecipients (Message. recipientType. CC, (Address []) InternetAddress. parse (copyto); return true;} catch (Exception e) {return false ;}} public boolean sendout () {try {mimeMsg. setContent (mp); mimeMsg. saveChanges (); System. out. println ("sending email .... "); 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 ("email sent successfully! "); Transport. close (); return true;} catch (Exception e) {log =" failed to send the email! "+ E; System. err. println (log); return false ;}} public String getLog () {return log ;}}

  

 

Ii. Problem Summary

 

2.1 error reported during local execution

Java ee 5 and jdk1.6 are used. Exceptions of ClassNotFound may occur during local running, but these classes are available in mail. jar. This is because the classes in the jar package we added conflict with those in javaee5. The solution I recommend is to delete the activation package and mail package in javaee5.

The procedure is as follows:

Find the javaee5 package referenced by eclipse, open it with rar software, find the activation and mail packages, and delete and save the packages. (Remember to refresh the reference package in ide)


2.2 javax. mail. MessagingException: 501 Syntax: HELO hostname

After passing the local test, I deployed it to the linux server, but encountered a javax. mail. MessagingException: 501 Syntax: HELO hostname exception. google found that the cause is:

 

When Javamail extracts the local hostname, it changes the dig to the hostname, and then sends an email by changing the ip address.

Because of the ip address corresponding to the hostname, linux cannot resolve the ip address (if it is windows, windows uses the netbios protocol to obtain the ip address of the host) to the ip address of the local hostname, as a result, javamail cannot call the sending ip address. Postfix will reject delivery when receiving such emails, resulting in a 501 error.

It can be solved through modifying the hosts file of the server on the Internet, but I found that it can also be solved directly in the Code (just add a line of code, which is very convenient), that is, in setSmtpHost () method, add the following line:

 

props.put("mail.smtp.localhost", "localHostAdress");

 

2.3 garbled Chinese name of the Attachment

If the attachment has a Chinese name, the direct setName () will be garbled. The following method can be used to solve the problem:

 

mbp.setFileName(MimeUtility.encodeText(name,"utf-8","B"));

 


This is basically the case. I will share it later when there are new discoveries.

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.