To send and receive messages using Java Mail

2010-09-12  来源:本站原创  分类:Java  人气:301 

With the continuous promotion of web applications, e-mail more and more are all used. Although we tend to e-mail and Foxmail, Outlook e-mail clients such as linked, but often we also need to send their programming to receive e-mail, for example, a Web site after Web site registered users of the receipt issued by mail, or when shopping online , after the completion of orders send a confirmation e-mail within minutes. For such demand, we can not have the mail client need to send or write your own message handler. Here we talk about how to use JavaMail to implement send and receive mail.

Note: This article is only intended to discuss the JavaMail send and receive messages with attachments some skills, so just give part of the code
1. Send e-mail with attachments

We usually send a message can be decomposed into two main parts, one is the sender, then the addressee, subject of mail headers, and part is the message content, which includes e-mail attachment. We send regular mail settings when the content type is "text / html", belt attachments, we need to set the content type of Multipart, then content, including the accessories and "text / html" type of text. Here's the place to tell you how to attachment to the message.

private Multipart getMultipart() throws MessagingException,UnsupportedEncodingException {
MimeMultipart mp = new MimeMultipart();
try
{
//  Set the contents of the content
MimeBodyPart contentMbp = new MimeBodyPart();
//  Please specify the character set, otherwise it will be garbled
contentMbp.setContent(_mailContent.getContent(),
"text/html; charset=GB2312");
mp.addBodyPart(contentMbp);
//  Add Attachment
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.encodeWord(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;
}

Note attachment to place as follows:
Send mail to note when the character set issues. Not only the content in to settings and file names also need to set. If we remove

mbp.setFileName(MimeUtility.encodeWord(fds.getName(),"GB2312",null));

this sentence, then you will be brought to the selected e-mail attachments or inside, but could not see the attachment. We can know by looking at the message size. We use this characteristic to achieve is to send html content in written language, and contains the picture information of the message.

2. To send content in the html page that contains the message

We all know html language to bring picture link (

), Then when we send e-mail links on the need for these pictures to do special processing. Otherwise, the message is received in each other will not see pictures when. Our special processing method is to send them as attachments, but does not appear in the annex. To do that would first need to parse the input of content and find the path brought pictures. Then the content of

Code into a. When we send attachments with mbp1.setHeader ("Content-ID", "IMG") to correspond to the pictures and attachments. How to resolve the specific content of the operation I will not go into, I now how to modify the given good examples of content sent.

//  Send html type for  content.  Including pictures inside  .
for(int i=0;i<_mailContent.getImgHash().size();i++)
{
MimeBodyPart mbp1 = new MimeBodyPart();
//  Get the picture of the data
FileDataSource fds = new FileDataSource(
(String)_mailContent.getImgHash().get("IMG"+i));
//  Set to MimeBodyPart in
mbp1.setDataHandler(new DataHandler(fds));
//  Html for images and the corresponding relationship between attachment
mbp1.setHeader("Content-ID","IMG"+i);
mp.addBodyPart(mbp1);
}

3. The status of the message

After reading the message, we can set the delete flag to the message, and then close with a true FOLDER time to clear has been marked as deleted messages. The message status is defined in the class FLAGS.FLAG. Include 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 be set according to different needs, but it should be noted that not all servers support these states. We are doing before you can getPermanentFlags way to get the Message in the state. Reference 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("DELETED message");
// Examine ALL system flags for this message
Flags flags = m.getFlags();
Flags.Flag[] sf = flags.getSystemFlags();
for (int i = 0; i < sf.length; i++)
{
if (sf[i] == Flags.Flag.DELETED)
System.out.println("DELETED message");
else if (sf[i] == Flags.Flag.SEEN)
System.out.println("SEEN message");
}

4. Receive e-mail with attachments

In the e-mail with attachments, the message is Multipart content type, so we need to resolve it to get content and attachments (which is to send mail with attachments reverse process). We use outlook, foxmail when these e-mail client will find that our messages are downloaded from the server and saved to local hard disk, and in this way to facilitate our e-mail offline browsing. In the following example we have to save messages on the server to the local. If you are interested you can write a client graphical interface to read the saved messages.
In the following example, I just told you how to parse attachments.

private void getAttachFile(Part messagePart,BufferedOutputStream writeAttachObj)
throws IOException, MessagingException
{
Object content = messagePart.getContent() ;
try
{
//  In this case the message is sent with the multi mode  ,
//   This model includes an attachment and the use of html that  content  Mail
if (content instanceof Multipart)
{
Multipart contentTmp = (Multipart) content ;
//  MULTI mode if it is sent  ,BodyPart(0).getContent()  Sure it is  content
System.out.println("content==" + contentTmp.getBodyPart(0).getContent()) ;
//getCount()  Can be content in the  bodyPart  The number, content is the first
//bodyPart,  Other accessories in accordance with the order and so on. But sometimes is another e-mail attachment  ,
// And this message inside may have other attachments. The following code uses the loop to parse the nested case  .
for (int i = 0 ; i < contentTmp.getCount() ; i++)
{
if (contentTmp.getBodyPart(i).isMimeType("multipart/*"))
{
Multipart multipart = (Multipart)
contentTmp.getBodyPart(i).getContent() ;
//  The place to increase recycling is to solve the case of nested attachments  .
for (int k = 0 ; k < multipart.getCount() ; k++)
{
//content  Also present in INPUTSTREAM in  .
saveAttacheFile(multipart.getBodyPart(k).getContentType(),
multipart.getBodyPart(k).getDisposition(),
multipart.getBodyPart(k).getFileName(),
multipart.getBodyPart(k).getInputStream(),
writeAttachObj);
}
}
else
{
saveAttacheFile(contentTmp.getBodyPart(i).getContentType(),
contentTmp.getBodyPart(i).getDisposition(),
contentTmp.getBodyPart(i).getFileName(),
contentTmp.getBodyPart(i).getInputStream(),
writeAttachObj);
}
}
}
//  This case the message is plain text form, and no attachment
else
{
writeAttachObj.write(("content = "+content+"
").getBytes());
writeAttachObj.flush();
}
}
catch (Exception ie)
{
System.out.println("exception====" + ie.getMessage()) ;
}
}
相关文章
  • To send and receive messages using Java Mail 2010-09-12

    With the continuous promotion of web applications, e-mail more and more are all used. Although we tend to e-mail and Foxmail, Outlook e-mail clients such as linked, but often we also need to send their programming to receive e-mail, for example, a We

  • WEBLOGIC JMS send and receive messages in 2010-07-30

    A JMS application consists of the following elements: · JMS client. Using JMS API to send and receive messages Java program. * Non-JMS (Non-JMS) client. Recognizing this is important - the old procedures often become part of the JMS application, and

  • Test send and receive messages 2010-11-11

    Send a message code: package com.yzk.test.message; import javax.jms.Connection; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.a

  • GCMail how to restrict internal and external network mail system send and receive messages? 2011-08-21

    Most companies now use both business electronic post office, to relieve the employees inside and outside the network to send and receive letters, as internal information security is a major part of communication, then how to manage the business part

  • apache James Mail Server 2.3.2 send and receive messages outside the network 2010-06-03

    Reference: http://www.blogjava.net/AstroQi/archive/2010/05/24/224181.html http://blog.csdn.net/lsharp/archive/2009/09/04/4517239.aspx If it is outside the network can send mail, but can not receive external network mail (after receiving the message i

  • JSM to send and receive messages 2010-03-29

    1.JSM message to send import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MapMessage; import javax.jms.Message; import javax.jms.MessageProduc

  • How to use JAX-WS binding SOAP with attachments send and receive messages? 2010-12-09

    WPS and WID V7.0 by JAX-WS binding of SOAP attachments with more comprehensive support, including: no reference to Annex (Unreferenced Attachments, SOAP message envelope does not reference an annex); comply with the W3C specification references attac

  • GCMail Server + Dynamic DNS test peanut shells outside the network send and receive messages and stability 2011-08-21

    Router Port Mapping 1, open IE, enter your router's IP: "192.168.0.1" or "192.168.1.1" pop-up the router login screen. Enter the user name with password: The default account is "admin", password: "admin" Select &quo

  • java mail api Xiangjie 2010-03-30

    JavaMail API Xiangjie Study: Source: Release Date: April 7, 2007 Views: 26 Abstract: JavaMail API is to read, write, send an electronic message optional package. We use it to build as Eudora, Foxmail, MS Outlook Express mail user agent generally (Mai

  • E-mail send and receive a comprehensive analysis of the failure 2010-08-08

    Internet e-mail is one of the most important applications, it provides a very convenient and fast means of communication. However, many users have had the experience of e-mail failures. The following E-mail the author by the failure of transceivers f

  • java mail send a message 2010-05-25

    J2EE JavaMail http://java.sun.com/products/javamail JavaMail API is an optional, can be used for reading, writing and sending electronic messages package (standard extension). You can use this package to create Mail User Agent (Mail User Agent, MUA)

  • Send mail using java mail 2011-10-06

    Toss the company's Web site recently, as I currently only java, so I use the java as a development language. Hey, php have to study under, and there are mobile phone development. To learn too much. Encountered in the open a mailbox to send mail, you

  • Java TCP / IP Socket Programming Notes (4) - send and receive data 2009-02-03

    1.TCP/IP agreement calls for information must be in the block (chunk) to send and receive, while the block length must be a multiple of 8 bits, therefore, we can assume that TCP / IP protocol to transmit the message that byte sequence. How to send an

  • Operations in Java, SMS send and receive serial interface 2 2010-06-07

    4. To send data Successfully initialized, you can send and receive the normal data. We are here to do shows the way to use PDU, Text one way or the phone number of Modem do not support the second is also simple, in the last mention. First, we can sen

  • Serial Port in Java, SMS send and receive operations (transfer) 2010-06-27

    1. Configuration comm.jar. Comm.jar is the realization of the underlying serial Sub operation API, the DLL File local calls, because Java Ben Shenbu have direct access to hardware setup capacity , it is by Tiaoyong local Fangfa to achieve. To Java's

  • Android under the call send and receive SMS messages, etc. 2010-10-28

    Original Address: http://blog.sina.com.cn/s/blog_694448320100luzw.html Android under the call send and receive SMS messages, etc. 1, adjusting the web browser Uri myBlogUri = Uri.parse ("http://xxxxx.com"); returnIt = new Intent (Intent.ACTION_V

  • Using java mail api and apache mail api sample code to send email 2011-04-24

    Mail this article were tested using the Java API ( http://www.oracle.com/technetwork/java/javamail/index.htm L) and the Apache mail API ( http://commons.apache.org/email/ ) to send mail function. (Note apache mail which depends on the java mail.) Tes

  • javaMail send and receive mail 2010-10-26

    javaMail send and receive e-mail program, tested it, no problem, huh, huh!! I tested the mail is 163 (NetEase), other mailboxes do not test, huh, huh!!

  • [Android Development] android, how to send and receive mail? 2010-11-29

    [Android Development] android, how to send and receive mail? More in http://360and.javaeye.com

  • Steps to send and receive mail JavaMail 2011-04-22

    First, send e-mail 1) Get Session i) implement a subclass of Authentication, the implementation of which the public PasswordAuthentication getPasswordAuthentication () method ii) New instance of a class above, set the user name and password iii) New