First, Code preview
These two days are sent on the struts2 to do the mail. 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 add your own downloaded Mail.jar, and Activation.jar to Classpath
Copy Code 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 {
/**
* Send mail to users
*/
Private static final long serialversionuid = 1L;
Private MimeMessage mimemsg; MIME Mail Object
Private session session; Mail Session Object
Private Properties props; System Properties
Private Boolean Needauth = false; Does SMTP require authentication
Private String username = ""; SMTP authenticated user name and password
Private String Password = "";
Private Multipart MP; Multipart object, message content, title, attachment, etc. 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 properties: Mail.smtp.host =" + HostName);
if (props = null)
Props = System.getproperties (); Get System Properties Object
Props.put ("Mail.smtp.host", hostName); Setting up an SMTP host
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 = "An error occurred while getting the mail session Object!" "+ e.tostring ();
SYSTEM.ERR.PRINTLN (log);
return false;
}
try {
mimemsg = new MimeMessage (session); To create a MIME mail object
MP = new Mimemultipart (); MP a multipart object
Multipart is a container which 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) {
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 ("program gets username and password");
Username = name;
Password = pass;
}
public boolean setsubject (String mailsubject) {
SYSTEM.OUT.PRINTLN ("Set message subject!") ");
try {
Mimemsg.setsubject (Mimeutility.encodetext (Mailsubject, "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 message 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 message 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); Get the data source
Mbp.setdatahandler (New DataHandler (FDS)); Get the attachment itself and into the bodypart
Mbp.setfilename (Fds.getname ()); Get file name same to enter BodyPart
Mp.addbodypart (MBP);
}
return true;
}catch (Exception e) {
Log = "Error adding attachment:" +E;
E.printstacktrace ();
return false;
}
}
public boolean AddFile (string path, string name) {
try{
MimeBodyPart mbp=new MimeBodyPart ();
Filedatasource fds=new Filedatasource (path); Get the 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;
E.printstacktrace ();
return false;
}
}
public boolean Setfrom (String from) {
System.out.println ("Set 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 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)
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 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 successful!") ");
Transport.close ();
return true;
catch (Exception e) {
Log = "message sent failed!" "+ E;
SYSTEM.ERR.PRINTLN (log);
return false;
}
}
Public String GetLog () {
return log;
}
}
Ii. Summary of issues
2.1 Local execution times wrong
I am using Java EE 5,jdk1.6, when running locally, there will be ClassNotFound exception, but these classes are in Mail.jar. 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.
The procedure is 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 ran into the javax.mail.messagingexception:501 syntax:helo hostname exception, Google found the following reasons:
Javamail in the local hostname will dig change hostname, and then to change the IP to send mail.
Because the hostname corresponding IP address, Linux can not resolve (if it is 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 javamail can not Call send IP. Postfix receive this type of mail will reject the delivery, resulting in a 501 error.
Online said can be modified by the server's Hosts file solution, 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:
Copy Code code as follows:
Props.put ("Mail.smtp.localhost", "localhostadress");
2.3 The annex Chinese name is garbled
If the attachment has Chinese name, Direct SetName () will garbled, through the following methods can be resolved:
Copy Code code as follows:
Mbp.setfilename (Mimeutility.encodetext (name, "Utf-8", "B"));