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.
Add the downloaded mail. jar and activation. jar to classpath.
Copy codeThe Code is 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 {
/**
* Send emails to users
*/
Private static final long serialVersionUID = 1L;
Private MimeMessage mimeMsg; // MIME email object
Private Session session; // email Session Object
Private Properties props; // System Properties
Private boolean needAuth = false; // whether smtp authentication is required
Private String username = ""; // smtp authentication username and password
Private String password = "";
Private Multipart mp; // Multipart object, mail content, title, attachments, and other content are added to it and then generated
Private String log;
Public EMailSender (){
}
Public EMailSender (String smtp ){
SetSmtpHost (smtp );
CreateMimeMessage ();
}
Public void setSmtpHost (String hostName ){
System. out. println ("set System attributes: mail. smtp. host =" + hostName );
If (props = null)
Props = System. getProperties (); // obtain the System property object
Props. put ("mail. smtp. host", hostName); // set the SMTP host
Props. put ("mail. smtp. localhost", "localHostAdress ");
}
Public boolean createMimeMessage (){
Try {
System. out. println ("prepare to get the mail session object! ");
Session = Session. getdefainstance instance (props, null); // get the mail session Object
} Catch (Exception e ){
Log = "An error occurred while obtaining the email 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 Identity 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 while setting the email subject! "+ E;
System. err. println (log );
Return false;
}
}
Public boolean setBody (String mailBody ){
Try {
System. out. println ("set mail body format ");
BodyPart bp = new MimeBodyPart ();
// Convert to 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 while 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 add it to the BodyPart
Mbp. setFileName (fds. getName (); // get the same file name as BodyPart
Mp. addBodyPart (mbp );
}
Return true;
} Catch (Exception e ){
Log = "error 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 add it to the BodyPart
Mbp. setFileName (MimeUtility. encodeText (name, "UTF-8", "B "));
Mp. addBodyPart (mbp );
Return true;
} Catch (Exception e ){
Log = "error when adding an attachment:" + e;
E. printStackTrace ();
Return false;
}
}
Public boolean setFrom (String from ){
System. out. println ("set the sender! ");
Try {
MimeMsg. setFrom (new InternetAddress (from); // you can specify the sender.
Return true;
} Catch (Exception e ){
Log = "set sender error:" + e;
Return false;
}
}
Public boolean setTo (String ){
System. out. println ("set recipient ");
If (to = null)
Return false;
Try {
MimeMsg. setRecipients (Message. RecipientType. TO, InternetAddress
. Parse ());
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 an 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. ));
// Transport. send (mimeMsg );
System. out. println ("sent successfully! ");
Transport. close ();
Return true;
} Catch (Exception e ){
Log = "failed to send 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:
Copy codeThe Code is as follows:
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:
Copy codeThe Code is as follows:
Mbp. setFileName (MimeUtility. encodeText (name, "UTF-8", "B "));