Javamail operation guide (2)

Source: Internet
Author: User
Bromon originality, please respect copyright
Ii. receiving emails

Generally, we use the POP3 protocol to receive emails. imap does not involve emails now. Although it takes me a lot of time to figure out the mail receiving function, it is so easy. A program can basically include it.

There are roughly three types of Emails: plain text emails, text emails containing other data, and emails containing attachments.

Code
/*
* Created on 2004-4-26
*/
Package org. bromon. mail;
Import javax. Mail .*;
Import java. util .*;
Import java. Io .*;

/**
* @ Author bromon
*/
Public class extends er
{
Folder inbox;
Store store;

// Connect to the email server to obtain the list of all emails
Public message [] getmail (string host, string name, string password) throws exception
{
Properties prop = new properties ();
Prop. Put ("mail. pop3.host", host );
Session session = session. getdefaultinstance (PROP );
Store = session. getstore ("POP3 ");
Store. Connect (host, name, password );

Inbox = store. getdefaultfolder (). getfolder ("inbox ");
Inbox. Open (Folder. read_only );

Message [] MSG = inbox. getmessages ();

Fetchprofile profile = new fetchprofile ();
Profile. Add (fetchprofile. item. envelope );
Inbox. Fetch (MSG, profile );

Return (MSG );
}

// Method required to process any email
Private void handle (Message MSG) throws exception
{
System. Out. println ("Email Subject:" + msg. getsubject ());
System. Out. println ("email Author:" + msg. getfrom () [0]. tostring ());
System. Out. println ("Sending date:" + msg. getsentdate ());
}

// Process text emails
Public void handletext (Message MSG) throws exception
{
This. Handle (MSG );
System. Out. println ("email content:" + msg. getcontent ());
}

// Process multipart mails, including the function of saving attachments
Public void handlemultipart (Message MSG) throws exception
{
String disposition;
Bodypart;

Multipart MP = (multipart) msg. getcontent ();
Int mpcount = mp. getcount (); // Number of miltiparts, used in addition to multiple parts, such as multiple attachments
For (INT m = 0; m <mpcount; m ++)
{
This. Handle (MSG );

Part = mp. getbodypart (m );
Disposition = part. getdisposition ();
If (Disposition! = NULL & disposition. Equals (part. Attachment) // you can check whether an attachment exists.
{
// This. saveattach (part); // This method is used to save the attachment. comment out the attachment because it may have a virus. Clear the mailbox and remove the comment.
} Else {
System. Out. println (part. getcontent ());
}
}
}

Private void saveattach (bodypart part) throws exception
{
String temp = part. getfilename (); // get the name of the unprocessed attachment
String S = temp. substring (11, temp. indexof ("? = ")-1); // go to the header and footer

// The file names are generally base64 encoded, and the following is the decoding
String filename = This. base64decoder (s );
System. Out. println ("attachment:" + filename );

Inputstream in = part. getinputstream ();
Fileoutputstream writer = new fileoutputstream (new file (filename ));
Byte [] content = new byte [255];
Int READ = 0;
While (read = in. Read (content ))! =-1)
{
Writer. Write (content );
}
Writer. Close ();
In. Close ();
}

// Base64 Decoding
Private string base64decoder (string s) throws exception
{
Sun. Misc. base64decoder decoder = new sun. Misc. base64decoder ();
Byte [] B = decoder. decodebuffer (s );

Return (new string (B ));
}

// Close the connection
Public void close () throws exception
{
If (Inbox! = NULL)
{
Inbox. Close (false );
}

If (store! = NULL)
{
Store. Close ();
}
}

Public static void main (string ARGs [])
{
String host = "pop.163.com ";
String name = "bromon ";
String Password = "My password ";

Worker er worker ER = new worker Er ();

Try
{
Message [] MSG = Receiver. getmail (host, name, password );

For (INT I = 0; I <msg. length; I ++)
{
If (MSG [I]. ismimetype ("text/*") // determines the mail type
{
Explorer. handletext (MSG [I]);
} Else {
Aggreger. handlemultipart (MSG [I]);
}
System. Out. println ("****************************");
}
Cycler. Close ();
} Catch (exception E)
{
System. Out. println (E );
}
}
}

A brother who is not used to reading Java code may feel a little troublesome. There is a small problem. The downloaded attachment will be added with the "#" symbol after the file name, I don't know whether this is the special handling of javamail or the POP3 specification. It's easy to change the file name through the program. There are many other operations for email. You can take a look at javadoc by yourself. I will not affect your exploration. Configure the proxy server in properties to allow the program to send and receive emails through the proxy. Generally, HTTP, Socks 4, and socks 5 support both.

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.