This article is sorted by some chapters of the "J2Se Advanced" book written by JR, "J2SE advance" is writing, perfect stage. "J2SE advance" Writing project group Thank you for reading this article.
This article is taken from the snow without trace blog
With the continuous promotion of network applications, more and more emails are used by everyone. Although we often connect email with Foxmail, Outlook email clients, but often we also need to program the implementation of sending and receive mail, such as receipt of mail after a website registered user, or when shopping Send a confirmation email within a few minutes after completing the order. For such demand, we cannot write mail or handlers yourself through existing mail clients. Here you explain to you how to use JavaMail to implement mail delivery. Note: This article only intends to discuss some of the techniques of JavaMail tape accessories mail, so just give some code, more more exciting content, please look forward to the "J2Se Advanced" book.
1. Send a message with attachment
The mail we usually transmit is mainly broken down into 2, one is a message header, the subject, the subject, and the other part of the message, which includes an accessory of the message. When we send a normal mail, the type of content setting is "text / html". After the attachment, we need to set the content type to Multipart, and the content includes an attachment and "text / html" body. The following this tells you how to place the attachment into the email.
Private Multipart getMultipart ()
Throws MessagingException, unsupportedencodingexception {
MimeMultipart MP =
New mimemultipart ();
Try
{
/ / Set the content in Content
MIMEBODYPARTMBP =
New mimebodypart ();
/ / Please specify the character set, otherwise it will be garbled
ContentMbp.setContent (_mailContent.getContent (),
"text / html; charSet = GB2312");
mp.addbodypart (contentMBP);
//Add attachments
FOR
INT i = 0; i <_mailattachment.getattachpath (). Size (); i )
{
MIMEBODYPART MBP =
New mimebodypart ();
FileDataSource fds =
New fileDataSource (String)
_mailattachment.getattachpath (). Get (i));
Mbp.SetDataHandler
New DataHandler (FDS));
Mbp.setFileName (MimeUtility.Encode, "FDS.GetName (),
"GB2312", NULL);
MP.AddBodyPart (MBP);
}
}
Catch (MessagingException IE)
{
System.out.println (
"SET Content Message Error ..." IE.GetMessage ());
Throw IE;
}
Catch (unsupportedEncodingexception IE)
{
System.out.println (
"Encode the filename error ..." IE.getMessage ());
Throw IE;
}
Return MP;
}
The precautions for placement attachments are as follows:
Need to pay attention to the problem of the character set when sending Mail. Not only the content is set in Content, but also the file name also needs to be set. If we remove MBP.SetFileName (fds.getname (), "GB2312", "GB2312", "GB2312", this sentence, then the attachment you choose will still be taken to the email, but you can't see it in the attachment. We can know by viewing email. We use this feature to implement the HTML language written in the seminated content, and include the message of the image information.
2. Send a message containing the HTML page in Content
Everyone knows that html language can bring picture links (
), Then we need special processes for these links when sending emails. Otherwise, the picture will not be seen when the other party receives the message. Our special treatment is to send them as an attachment, but not in the attachment. To do this, you must first analyze the input content and find the path to the picture. Then put the content in content
This code becomes
. We use MBP1.SetHeader ("Content-ID", "IMG") when sending attachments. How do I specifically parse the operation of Content, I haven't described it. I now give an example of how to send a modified Content.
// For the Content of sending an HTML type. Inside the picture.
FOR
INT i = 0; I <_mailcontent.getimghash (). size (); i )
{
MIMEBODYPART MBP1 =
New mimebodypart ();
// Get the data of the picture
FileDataSource fds =
New fileDataSource
_Mailcontent.getimghash (). Get (
"IMG" i)));
// Set to MIMEBODYPART
Mbp1.setdataHandler
New DataHandler (FDS));
/ / Set the correspondence between the picture attachment and HTML
Mbp1.setHeader
"Content-ID",
"IMG" i);
mp.addbodypart (MBP1);
}
3. The status of the message
After reading the email, we can delete the flag to email, and then use true when you close the Folder, empty the email that has been marked as deletion. The status of the message is defined in class flags.flag. Including the following:
Flags.flag.answered
Flags.flag.deleted
Flags.flag.draft
Flags.Flag.Flagged
Flags.flag.recent
Flags.Flag.seen
Flags.flag.user
We can set according to different needs, but you need to note that all servers support these states. We can use the getPermanentFlags method before doing operations to get the status in the message. Refer to the following code
Message m = folder.getMessage (1);
// set the deleted flag
m.setflag (flags.flag.deleted,
True);
// Check if deleted Flag is set of this message
IF (M.isSet (Flags.Flag.Deleted))
System.out.println (
"Deleded message");
// Examine All System Flags for this Message
Flags flags = m.getflags ();
Flags.flag [] sf = flags.getsystemflags (); for
INT i = 0; i { IF (sf [i] == flags.flag.delete) System.out.println ( "Deleded message"); Else IF (sf [i] == flags.flag.seen System.out.println ( "Seen message"); } 4. Receive messages with accessories In the email with attachment, the content of the message is a multipart type so that we need to resolve it to get Content and attachments (it is the reverse process of sending messages with accessories). Everyone will find out when using Outlook, Foxmail, our mail is downloaded from the server and saved to the local hard drive, which makes us easy to browse the message offline. In the example below, we also saved the mail on the server to the local. If you are interested, you can write a client's graphical interface to read the saved mail. In the example below, I just introduce you how to resolve attachments. Private Void getttachfile (Part MessagePart, BufferedoutputStream Writettachobj) Throws ioException, MessagingException { Object content = messagepart.getContent (); Try { // This kind of mail is sent in Multi mode, // This mode includes an accessory and an email with HTML represents Content. IF (Content InstanceOf multipart) { Multipart contentTMP = (multipart) Content; / / If it is sent by the Multi mode, Bodypart (0) .GetContent () is definitely content System.out.println ( "Content ==" ContentTmp.getBodypart (0) .getContent ()); // getCount () You can get the number of Bodypart in Content, Content is the first // Bodypart, other attachments are pushed in sequence. But sometimes is another email, // and there may be other accessories in this email. The following code parses the nested situation with a loop. FOR INT i = 0; i { IF (contenttmp.getbodypart (i) .ismimetype "Multipart / *")))) { Multipart Multipart = (Multipart) ContentTmp.getBodypart (i) .getContent (); // This place increases the cycle to solve the case of nested attachments. FOR INT K = 0; k { // Content will also exist in the InputStream. SavetTachefile (Multipart.getBodypart (k) .GetContentType (), Multipart.getBodypart (k) .GetdisPosition (), Multipart.getBodypart (k) .GetFileName (), Multipart.getBodypart (k) .GetinputStream (), WRITEATTACHOBJ); } } Else { SavetTachefile (contentTmp.getBodypart (i) .GetContentType (), ContentTMP.GetBodyPart (i) .GetdisPosition (), ContentTMP.getBodypart (i) .GetFileName (), ContentTMP.getBodypart (i) .GetinputStream (), Writeattachobj); } } } // In this case the message is a plain text form, and there is no accessory Else { Writeattachobj.write ((( "Content =" Content "/ r / n"). GetBytes ()); Writeattachobj.flush (); } } Catch (Exception IE) { System.out.println ( "eXception ====" IE.getMessage ()); } }