In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about how to develop JavaMail. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
Introduction: the recent project to do a simple mail function, that is, to enter the contents of the mail from the foreground, to the configuration file to read the sender, the recipient and other information, and then send the email to the designated mailbox, in which the recipient and CC can have multiple, based on this requirement, queried the relevant information, decided to use JavaMail this plug-in to achieve.
Preparation:
Introduction of 1.JavaMail
JavaMail, as its name implies, provides developers with a programming interface for dealing with email. It is an API released by Sun to deal with email. It can easily perform some commonly used mail transfers.
Although JavaMail is one of Sun's API, it has not yet been added to the standard java development kit (JavaDevelopmentKit), which means you have to download additional JavaMail files before using it. In addition, you need to have Sun's JavaBeans Activation Framework (JAF). The operation of JavaBeans Activation Framework is very complex, and to put it simply here, the operation of JavaMail must rely on its support. Using these files under Windows 2000 requires you to specify the path to these files, which is similar on other operating systems.
JavaMail is an optional package, so you need to download it from java.sun.com first if you need to use it. The latest version is JavaMail1.4, and you need Javabean Activation Framework support when using JavaMail, so you also need to download JAF. To install JavaMail, you just need to add them to CLASSPATH. If you don't want to modify CLASSPATH, you can directly copy their jar package to JAVA_HOME/lib/ext. So the JavaMail is installed.
The core classes used to handle e-mail in the JavaMail package are: Session,Message,Address,Authenticator,Transport,Store,Folder and so on. Session defines a basic mail session that needs to read information such as mail server, user name and password from Properties.
two。 Download the jar package
There is a download link on the Internet, but here I still upload the jar package.
Javamail-1 [1] .4.2.zip
Jaf-1_1_1.zip
The jar of dom4j.jar does not provide download resources.
3. Project environment
System:win7 myeclipse:6.5 tomcat:5.0 JDK: both compile and run are 1.4
For convenience, it is still running under the previous UpDown project, and the files used this time are only those under the sendmail package.
4.class&method
Please refer to: http://www.jspcn.net/htmlnews/1150019680500144.html
Start
Import the jar package of javamail, JAF and dom4j, and then create the corresponding file as follows:
Encrypt.jar is mainly used to encrypt and decrypt passwords.
Package sendmail; / * * Module: Encrypt.java * Description: encrypt and decrypt passwords * Company: * Author: ptp * Date: Mar 6, 2012 * / public class Encrypt {public static final int pass1 = 10; public static final int pass2 = 1 Public Encrypt () {} / * * @ Title: DoEncrypt * @ Description: method for encrypting passwords * @ param @ param str * @ param @ return configuration file * @ return String return type * @ throws * / public static String DoEncrypt ( String str) {StringBuffer enStrBuff = new StringBuffer () For (int I = 0; I < str.length (); iTunes +) {int tmpch = str.charAt (I); tmpch ^ = 1; tmpch ^ = 0xa; enStrBuff.append (Integer.toHexString (tmpch));} return enStrBuff.toString () .toUpperCase () } / * * @ Title: DoDecrypt * @ Description: method for decrypting passwords * @ param @ param str * @ param @ return configuration file * @ return String return type * @ throws * / public static String DoDecrypt (String str) {String deStr = str.toLowerCase () StringBuffer deStrBuff = new StringBuffer (); for (int I = 0; I < deStr.length (); I + = 2) {String subStr = deStr.substring (I, I + 2); int tmpch = Integer.parseInt (subStr, 16); tmpch ^ = 1; tmpch ^ = 0xa; deStrBuff.append ((char) tmpch) } return deStrBuff.toString ();} public static void main (String args []) {String source = "123456"; String s = DoEncrypt (source); System.out.println ("de=" + s); source = DoDecrypt (s); System.out.println ("en=" + source) }}
MailInfo.java javabean defines the fields required by the message and the corresponding get and set methods
Package sendmail; / * * Module: MailInfo.java * Description: javabean * Company: * Author: ptp * Date: Mar 1, 2012 * / public class MailInfo {private String host;// mail server domain name or IP private String from;// sender private String to;// recipient private String cc / / copy person private String username;// Sender user name private String password;// Sender password private String title;// message subject private String content;// message content public String getHost () {return host;} public void setHost (String host) {this.host = host } public String getFrom () {return from;} public void setFrom (String from) {this.from = from;} public String getTo () {return to;} public void setTo (String to) {this.to = to;} public String getCc () {return cc } public void setCc (String cc) {this.cc = cc;} public String getUsername () {return username;} public void setUsername (String username) {this.username = username;} public String getPassword () {return password;} public void setPassword (String password) {this.password = password } public String getTitle () {return title;} public void setTitle (String title) {this.title = title;} public String getContent () {return content;} public void setContent (String content) {this.content = content;}}
MyAuthenticator.java is used to authorize mail
Package sendmail; / * * Module: MailInfo.java * Description: email authorization class * Company: * Author: ptp * Date: Mar 6, 2012 * / import javax.mail.PasswordAuthentication; public class MyAuthenticator extends javax.mail.Authenticator {private String strUser; private String strPwd; public MyAuthenticator (String user, String password) {this.strUser = user This.strPwd = password;} protected PasswordAuthentication getPasswordAuthentication () {return new PasswordAuthentication (strUser, strPwd);}}
Wrapper class for SendMail.java to send mail
First read the xml configuration file, then parse the xml file, and finally get the value of the configuration file and send an email after the encapsulation is completed.
Package sendmail; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage Import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element / * Module: SendMail.java * Description: send email * Company: * Author: ptp * Date: Mar 1, 2012 * / public class SendMail {private static final Log log = LogFactory.getLog (SendMail.class) / / the path to the configuration file xml private final static String XML_PATH = "src" + File.separator + "sendmail" + File.separator + "SendMail.xml"; / / the javabean object private static MailInfo mailInfo = new MailInfo () corresponding to the field in the xml file; / *
Title: readXML
*
Description: read the xml file and output the file contents as a string
* @ param xmlPath configuration file path * @ return * @ throws Exception * / private String readXML (String xmlPath) throws Exception {log.debug ("xmlPath=" + xmlPath); String fileContent = ""; File file = new File (xmlPath) If (file.isFile () & & file.exists ()) {try {InputStreamReader read = new InputStreamReader (new FileInputStream (file), "UTF-8"); BufferedReader reader = new BufferedReader (read); String line Try {while ((line = reader.readLine ())! = null) {fileContent + = line;} reader.close (); read.close () } catch (IOException e) {e.printStackTrace ();}} catch (UnsupportedEncodingException e) {e.printStackTrace ();} catch (FileNotFoundException e) {e.printStackTrace () }} else {throw new Exception ("the configuration file SendMail.xml in the config directory does not exist, please check");} log.debug ("xml=" + fileContent); return fileContent;} / *
Title: parseXML
*
Description: send an email to the specified recipient and CC, and make some simple verification, such as the required fields and the value of type
* @ param xml configuration file content * @ param type message type * / private void parseXML (String xml, String type) {type=type.toLowerCase (); / / ignore the case of the type field try {/ / parse XML, and get the doc object Document doc = DocumentHelper.parseText (xml) / / determine whether the value of type is correct, and the value of type should be a String flag = doc.getRootElement () .element (type) + "" in the secondary node of the message. If (null = = flag | | flag.equals ("null")) throw new DocumentException ("the type value passed in is incorrect, the value of type should be one of the secondary nodes in the SendMail.xml message, please check the file and re-pass the value of type") / / set host name Element hostEle = (Element) doc.selectSingleNode ("/ mail/" + type + "/ host"); if (null = = hostEle | | ".equals (hostEle.getTextTrim () {throw new DocumentException (" Mail server domain name or IP cannot be empty, please check the configuration file SendMail.xml ") } mailInfo.setHost (hostEle = = null? "": hostEle.getTextTrim ()); / / set sender Element fromEle = (Element) doc.selectSingleNode ("/ mail/" + type + "/ from") If (null = = fromEle | | ".equals (fromEle.getTextTrim () {throw new DocumentException (" Sender address cannot be empty, please check the configuration file SendMail.xml ");} mailInfo.setFrom (fromEle = = null?": fromEle.getTextTrim ()) / / set email subject Element titleEle = (Element) doc.selectSingleNode ("/ mail/" + type + "/ title"); mailInfo.setTitle (titleEle = = null? ": titleEle.getTextTrim ()) / / set recipients. The processing of multiple recipients is followed by Element toEle = (Element) doc.selectSingleNode ("/ mail/" + type + "/ to"). If (null = = toEle | | ".equals (toEle.getTextTrim () {throw new DocumentException (" recipient address cannot be empty, please check the configuration file SendMail.xml ");} mailInfo.setTo (toEle = = null?": toEle.getTextTrim ()) / / set Element ccEle, and put the processing of multiple CC users after Element ccEle = (Element) doc.selectSingleNode ("/ mail/" + type + "/ cc"); mailInfo.setCc (ccEle = = null? ": ccEle.getTextTrim ()) / / set sender user name Element nameEle = (Element) doc.selectSingleNode ("/ mail/" + type + "/ username"); if (null==nameEle | | ".equals (nameEle.getTextTrim () {throw new DocumentException (" Sender user name cannot be empty, please check the configuration file SendMail.xml ") } mailInfo.setUsername (nameEle = = null? "": nameEle.getTextTrim ()); / / set the sender password Element passEle = (Element) doc.selectSingleNode ("/ mail/" + type + "/ password") If (null==passEle | | ".equals (passEle.getTextTrim () {throw new DocumentException (" Sender password cannot be empty, please check the configuration file SendMail.xml ");} mailInfo.setPassword (passEle = = null?": passEle.getTextTrim ());} catch (DocumentException e) {e.printStackTrace () }} / *
Title: sendMailOfValidate
*
Description: method of sending mail, Authenticator class verification
* / private void sendMailOfValidate () {Properties props = System.getProperties (); props.put ("mail.smtp.host", mailInfo.getHost ()); / / set the domain name or IP props.put of the mail server ("mail.smtp.auth", "true"); / / for authorized mail, mail.smtp.auth must be set to true String password=mailInfo.getPassword () / / password try {password=Encrypt.DoDecrypt (password) / / if the password is encrypted, use this method to decrypt the password} catch (NumberFormatException E1) {/ / if the password is not encrypted, no processing is done to the password} / / pass in the sender's user name and password, and construct the MyAuthenticator object MyAuthenticator myauth = new MyAuthenticator (mailInfo.getUsername (), password) / pass in props and myauth objects to construct the mail authorized session object Session session = Session.getDefaultInstance (props, myauth); / / pass the Session object as a parameter of the MimeMessage constructor to the construction message object MimeMessage message = new MimeMessage (session); try {message.setFrom (new InternetAddress (mailInfo.getFrom () / / Sender / / handle the case of multiple recipients. In the configuration file SendMail.xml, if (mailInfo.getTo ()! = null & &! ".equals (mailInfo.getTo () {String to [] = mailInfo.getTo () .split (", "); for (int I = 0) must be separated by commas. I < to.length; iTunes +) {message.addRecipient (Message.RecipientType.TO, new InternetAddress (to [I])) / / recipient}} / / A pair of if (mailInfo.getCc ()! = null & &! ".equals (mailInfo.getCc () {String cc [] = mailInfo.getCc (). Split (", ") For (int j = 0; j < cc.length; jacks +) {message.addRecipient (Message.RecipientType.CC, new InternetAddress (cc [j])); / / CC}} message.setSubject (mailInfo.getTitle ()) / / subject message.setText (mailInfo.getContent ()); / / content Transport.send (message); / / call the mail sending method log.debug ("message sent successfully");} catch (AddressException e) {e.printStackTrace () } catch (MessagingException e) {e.printStackTrace ();}} / * *
Title: sendMail
*
Description: entry for external program calls
* at present, there are three types of param type messages, that is, logmessage, checkmessage and ordermessage,type can only pass one of these three values, but no other values can be passed * @ param content email content * @ throws Exception * / public void sendMail (String type,String content) throws Exception {log.debug ("input parameter type=" + type); log.debug ("input parameter content=" + content) If (null = = type | | ".equals (type) | | null = = content | |" .equals (content)) {throw new Exception ("the values of the input parameters type and content fields of the method cannot be empty or null");} String xml=readXML (XML_PATH); / / get the xml string parseXML (xml,type) / / parse the xml string, put the value of the corresponding field into the mailInfo object mailInfo.setContent (content); / / set the content sent sendMailOfValidate () / / send email} / * to facilitate direct testing with the main method * @ param args * @ throws Exception * / public static void main (String args []) throws Exception {SendMail mail = new SendMail () / / type type, according to this field to configure a match in the file SendMail.xml, and then send it to the corresponding mailbox String type = "logmessage"; / / the content of the email is actually passed from the foreground to the background String content = "Hello, enjoy using JavaMail package to develop email function" / / you can only see the sendMail method when called in other classes. To protect the internal details, other methods are declared as private mail.sendMail (type, content); / / there is no log file in this project, so I print a sentence to tell myself that the program has successfully run System.out.println ("* success****"). }}
Note: the verification in the code may not be rigorous and comprehensive, because the configuration file is configured by the developer, and the configuration file is described in detail, so a lot of validation is omitted from the code.
SendMail.xml Mail Profil
Smtp.qq.com 838045782@qq.com 838045782 838045782@qq.com test JavaMail 838045782@qq.com qq.comlegum taipeng0820cm 163.com 123456
Note: the password is required. Because of the introduction, I deleted my password and changed it to 123456. In practice, I need to configure the domain name, sender, recipient, CC person, username and password of the mail server as needed.
Result
Operation mode: execute and run the main mode in the SendMail.java class and you can test it. Please follow the instructions to configure the xml file before testing.
You may encounter the following errors the first time you run, so the note.txt file is used to provide the errors encountered and the corresponding solutions
Note.txt
Java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream at javax.mail.Session.loadProvidersFromStream (Session.java:928) at javax.mail.Session.access$000 (Session.java:174) at javax.mail.Session$1.load (Session.java:870) at javax.mail.Session.loadResource (Session.java:1084) at javax.mail.Session.loadProviders (Session.java:889) at javax.mail.Session. (Session.java:210) at javax.mail.Session.getDefaultInstance (Session .java: 299) at mail.SendMail.sendMail (SendMail.java:31) at mail.SendMail.main (SendMail.java:50) Exception in thread "main"
Solution: search for javaee.jar under the installation directory of myeclipse, then open it with compressed software and delete the mail folder under javax
Java.lang.NoClassDefFoundError: com/sun/activation/registries/LogSupport at javax.activation.MailcapCommandMap. (MailcapCommandMap.java:140) at javax.activation.CommandMap.getDefaultCommandMap (CommandMap.java:61) at javax.activation.DataHandler.getCommandMap (DataHandler.java:153) at javax.activation.DataHandler.getDataContentHandler (DataHandler.java:611) at javax.activation.DataHandler.writeTo (DataHandler.java:315) at javax.mail.internet.MimeUtility.getEncoding (MimeUtility.java:264) at javax.mail.internet.MimeBodyPart .updateHeaders (MimeBodyPart.java:1299) at javax.mail.internet.MimeMessage.updateHeaders (MimeMessage.java:2071) at javax.mail.internet.MimeMessage.saveChanges (MimeMessage.java:2039) at javax.mail.Transport.send (Transport.java:119) at mail.SendMail.sendMailNoValidate (SendMail.java:48) at mail.SendMail.main (SendMail.java:96) Exception in thread "main"
Solution: search for javaee.jar under the installation directory of myeclipse, then open it with compressed software and delete the activation folder under the javax folder.
Javax.mail.SendFailedException: Sending failed; nested exception is: javax.mail.MessagingException: 503 Error: need EHLO and AUTH first! At javax.mail.Transport.send0 (Transport.java:219) at javax.mail.Transport.send (Transport.java:81) at com.asiainfo.bboss.sendmail.SendMailServiceImpl.sendMailNoValidate (SendMailServiceImpl.java:210) at com.asiainfo.bboss.sendmail.SendMailServiceImpl.sendMail (SendMailServiceImpl.java:243) at com.asiainfo.bboss.sendmail.SendMailServiceImpl.main (SendMailServiceImpl.java:261)
Solution: props.put ("mail.smtp.auth", "true")
Javax.mail.SendFailedException: Sending failed; nested exception is: javax.mail.AuthenticationFailedException at javax.mail.Transport.send0 (Transport.java:219) at javax.mail.Transport.send (Transport.java:81) at com.asiainfo.bboss.sendmail.SendMailServiceImpl.sendMailNoValidate (SendMailServiceImpl.java:211) at com.asiainfo.bboss.sendmail.SendMailServiceImpl.sendMail (SendMailServiceImpl.java:244) at com.asiainfo.bboss.sendmail.SendMailServiceImpl.main (SendMailServiceImpl.java:262)
Solution: MyAuthenticator myauth = new MyAuthenticator (mailInfo.getUsername (), password)
The screenshot of the operation is as follows:
Figure 1:myeclipse background print result there is no log4j.properties file under this project, so there will be a red message, and the log in the code has not been printed.
Photo 2: go to my QQ Mail to receive the mail-inbox list
Photo 3: go to my QQ Mail to receive the letter-the content of the email.
Figure 4: go to my 163 mailbox to receive mail-inbox list
Confirm that you have received the email, because the 163 email shows my real name, so there is no screenshot here.
Figure 5: go to my 163 mailbox to receive the mail-the content of the email
Confirm that you have received the email, because the 163 email shows my real name, so there is no screenshot here.
The above is just a small application for the javamail plug-in, which can also receive mail, forward, reply, upload attachments and other functions.
The above is the editor for you to share how to develop JavaMail, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.