Package com.mail;
Import java.io. *; import java.util. *; import javax.mail. *; import javax.mail.internet. *; import java.io.printwriter; import java.util.properties Import javax.naming.context; import javax.naming.initialcontext; import javax.activation. *; import java.io ioException;
// public class prasemimeMessage Implements Runnable {Public Class PRASEMEMESSAGE {Public Static Class SmtpauthenTICator Extends Authenticator {Private String UserName; Private String Password
Public SMTPAUTHENTICATOR (String Username, String Password) {super (); this.username = username; this.password = password;}
Protected passwordAuthentication () {return new passwordauthentication (this.username, this.password);}}
private MimeMessage mimeMessage = null; private String saveAttachPath = ""; // store directory after the attachment downloads private String picAddress = ""; // pictures stored URL address private StringBuffer bodytext = new StringBuffer (); // store the message content of StringBuffer Object private String dateformat = "yy-mM-dd HH: mm"; // default display format before / * * * * constructor initializes a MimeMessage Object * * / public PraseMimeMessage () {} public PraseMimeMessage (MimeMessage mimeMessage) {this.mimeMessage = mimeMessage; System.out.println ( "create a PraseMimeMessage object ........ / n");} public void setMimeMessage (MimeMessage mimeMessage) {this.mimeMessage = mimeMessage;} // set Picture URL address public void setPicaddress (String Picaddress) {this.picaddress = picaddress;} // Take a picture URL address PUBLIC STRING GETPICDRESS () {Return this.picaddress;} / * * * Get sender's address and name * * / Public string getFrom () throws exception {intern Etaddress address [] = (InternetDress []) mimeMessage.GetFrom (); string from = address [0] .Getaddress (); if (from == null) from = ""; string personal = address [0] .getPersonal ); If (personal == null) personal = ""; string fromaddr = personal "<" from ">"; return fromaddr;} / * * * * Get mail recipient, Cc, and dense delivery Address and name, depending on the parameters transmitted * * "to" ---- Recipient "CC" --- Ccc "BCC"
--- Bcc address * * / public String getMailAddress (String type) throws Exception {String mailaddr = ""; String addtype = type.toUpperCase (); InternetAddress [] address = null; if (addtype.equals ( "TO ") || addtype.equals (" cc ") || addtype.equals (" bcc ")) {if (addtype.equals (" to ")) {address = (InternetAddress []) MimeMessage.GetRecipients (Message.RecipientType .TO);} else if (addtype.equals ( "CC")) {address = (InternetAddress []) mimeMessage.getRecipients (Message.RecipientType.CC);} else {address = (InternetAddress []) mimeMessage.getRecipients ( Message.recipientType.bcc);} if (address! = Null) {for (int i = 0; i
} / * * Get mail transmission date * / public String getSentDate () throws Exception {Date sentdate = mimeMessage.getSentDate (); SimpleDateFormat format = new SimpleDateFormat (dateformat); return format.format (sentdate);} / * * * Get the textual content of the message * / public string getBodytext () {return bodytext.tostring ();} / * * * Resolution message, save the obtained mail content into a StringBuffer object, parsing the message * * mainly according to the mimeType type perform different operations, step by step analysis * / public void getMailContent (Part part) throws Exception {String contenttype = part.getContentType (); int nameindex = contenttype.indexOf ( "name"); boolean conname = false; if (nameindex ! = -1) Conname = true; //system.out.println ("in "ttype:" ContentType); if (Part.ismType ("text / place") {bodytext.Append (String) PART .getContent ());} else if (Part.ismenstype ("text/ html" &&! convename) {bodytext.Append ((string) Part.getContent ());} else if (Part.ismenstype ("Multipart / * ")) {Multipart Multipart = (Multipart) Part.getContent (); Try {int count (); for (int i = 0; i / * * * Is determined whether receipt of this message, if necessary acknowledgment returns "true", otherwise "false" * / public boolean getReplySign () throws MessagingException {boolean replysign = false; String needreply [] = mimeMessage.getHeader ( "Disposition -Notification-to "); if (needreply = null) {replysign = true;}! return replysign;} / * * * get this message message-ID * / public String getMessageId () throws MessagingException {return mimeMessage.getMessageID ( } / * * * [Determine if this message is read, if not read, return false, turn back to true] * / public boolean isnew () throws messagingException {// boolean isnew = false; // flags flags = (( MIMEMESSAGE) .GETFLAGS (); //flags.flag [] flag = flags.getsystemflags (); //system.out.println ("Flags's length:" flag.length); // for (int i = 0; i (Disposition.Equals (part.attachment)) || (Part.equals (Part.inline)))))) ATTACHFLAG = true; Else IF (MPART / * ") {attachflag = iscontainattach ((Part" ) mPart);} else {string consty = mpart.getContentType (); if ("Application")! = -1) attachflag = true; if (conty.tolowercase (). INDEXOF (" ")! = -1) attachflag = true;}}} catch (exception ex) {system.out.println (" [iscontainattach method " "] / n "); return false;}} else .isMimeType ( "message / rfc822")) {attachflag = isContainAttach ((Part) part.getContent ());} return attachflag;} / * * * [save] Annex * / public void saveAttachMent (Part part) throws Exception { String filename = ""; if (part.ismemtype ("Multipart / *")) {Multipart MP = (Multipart) part.getContent (); for (int i = 0; i (. FileName.toLowerCase () indexOf ( "GB2312") = -1!)) {FileName = MimeUtility.decodeText (fileName); saveFile (fileName, mpart.getInputStream ());}}}} else if (part.isMimeType ("Message / RFC822")) {saveattachment () Part.getContent ());}} / * * * [Set attachment storage path] * / public void setattachpath (string attachpath) {this.saveattachpath = attachpath;} / * * * [Set Date Display Format] * / Public Void SetDateFormat (String Format) THROWS Exception {this.dateFormat = Format;} / * * * [Get Accessory Storage Path] * / Public STRING GetAttachPath () {Return SaveAttachPath; } / * * * [truly save the attachment to the specified directory] * / private void saveFile (String fileName, InputStream in) throws Exception {String osName = System.getProperty ( "os.name"); String storedir = getAttachPath () String separator = ""; if (osname == null) OsName = ""; if (osname.tolowercase (). INDEXOF ("win")! = -1) {separator = "//"; if (storeDir = = NULL || Storedir.Equals (")) Storedir =" C: // TMP ";} else {separator =" / "; storedir =" / home / qianglee / mail / user / data ";} String SaveFullPath = GetAttachPath (); //system.out.println (" Format Time: / N "); Calendar Cal = Calendar.GetInstance (); SimpleDateFormat Formatter = New SimpleDateFormat (" YYYY-MM-DD "); string mdatetime = formatter.format (CAL.GetTime ()); //System.out.println (" ); // MDateTimes = 2004 -12-05 file newdir1 = new file (storedir "/" mdatetime); if (newdir1.mkdir ()) system.out.println ("******** successfully created a folder 1 layer ** ******** / n "); thread.sleep (100); file newdir2 = new file (storedir " / " mdatetime " / " savefullpath); if (newDir2.mkdir ()) System.out .println ("******** successfully created a folder 2 layer *********** / n"); thread.sleep (100); // Subsename here's extension, Then rename the filename String FileExt = ""; if (filename.indexof (". Jpg")> 0 || filename.indexof (". Jpg")> 0) FileExt = ".jpg"; IF (". png")> 0 || filename.indexof (". png")> 0) fileext = ".png"; if (filename.indexof (". gif")> 0 || filename. IndexOf (". GIF")> 0) FileExt = ".gif"; if (filename.indexof (". bmp")> 0 || filename.indexof (". bmp")> 0) fileext = ".bmp" ; System.out.println ( "file extension: [" fileExt "] / n"); String rand_fileName = Long.toString (System.currentTimeMillis ()); // fileExt; String last_fileName = rand_fileName fileExt; System. Out.println ("file name: [" rand_filename "] / n"); system.out.println ("file original name: [" filename "] / n"); file storefile = new file (storeDir "/ " mDateTime " / " saveFullPath separator last_fileName); String picAddress =" http://xxx.xxx.xxx.xxx " " / user / data / " mDateTime " / " saveFullPath separator rand_fileName " .png "; setPicaddress (PicadDress); // Set the image storage address system.out.println (" Last attachment is saved to: [" storefile.toString () "] / n "); // for (int i = 0; storefile.exists (); i ) {// storefile = new File (storedir separator fileName i); //} BufferedOutputStream bos = null; BufferedInputStream bis = null; try {bos = new BufferedOutputStream (new FileOutputStream (storefile); bis = new bufferedinputStream (in); int C; while ((c = bisread ())! = -1) {bos.write (c); bos.flush ();}} catch {EXCEPTION. PrintStackTrace (); throw new exception ("file saver failed!");} finally {bos.close (); bis.close ();}} / * * * Split the sender's mail name * get the sender's number * / public static String getMobileNumber (String srcMailName) {// public String getMobileNumber (String srcMailName) {String sParm = srcMailName; String temp = srcMailName; if (temp == null || temp.equals ( "")) {temp = "WrongMobile";} //if (tmp.length() = ) IF (Temp.indexof ("<") <0 || Temp.indexof ("@") <0) {TEMP = "WRONGMOBILE";} else {temp = sparm.substring (Sparm.indexof ("<") 1, sparm.indexof ("@")); //sparm.Length ()} return temp;} / * * * Split the sender's mail name * get the sender's email address to reply * / public static String getMobieleSender (String srcMailAddress) {// public String getMobieleSender (String srcMailAddress) {String sParm = srcMailAddress; String temp = srcMailAddress; if (temp == null || temp.equals ( "")) {temp = "wrongaddress" } Else {temp = sparm.substring (Sparm.indexof ("<") 1, sparm.indexof (">")); //sparm.length ()} Return Temp;} / * * Send Mail * * @param smtpHost * * @param email * * @throws MessagingException * / protected static void sendMail (String email, String returnID, String mid, boolean flag) throws MessagingException // protected void sendMail (String email, String returnID, boolean flag) throws MessagingException {Try {// string mailid = returnid; // substring (Sparm.indexof ("<") 1, Sparm.indexof (">")); // mailid = mailid.substring (Mailid.Indexof ("0") 1, mailid.length ()); //system.out.println ("******* **************************************** "); //system.out.println ( "Id = [" mailid "] / n / n"); //system.out.println ("********************* ************************* "); Properties PROPS = System.getProperties (); Props.Put (" mail.smtp.host "," Mail .xxx.com.cn "); // SMTP server //props.put ("mail.smtp.host", "mail.xxx.com"); // SMTP server Props.put ("mail.smtp.auth", "true"); // Do you need to verify your identity prOPs.put ("mail.mime.charset", "GB2312"); // message Text character set // string username = "xxxx"; // mailbox user name // String password = "xxxx"; // mailbox password // String username = "xxxx"; // mailbox username // string password = "xxxx"; // mailbox password string username = "xxxx"; // mailbox user name string password = "xxxx"; // mailbox password SMTPAUTHENTICATOR Authenticator = new smtpauthenticator (username, password); // User authentication // Create A New session Object session session = session.GetInstance (props, authenticator); session.setdebug (false); // Whether to print debug information tag // String from = "xxxx@xxx.com.cn"; // sender Mailbox // string from = "xxxx@xxxx.com"; // Send square mailbox string from = "xxxx@xxx.com.cn"; // send square mail box string to = email; // Receive square mail box string subject = "Thank you for your participation!"; // message title String body = ""; if (flag) {// body = "Hello! Thank you for your participation! Your post number is [" returnid "], if you want Cancel this post release, please reply to this message and do not send any attachments, the system will cancel your postings! If you want to release it, please don't reply this message. "; // message body body =" Hello! Thank you! Participate! Your post number is [" returnid "], if you want to cancel the post release, click on the connection http: // xxx below. xxx.xxx.xxx/user/userManager.jsp?mid=" mid "is canceled. "; // mail body body =" copyright statement: XX has copyrights of this site page design; the copyright of the picture information is owned by the information provider, and the functional content is owned by this site. Any person may not copy or make mirroring on the server to which the site belongs is not explicit written without XXX. Traditional media reprints or any other form of commercial use must be contacted with the data provider or XXXX in advance and appraised. XXXX's copyright, signature rights, and portrait disputes caused by the contributor's publishing content shall be responsible by the contributor. This site does not assume any responsibility. The content provided by the contributor represents only its personal behavior and has nothing to do with this standpoint. For users uploading content on this site, the upload content is regarded as voluntarily, and the author will pay another fee; and the uploading content may be downloaded or used by others. Anyone who uploaded content on this site is considered to agree to others. Free download in this site, use this upload content. Uploading content is strictly prohibited to issue or link illegal information about politics, pornography, religion, superstition, otherwise the content of the criminal or civil legal responsibility caused by this content is borne. For this site, it is obliged to provide the public security department to provide the public security department to provide information on the public security department. Attachment: 1. This site will prior announcement if you need to suspend services due to system maintenance or upgrade. If the service is caused by hardware failure or other force majeure, the site does not assume any responsibility for all inconveniences and losses caused during the suspended service. 2. This system does not assume any responsibility when the system is lost, and this site does not assume any responsibility. 3. Users have a variety of laws during this site, and everything is responsible for himself. This site does not assume any responsibility. The final interpretation right of this site is all all of XX. "; // body =" Hello! Thank you for your participation! Your post number is [" Returnid "], if you want to cancel this post release, please click below to connect http://xxx.xxx.xxx.xxx/user/subcancel.jsp?uid=" mailid "Cancel. "; // mail body} else {body =" Hello! You have successfully canceled the information of the published state, thank you for your participation! Please do not reply to this message. "; // message body} // create a new MimeMessage object (using the Session created above) MimeMessage message = new MimeMessage (session); message.setFrom (new InternetAddress (from,"! Thank you for your participation "," gb2312 " ))); Internetdress [] address = new interfaceaddress [] {new internetdress (to, "Receive Man Name", "GB2312")}; message. rerecipients (message.recipientType.to, address); // If you don't need to take an accessory Use the following two lines of code directly to Message.SetContent (Body, "Text / Plain"); Message.SetText (Body, "GB2312"); system.send (Message); system.out.println ("--- --- Mail Send to [" TO "] Success ------- / n ");} catch (throwable t) {system.out.println (" ----- email no send success ------- / n "); T.PrintStackTrace (System.out);}} / * * * PrasemimeMessage class test * / public static void main (String args []) throws exception {// public void run () {system.out.println ("begin thread / n"); int Timecount = 0; While (TRUE) {Try {// Login mailbox recipient, sending information, inserting a database, reverse query, String host = "pop.xxxx.com.cn"; string username = "xxxx"; string password = "xxxx "; Properties props = new Properties (); Session session = Session.getDefaultInstance (props, null); Store store = session.getStore (" pop3 "); store.connect (host, username, password); Folder folder = store. GetFolder ("Inbox"); Folder.Open (Folder.Read_Write); message message [] = folder.getMess (); System.out.Println ("A total of: [" message.length "]] 邮 邮 / N" ); PraseMimeMessage PMM = NULL; for (int i = 0; i Insert Database Record, etc. // If you take the way, then the storage attachment is performed, and the user's mail record is inserted into the database processing // Get the sender email address system.out.println ("[Processing Mail Process Start] / n"); System.out.println ("[**************************************** ] / n "); string sender = getMobielesender (whose); string mobileUser = getMobilenumber (whose); // This message does not repeat the library table query indicates String MessageOnlyid; // Reply Successful Mailid No. String ReturnMailid; if (Sender. Equals ("WRONGADDRESS")) System.out.println ("Unable to get the user's email address, unable to reply! / n"); else {string realusermobile; string tmpsender = sender; string tmpsender2 = sender; tmpSender2 = sender.substring (TmpSender.indexof ("<") 1, TmpSender.indexof ("@")); system.out.println (TmpSender2 "is the mail name / n"); string idmobileuser = tmpsender2; if (TmpSender2.length )! = 11 ||! (TmpSender2.substring (0, 3)). Equals ("xxx")) {system.out.println (TmpSender2 "mail name non-mobile phone number, calling interface to obtain / n"); AIMCQuery QueryMobile = new aimcQuery (); realusermobile = querymobile.aimcResult (tmpsender); // realusermobile = "not get"; system.out.println (TMPS ENDER2 "Mail Name Non Mobile Number Call Interface Get = [" RealusermObile "] / N"); if (RealUserMobile.equals ("Not get" || realusermobile.equals (") || RealusermObile == null) { System.out.println (TmpSender2 "eventually failed to get the correct mail name, this message does not work! / N ");} if (Realusermobile.Length ()! = 11 ||! (Realusermobile.substring (0, 3)). Equals (" 133 ")) {system.out.println (TmpSender2 " eventually fail Get the correct mail name, this message does not process! / N ");} else {// Handling this message, including the accessory, calling the database insertion record, etc. // 1. Storage attachment // Judgment attachment status // //3 (PMM.iscontainattach ((part) message [i])) {//pmm.settachpath (mobileuser); pmm.SetattachPath; pmm.saveattachment ((part) Message [i]); // 2. Reply to the message //sendmail (RealUserMobile "@xxxx.com.cn "); // 3. Write the database system.out.println ("This record is written to the database, you want to get the user mail information / n"); System.out.Println ("[[[[[[User Mail Information:]] / N"); System. Out.println ("****** user mobile phone number, unique indication: [" RealusermObile "] / n"); system.out.println ("****** User Mail Send Date: [" PMM.GetSentDate () "] / n"); System.out.Println ("****** User Mail Title, Post Title: [" PMM.Getsubject () "] / n"); System.out.println ("****** User Mail body, post content: [" pmm.getBodytext () "] / n"); system.out.println ("*****) Mailbox name, auxiliary information: [" sender "] / n "); system.out.println (" ****** User attachment address 1 original: [" pmm.getpiicaddress () "] / n "); System.out.println (" ****** User attachment address 1 modified: [xxx] / n "); string title = new string (pmm.getsubject ()). GetBytes (" GB2312 " ), "ISO8859_1"); string body = new string (pmm.getBodytext ()). GetBytes ("gb2312"), "ISO8859_1"); // String Title = pmm.getsubject (); // string body = PMM .getBodytext (); if (title.equals (") || Title.equals (" ") || title == null || Title.equals (" null ") || Title.equals (" null ")) {System.out.println ("Title = [" Title "] / N"); title = "Title is not named"; Title = new string (Title.getbytes ("GB2312"), "ISO8859_1");} f (body.equals (") || body.equals (" / r / n ") || body.equals (" / n ") || body.equals (" / r ") || body == null || body.equals (" null ") || body.equals (" null ")) {system.out.println (" body " = [" "] / n "); body =" There is no specific body information "; body = new string (body.getbytes (" GB2312 ")," ISO8859_1 ");} string address = new string (Sender.getbytes (" GB2312 ")," ISO8859_1 "); string url = new string (pmm.getpicaddress ()). GetBytes (" GB2312 ") , "ISO8859_1"); messageOnlyID = Long.toString (System.currentTimeMillis ()); mailDBinsert insertMail = new mailDBinsert (); boolean insertFlag = insertMail.insertDB (realUserMobile, pmm.getSentDate (), title, body, address, url, URL, MessageOnlyid; if (insertflag) system.out.println ("Mail Information Insert Database Table Success / N"); Else System.Out.println ("Mail Information Insert Database Table Failed / N"); // Stop, then take the information you just inserted ..... Canceled, because there is an unsafe factor // only give the user a connection, then make it judge Thread.sleep (500); // It doesn't have to take the idmailid = INSERTMAIL.GETSENDID (MSSAGEONLYID); // 2. Reply to this message sendMail (tmpSender2 "@ xxxx.com.cn", returnMailID, messageOnlyID, true); // returnMailID, true); //sendMail(realUserMobile "@xxxx.com.cn ", returnMailID, true); insertMail. Close ();} else {// No attachment, query library, today all of the mobile phone number belonging to the user's mobile phone number is // first query the user release information Follow the mobile phone number and today's date (RealusermObile) //MAildbinsert INSERTMAIL = New maildbinsert (); //if (ISERTMAIL.GETUSERPOSTFLAG (RealUserMobile) )) )) )) )) )) )) )) )) )) ))) )) ))) )) )) ))) )) )) )) )) )) )) )) ))) ))) )) ))))) No status, according to the date and mobile number // INSERTMAIL.UPDATEUSERFLAG (RealUserMobile, (pmm.getsentdate (). Substring (0,8)))); // Sending a message tells the user that it has set up: // sendmail (RealusermObile "@ xxxx.com.cn "," "", false); //} //insertmail.close (); thread.sleep (500);}}} Else {// send mail account is mobile phone number, no need to call query interface Directly execute system.out.println ("" "The account of the message is the mobile phone number [" sender "] without calling query interface / N"); // 1. Storage attachment // With an attachment IF (PMM.iscontainAttach ((Part) Message [i])) {pmm.settachpath (mobileuser); pmm.saveattachment ((part) message [i]); // 2. Reply to the message // sendmail (sender); // 3. Write the database system.out.println ("This record is written to the database, you want to get the user mail information / n"); System.out.Println ("[[[[[[User Mail Information:]] / N"); System. Out.println ("****** user mobile phone number, unique indication: [" TmpSender2 "] / n"); system.out.println ("****** User email date: [" PMM.GetSentDate () "] / n"); System.out.Println ("****** User Mail Title, Post Title: [" PMM.Getsubject () "] / n"); System.out.println ("****** User Mail body, post content: [" pmm.getBodytext () "] / n"); system.out.println ("*****) Mailbox name, auxiliary information: [" sender "] / n "); system.out.println (" ****** User attachment address 1 original: [" pmm.getpiicaddress () "] / n "); System.out.println (" ****** User attachment address 1 modified: [xxx] / n "); string title = new string (pmm.getsubject ()). GetBytes (" GB2312 " ), "ISO8859_1"); string body = new string (pmm.getBodytext ()). GetBytes ("gb2312"), "ISO8859_1"); // String Title = pmm.getsubject (); // string body = PMM .getBodytext (); if (title.equals (") || Title.equals (" ") || title == null || Title.equals (" null ") || Title.equals (" null ")) {System.out.println ("Title = [" Title "] / N"); title = "Title is not named"; title = new string (titl E.GETBYTES ("GB2312"), "ISO8859_1");} IF (body.equals (") || body.equals (" / r / n ") || body.equals (" / n ") || Body.equals ("/ r") || body == null || body.equals ("null") || body.equals ("null")) {system.out.println ("body = [" body "] / n"); body = "There is no specific body information"; body = new string (Body.getbytes ("GB2312"), " ISO8859_1 ");} String address = new string (Sender.getbytes (" GB2312 ")," ISO8859_1 "); string url = new string (pmm.getpicaddress ()). GetBytes (" GB2312 "," ISO8859_1 ") ; messageOnlyID = Long.toString (System.currentTimeMillis ()); mailDBinsert insertMail = new mailDBinsert (); boolean insertFlag = insertMail.insertDB (tmpSender2, pmm.getSentDate (), title, body, address, url, url, messageOnlyID); IF (InsertFlag) System.out.Println ("Mail Information Insert Database Table Success / N"); Else System.Out.println ("Mail Information Insert Database Table Failed / N"); // Stop, then take it just now Inserted information, in the same, no ID of Thread.Sleep (500); returnmailid = INSERTMAIL.GETSENDID (MessageOnlyID); // Reply to send mailmail (sender "@ xxxx.com.cn", returnmailid, messageonlyid, true); // sendmail (sender, "0", true); // ReturnMailid, true); insertmail.close ();} else {// No attachment, query library, today's mobile phone number belonging to this user's mobile phone number today No // maildbinsert insertmail = new maildbinsert (); //if (IsertMail.getuserpostflag (TMPSENDER2, (PMM.GetSentDate ().substring (0, 8 )) )) ))) ))) )))) ))) ))) ))) ))) ))) ))) )) ))) ))) )))) )) ))))) Execute whether the user can set the user, according to the date and mobile number //insertmail.UpdateUserflag (TMPSENDER2, (pmm.getsentdate().substring (0 ,8))); // Send a message tells the user that it is already // sendmail (TmpSender2 "@ xxxx.com.cn", "", false); ///} //insertmail.close (); thread.sleep (500);}}} system.out.println ("[processing email flow end ] / n "); System.out.Println (" [****************************************** ******] / n "); system.out.println (" ************ Section [" TMPCount "] mail has been read and deleted *** ********** / n ");} folder.close (TRUE); store.close (); timecount ;} catch (exception e) {Continue;