Javamail: parsing the email format with attachments

Source: Internet
Author: User

Javamail was used in the last lesson. Javamail can use the POP3 protocol to receive mails and can be used to publish articles by mail. So what should we do? In this case, you must first understand the email format with attachments. After the email is parsed, we can see the following email code (note that the delimiter has been replaced with a easier-to-read format for ease of reading ):

Received: From 127.0.0.1 by fms4711; Fri, 25 Jul 2008 13:02:36 + 0800
Date: Fri, 25 Jul 2008 13:02:36 + 0800
From: "beansoft" <beansoft@earth.org>
To: "HP" Subject: =? Gb2312? B? Wb249ri9vp4 =? =
Message-ID: <200807251302355150265@earth.org>
X-mailer: Foxmail 6, 13,102, 15 [CN]
Mime-type: 1.0

Content-Type: multipart/mixed;
Boundary = "============== split a ================"

This is a multi-part message in MIME format.

-- =
Content-Type: multipart/alternative;
Boundary = "============= split 2 =============================="

-- =
Content-Type: text/plain;
Charset = "gb2312"
Content-transfer-encoding: 7bit

Body

-- =
Content-Type: text/html;
Charset = "gb2312"
Content-transfer-encoding: 7bit

<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML> <Meta http-equiv = Content-Type content = "text/html; charset = gb2312">
<Meta content = "mshtml 6.00.5730.13" name = generator> <Link
Href = "BLOCKQUOTE {margin-top: 0px; margin-bottom: 0px; margin-left: 2em }"
Rel = stylesheet> <Body style = "font-size: 10pt; margin: 10px; font-family: verdana">
<Div> <font face = verdana size = 2> <strong> body </strong> </font> </div> <font
Face = verdana size = 2>
<Div> & nbsp; </div> </font> </body>

-- = --

-- =
Content-Type: Application/octet-stream;
Name = "string2java.jpg"
Content-transfer-encoding: base64
Content-Disposition: attachment;
Filename = "string2java.jpg"

/9j/4 aaqskzjrgabaqaaaqabaad/2wbdaaggbgcgbqghbwcjcqgkdbqndasldbksew8uhrofhh0a
Oakkkkaciiigaooooa // 2q =

-- =
Content-Type: Application/octet-stream;
Name = "foxmailupdate. log"
Content-transfer-encoding: base64
Content-Disposition: attachment;
Filename = "foxmailupdate. log"

Oaaaapgb7ghgscg8a8w48hc9ihdb8ccilhlkxcywnp + 8dprb30zrsi2k4tpjp0gylb3cua0jrtbl
G/z8xa5pjneuwd9uiu0neh4iobo + 12ok9hskk7xfxyhw ++ a50fhqucdxx5kpf2d6

-- = --
 

 

It corresponds to the message object of javamail. A message object has multiple child objects, such as multipart objects. More specifically, the entire mail content is a large multipart, however, the body of the mail is nested in a submultipart. If you do not understand the organizational structure, you may not be able to get the body of the mail correctly. This structure is shown in:

Email message

 

Header (subject, sender information, etc)
 
All multipart emails, including body and attachments

 

Body multipart

 

Text text/plain

 

Content-Type: text/plain; charset = "gb2312"

 
 
HTML webpage text/html

 

Content-Type: text/html; charset = "gb2312"

 
 

 

 
 
 

Appendix 1

 

Content-Type: Application/octet-stream;

Name = "string2java.jpg"

Content-transfer-encoding: base64

Content-Disposition: attachment;

Filename = "string2java.jpg"

 
 
 

Appendix 2

 

Content-Type: Application/octet-stream;

Name = "foxmailupdate. log"

Content-transfer-encoding: base64

Content-Disposition: attachment;

Filename = "foxmailupdate. log"

 
 

 

 

 

With this information, we can resolve the email. The Code is as follows:

 

Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Import java. util. properties;

Import javax. Mail. address;
Import javax. Mail. bodypart;
Import javax. Mail. fetchprofile;
Import javax. Mail. flags;
Import javax. Mail. folder;
Import javax. Mail. message;
Import javax. Mail. messagingexception;
Import javax. Mail. multipart;
Import javax. Mail. nosuchproviderexception;
Import javax. Mail. part;
Import javax. Mail. Session;
Import javax. Mail. store;
Import javax. Mail. Internet. internetaddress;
Import javax. Mail. Internet. mimemultipart;

