Send mail via javamail. I will understand it after reading it.

Source: Internet
Author: User
Tags smtp auth
/** RecieveMail. java ** Created on 2008.7.9, pm2: 40 ** To change this template, choose Tools | Template Manager * and open the template in the editor. */package mail; import javax. mail. *; import javax. mail. internet. *; import java. util. *; import java. io. *; /***** @ author user ** generate zookeeper token when generating zookeeper, Zookeeper, and zookeeper. extends extends */public class RecieveMail {private String _ popServer = ""; Private String _ popUser = ""; private String _ popPassword = ""; public void getMails () {try {// recieve mail receive ();} catch (Exception ex) {Logger. println ("Usage: java com. lotontech. mail. POPMail "+" popServer popUser popPassword ") ;}} private void receive () {Store store = null; Folder folder = null; try {// prepare to open mails pool Properties props = System. getProperties (); Session session = Session. getDefaultInstance (props, null); store = session. getStore ("pop3"); store. connect (_ popServer, _ popUser, _ popPassword); folder = store. getDefaultFolder (); if (folder = null) throw new Exception ("No default folder"); folder = folder. getFolder ("INBOX"); if (folder = null) throw new Exception ("No POP3 INBOX"); // inbox folder // make it writeable folder. open (Folder. READ_WRITE); // array mails I N msgs Message [] msgs = folder. getMessages (); for (int msgNum = 0; msgNum <msgs. length; msgNum ++) {// read mail Logger. println ("this the" + (msgNum + 1) + "mail in the server INBOX"); printMessage (msgs [msgNum]); checkMessage (msgs [msgNum]); // delete readen mail msgs [msgNum]. setFlag (Flags. flag. DELETED, true) ;}} catch (Exception ex) {Logger. println (ex. getMessage ();} finally {try {// set true to af Firm the operation if (folder! = Null) folder. close (true); if (store! = Null) store. close ();} catch (Exception ex2) {Logger. println (ex2.getMessage () ;}} private void printMessage (Message message) {try {Logger. println ("mail info ------ start ------"); // from address String from = (InternetAddress) message. getFrom () [0]). getPersonal (); if (from = null) from = (InternetAddress) message. getFrom () [0]). getAddress (); Logger. println ("FROM:" + from); // subject String subject = messa Ge. getSubject (); Logger. println ("SUBJECT:" + subject); // headers String [] header = message. getHeader ("X-IFArea"); if (header. length> 0) Logger. println ("X-IFArea:" + header [0]); // content Part messagePart = message; Object content = messagePart. getContent (); if (content instanceof Multipart) {for (int m = 0; m <(Multipart) content ). getCount (); m ++) {if (Multipart) content ). getBodyPart (m ). getFileName ()! = Null) {Logger. println ("affix:" + (Multipart) content ). getBodyPart (m ). getFileName () ;}} Logger. println ("mail info ------ end ------");} catch (Exception ex) {Logger. println (ex. getMessage () ;}} private void checkMessage (Message message) {try {// subject String subject = message. getSubject (); // headers String [] header = message. getHeader ("X-IFArea"); if (header. length <1) throw new Exception ("mail ch Eck error, there is no X-IFArea "); String x_IFArea = header [0]; // error reports List x_err_IFAreas = new ArrayList (); for (int I = 1; I <= 3; I ++) {String [] error = message. getHeader ("X-Ex" + I + "-IFArea"); if (error! = Null & error. length> 0) x_err_IFAreas.add ("X-Ex" + I + "-IFArea" + error [0]);} // content Part messagePart = message; Object content = messagePart. getContent (); List files = new ArrayList (); if (content instanceof Multipart) {for (int fileNumber = 0; fileNumber <(Multipart) content ). getCount (); fileNumber ++) {messagePart = (Multipart) content ). getBodyPart (fileNumber); if (messagePart. getFileName () = null) continue; BlobData data = new BlobData (); data. setBlobName (messagePart. getFileName (); data. setStream (messagePart. getInputStream (); files. add (data) ;}// create TransmitIncepters to deal the message String className = ""; Property property Property = Property. getInstance (); // if (subject. equalsIgnoreCase (property. getProperty ("titleRegist "). trim () {className = CONSTANT. mail_class_Regist;} else if (subject. equalsIgnoreCase (property. getProperty ("titleDeleteRegist "). trim () {className = CONSTANT. mail_class_DeleteRegist;} else if (subject. equalsIgnoreCase (property. getProperty ("titleAccept "). trim () {className = CONSTANT. mail_class_Accept;} else {throw new Exception ("wrong title, can not incept the mail to db");} // desine for only get the name from subject string TransmitIncepter incepter = TransmitIncepter. getInstance (className); incepter. setSubject (subject); incepter. setX_IFArea (x_IFArea); incepter. setX_err_IFAreaList (x_err_IFAreas); incepter. setFileList (files); incepter. setSentDate (message. getSentDate (); incepter. run ();} catch (Exception ex) {Logger. println (ex. getMessage () ;}} public void setPopServer (String popServer) {_ popServer = popServer;} public void setPopUser (String popUser) {_ popUser = popUser ;} public void setPopPassword (String popPassword) {_ popPassword = popPassword ;}}
/** SendMail. java ** Created on 2008.7.9, am11: 47 ** To change this template, choose Tools | Template Manager * and open the template in the editor. */package mail; import java. util. *; import javax. mail. *; import javax. mail. internet. *; import java. util. date; import javax. activation. *; import oracle. SQL. BLOB; import java. io. *; public class SendMail {private MimeMessage mimeMsg; private Session session; Private Properties props; // your desired region has been private boolean needAuth = false; // smtp token has been used when your desired region has been encrypted using private String username = ""; // smtp authentication name private String password = ""; // smtp authentication using encrypted private Multipart mp; // The Multipart authentication image contains the following content, table topic: Add a parameter containing the parameter MimeMessage photo image/******/public SendMail () {setSmtpHost (""); // Please specify whether or not the specified parameter has been specified, and whether or not the specified parameter has been specified before using createmememessage ();} public SendMail (String smtp) {setSmtpHost (smtp); createMim EMessage ();}/***** @ param hostName String **/public void setSmtpHost (String hostName) {Logger. println ("system property: mail. smtp. host = "+ hostName); if (props = null) props = System. getProperties. put ("mail. smtp. host ", hostName); // SMTP reschedule register name}/***** @ return boolean **/public boolean createMimeMessage () {try {Logger. println ("prepare to read mail body object"); se Ssion = Session. getDefaultInstance (props, null); // catch (Exception e) {System. err. println ("error ecured in getting mail body" + e); return false;} Logger. println ("create mime mail body! "); Try {mimeMsg = new MimeMessage (session); // create an mp = new MimeMultipart (); return true;} catch (Exception e) {System. err. println ("fail to create mime body" + e); return false ;}/ ***** @ param need boolean ***/public void setNeedAuth (boolean need) {Logger. println ("config smtp auth: mail. smtp. auth = "+ need); if (props = null) props = System. getProperties (); if (need) {props. put ("mai L. smtp. auth "," true ");} else {props. put ("mail. smtp. auth "," false ") ;}}/***** @ param name String ** @ param pass String ***/public void setNamePass (String name, String pass) {username = name; password = pass;}/***** @ param mailSubject String ** @ return boolean **/public boolean setSubject (String mailSubject) {Logger. println ("config mail subject"); try {mimeMsg. setSubject (mailSubject); Return true;} catch (Exception e) {System. err. println ("fail to config mail subject"); return false ;}/ ***** @ param mailSubject String *** @ return boolean ***/public boolean setHeader (String name, string context) {Logger. println ("config mail header:" + name); try {mimeMsg. setHeader (name, context); return true;} catch (Exception e) {System. err. println ("fail to config mail header"); retu Rn false;}/***** @ param mailBody String **/public boolean setBody (String mailBody) {try {BodyPart bp = new MimeBodyPart (); bp. setContent ("<meta http-equiv = Content-Type content = text/html; charset = iso-2022-jp>" + mailBody, "text/html; charset = iso-2022-jp"); mp. addBodyPart (bp); return true;} catch (Exception e) {System. err. println ("config mail main body" + e); return false ;}} public bool Ean addFileAffix (String filename, BLOB blob) {Logger. println ("add file affix:" + filename); try {BodyPart bp = new MimeBodyPart (); BlobDataSource streamds = new BlobDataSource (filename, blob); bp. setDataHandler (new DataHandler (streamds); bp. setFileName (streamds. getName (); bp. setHeader ("Content-Transfer-Encoding", "base64"); mp. addBodyPart (bp); return true;} catch (Exception e) {System. err. print Ln ("add file affix:" + filename + "error ecured" + e); return false ;}} public boolean addFileAffix (String filename) {Logger. println ("add file affix:" + filename); try {BodyPart bp = new MimeBodyPart (); FileDataSource fileds = new FileDataSource (filename); bp. setDataHandler (new DataHandler (fileds); bp. setFileName (fileds. getName (); mp. addBodyPart (bp); return true;} catch (Exception e) {Syst Em. err. println ("add file affix:" + filename + "error ecured" + e); return false ;}} public boolean addFileAffix (BlobData [] blobs) {try {for (int I = 0; I <blobs. length; I ++) {Logger. println ("add file affix:" + blobs [I]. getBlobName (); BodyPart bp = new MimeBodyPart (); BlobDataSource streamds = new BlobDataSource (blobs [I]. getBlobName (), blobs [I]. getBlob (); bp. setDataHandler (new DataHandler (stre Amds); bp. setFileName (streamds. getName (); mp. addBodyPart (bp);} return true;} catch (Exception e) {System. err. println ("add file affix, error ecured" + e); return false ;}} /***** @ param name String ** @ param pass String **/public boolean setFrom (String from) {Logger. println ("set fromer! "); Try {mimeMsg. setFrom (new InternetAddress (from); // the sender of the message must have been successfully set to return true;} catch (Exception e) {return false ;}} /***** @ param name String ** @ param pass String **/public boolean setTo (String to) {if (to = null) return false; try {mimeMsg. setRecipients (Message. recipientType. TO, InternetAddress. parse (to); return true;} catch (Exception e) {return false;}/*** @ param name S Tring ** @ param pass String **/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 ;}} /***** @ param name String ** @ param pass String **/public boolean sendout () {try {mimeMsg. setContent (mp); mimeMsg. saveChanges (); L Ogger. 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); Logger. println ("sending mail succeed! "); Transport. close (); return true;} catch (Exception e) {System. err. println (" Fail to send mail! "+ E); return false ;}}}
 
 
When receiving mail attachments, it applies to the input stream. Here, it is easy to generate unnecessary things. When reading the input stream, it is best to use while (int = in. read ())! =-1) to receive the actual length, otherwise the file will be added with some inexplicable spaces.

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.