/**
* Mail acceptance test
*
*/
Public class pop3mailreceivertest {

Public pop3mailreceivertest (){
Try {
// 1. Set the connection information to generate a session
Properties props = new properties ();
Props. Put ("mail. Transport. Protocol", "POP3"); // POP3 receiving protocol
Props. Put ("mail. Pop. Port", "110 ");
// Props. Put ("mail. debug", "true"); // debug

Session session = session. getinstance (props );

// 2. Get the store and connect to the server
Store store = session. getstore ("POP3 ");
Store. Connect ("localhost", "hp@earth.org", "1234 ");
// 3. Open the default directory folder through store
Folder folder = store. getdefaultfolder (); // default parent directory
If (Folder = NULL ){

System. Out. println ("server unavailable ");
Return;
// System. Exit (1 );
}

// System. Out. println ("Default mailbox name:" + folder. getname ());
//
// Folder [] folders = folder. List (); // default directory list
//
// System. Out. println ("Number of subdirectories in the default directory:" + folders. Length );

Folder popfolder = folder. getfolder ("inbox"); // get the inbox
Popfolder. Open (Folder. read_write); // you can delete emails to open the directory.
// 4. list all emails in the inbox
Message [] messages = popfolder. getmessages ();
// Number of retrieved mails
Int msgcount = popfolder. getmessagecount ();
System. Out. println ("Total Emails:" + msgcount + "mails ");

// Fetchprofile fprofile = new fetchprofile (); // select the Mail Download mode,
// Select different modes based on the network speed
// Fprofile. Add (fetchprofile. item. envelope );
// Folder. Fetch (messages, fprofile); // optional download email

// 5. process each email cyclically and convert the email into news
For (INT I = 0; I <msgcount; I ++ ){
Message MSG = messages [I]; // a single email
// Sender information
Address [] froms = msg. getfrom ();
If (froms! = NULL ){
System. Out. println ("sender information:" + froms [0]);
Internetaddress ADDR = (internetaddress) froms [0];
System. Out. println ("sender address:" + ADDR. getaddress ());
System. Out. println ("sender display name:" + ADDR. getpersonal ());
}
News news = new news (); // generate a news object
System. Out. println ("Email Subject:" + msg. getsubject ());
News. settitle (msg. getsubject ());

// Getcontent () is used to obtain the package content. The part is equivalent to the outer packing.
Multipart = (multipart) msg. getcontent (); // obtain the content of the email, which is a large package,
// Multipart
// Contains all emails (body + attachment)
System. Out. println ("Total mails" + multipart. getcount () + "part composition ");

// Process each part in sequence
For (Int J = 0, n = multipart. getcount (); j <n; j ++ ){
System. Out. println ("Processing Section" + J + "section ");
Part = multipart. getbodypart (j); // unpack and retrieve all parts of multipart. Each part may be the mail content,
// It may also be another small package (multippart)

// Determine whether the content of this package is a small package. Generally, this part is the body Content-Type: multipart/alternative.
If (part. getcontent () instanceof multipart ){
Multipart P = (multipart) part. getcontent (); // convert it into a small package
System. Out. println ("small package contains" + P. getcount () + "part ");
// List all content in a small package
For (int K = 0; k <p. getcount (); k ++ ){
System. Out. println ("small package content:" + P. getbodypart (k). getcontent ());
System. Out. println ("content type :"
+ P. getbodypart (k). getcontenttype ());
If (P. getbodypart (k). getcontenttype (). startswith ("text/plain ")){
// Process the text body
News. setbody (P. getbodypart (k). getcontent () + "");
} Else {
// Process the html body
News. setbody (P. getbodypart (k). getcontent () + "");
}
}
}

// Content-Disposition: attachment; filename = "string2java.jpg"
String disposition = part. getdisposition (); // process the Attachment Information
If (Disposition! = NULL ){

System. Out. println ("Attachment Found:" + part. getfilename ());
System. Out. println ("content type:" + part. getcontenttype ());
System. Out. println ("attachment content:" + part. getcontent ());
Java. Io. inputstream in = part. getinputstream (); // open the input stream of the attachment.
// Read the attachment bytes and store them in the file
Java. Io. fileoutputstream out = new fileoutputstream (part. getfilename ());
Int data;
While (Data = in. Read ())! =-1 ){
Out. Write (data );
}
In. Close ();
Out. Close ();
}
}
//}
// Todo newsdao. Save (News); // store the information carried by the email as news

// 6. delete a single email and mark the email to be deleted.
// Msg. setflag (flags. Flag. Deleted, true );
}

// 7. Disabling folder will actually Delete the email, and false will not be deleted
Popfolder. Close (true );
// 8. close the store and disconnect the network
Store. Close ();
} Catch (nosuchproviderexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (exception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
New pop3mailreceivertest ();

}

}

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.