Javamail extract body part

Hello All,
I am new to javamail api.
The problems, i am encountering are outlined below.
1- First problem which i am encountering is, when i extract the body out of the email, it contains different html tags as well. How can i get rid of these
html tags?
2- Lets say, in my test Gmail account, i had three test emails. Once i read the email body of all three messages and try to
re-run my application, it says, there are no emails in the Gmail inbox. I am unable to understand this concept, so please
help me.
3- Thirdly the disposition is always returned as null, in every case. Why is that?
My code is given below.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import com.datel.email.constants.EmailConstants;
import com.oreilly.networking.javamail.model.EmailBean;
import com.oreilly.networking.javamail.model.ReceiverInformation;
import com.oreilly.networking.javamail.model.SenderInformation;
public class DatelEmailClient {
     public static void main(String[] args) throws MessagingException, IOException {
          DatelEmailClient emailClient = new DatelEmailClient();
          Folder inbox = emailClient.getEmailFolder();
          Message[] messages = emailClient.getMessages(inbox);
          emailClient.readMessageContent(messages);
     public Folder getEmailFolder() throws MessagingException{
          Properties prop = new Properties();
prop.setProperty(EmailConstants.IMAP_SOCKET_FACTORY_KEY, EmailConstants.IMAP_SOCKET_FACTORY_VALUE);
prop.setProperty(EmailConstants.IMAP_SOCKET_FACTORY_FALLBACK_KEY, EmailConstants.IMAP_SOCKET_FACTORY_FALLBACK_VALUE);
prop.setProperty(EmailConstants.IMAP_PORT_KEY, EmailConstants.IMAP_PORT_VALUE);
prop.setProperty(EmailConstants.IMAP_SOCKET_FACTORY_PORT_KEY, EmailConstants.IMAP_SOCKET_FACTORY_PORT_VALUE);
prop.put(EmailConstants.IMAP_HOST_KEY, EmailConstants.IMAP_HOST_VALUE);
prop.put(EmailConstants.IMAP_PROTOCOL_KEY, EmailConstants.IMAP_PROTOCOL_VALUE);
prop.put("mail.debug", "true");
Session session = Session.getDefaultInstance(prop);
Store store = session.getStore();
System.out.println("Connecting...");
store.connect(EmailConstants.IMAP_HOST_VALUE, EmailConstants.USER_NAME, EmailConstants.PASSWORD);
System.out.println("Connected...");
Folder inbox = store.getDefaultFolder().getFolder("INBOX");
return inbox;
     public Message[] getMessages(Folder inbox) throws MessagingException{
          inbox.open(Folder.READ_WRITE);
          Message[] msg = inbox.getMessages();
          return msg;
     public void readMessageContent(Message[] message) throws MessagingException, IOException{
          BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
          SenderInformation sender = new SenderInformation();
ReceiverInformation receiver = new ReceiverInformation();
EmailBean emailBean= new EmailBean();
          if(message != null){
               for(int i = 0; i < message.length; i++){
                    System.out.println("Subject: " + message.getSubject());
                    //Reading Email Message Flags
                    Flags flags2 = message[i].getFlags();
                    if (flags2.contains(Flags.Flag.ANSWERED)) {
                         System.out.println("ANSWERED message");
                    if (flags2.contains(Flags.Flag.DELETED)) {
                         System.out.println("DELETED message");
                    if (flags2.contains(Flags.Flag.DRAFT)) {
                         System.out.println("DRAFT message");
                    if (flags2.contains(Flags.Flag.FLAGGED)) {
                         System.out.println("FLAGGED message");
                    if (flags2.contains(Flags.Flag.RECENT)) {
                         System.out.println("RECENT message");
                    if (flags2.contains(Flags.Flag.SEEN)) {
                         System.out.println("SEEN message");
                    if (flags2.contains(Flags.Flag.USER)) {
                         System.out.println("USER message");
                    * Handling body of the message
                    Object object = message[i].getContent();
                    if(object instanceof Multipart){
                         Multipart multipart = (Multipart) object;
                         processMultipart(multipart);
                    System.out.println("Read message? [Y to read / N to end]");
     String line = reader.readLine();
     if ("Y".equalsIgnoreCase(line)) {
                         System.out.println("****************************");
                    else if ("N".equalsIgnoreCase(line)) {
                         break;
                    else {
          }//for ends here
     }//If ends here
}//readMessageContent ends here
     public void processMultipart(Multipart multiPart) throws MessagingException, IOException{
          System.out.println("Number of parts of Body: " + multiPart.getCount());
          System.out.println("Content type of MultiPart is: "+multiPart.getContentType());
          for(int i =0 ; i < multiPart.getCount(); i++){
               processPart(multiPart.getBodyPart(i));
     }//processMultiPart ends here
     * @throws MessagingException
     * @throws IOException
     public void processPart(Part part) throws MessagingException, IOException{
          String contentType = part.getContentType();
          System.out.println("Content-Type: " + part.getContentType());
          if (contentType.toLowerCase( ).startsWith("multipart/")) {
               System.out.println("Calling multipart from processPart..");
               processMultipart((Multipart) part.getContent( ) );
          InputStream io = part.getInputStream();
          for(int i= 0;i < io.available(); i++)
               System.out.println("I am reading email body..Y");
               System.out.print((char)io.read());
               //buf.append((char) io.read());
               //String output = (char) io.read();
}//main ends here
My constant file is given below
package com.datel.email.constants;
public class EmailConstants {
     public static final String IMAP_SOCKET_FACTORY_KEY="mail.imap.socketFactory.class";
     public static final String IMAP_SOCKET_FACTORY_VALUE="javax.net.ssl.SSLSocketFactory";
     public static final String IMAP_SOCKET_FACTORY_FALLBACK_KEY="mail.imap.socketFactory.fallback";
     public static final String IMAP_SOCKET_FACTORY_FALLBACK_VALUE="false";
     public static final String IMAP_PORT_KEY="mail.imap.port";
     public static final String IMAP_PORT_VALUE="993";
     public static final String IMAP_SOCKET_FACTORY_PORT_KEY="mail.imap.socketFactory.port";
     public static final String IMAP_SOCKET_FACTORY_PORT_VALUE="993";
     public static final String IMAP_HOST_KEY="mail.imap.host";
     public static final String IMAP_HOST_VALUE="imap.gmail.com";
     public static final String IMAP_PROTOCOL_KEY="mail.store.protocol";
     public static final String IMAP_PROTOCOL_VALUE="imap";
     public static final String USER_NAME="[email protected]";
     public static final String PASSWORD="xxxxx";
Please help me out in the above mentioned queries.
Thanks,
Ben

1- First problem which i am encountering is, when i extract the body out of the email, it contains different html tags as well. How can i get rid of these
html tags?By processing the string to remove the tags. If you don't want to have to parse the html yourself,
you can search the web for one of the many html parsing Java libraries. (This isn't really a JavaMail problem.)
2- Lets say, in my test Gmail account, i had three test emails. Once i read the email body of all three messages and try to
re-run my application, it says, there are no emails in the Gmail inbox. I am unable to understand this concept, so please
help me.IMAP or POP3? What are your Gmail settings? Did you read the JavaMail FAQ about connecting to Gmail?
3- Thirdly the disposition is always returned as null, in every case. Why is that?The disposition is optional, so perhaps the sender didn't include it. Or perhaps the server isn't properly
reporting it to the client. Post the protocol trace when accessing a message with no disposition and
post the corresponding MIME content of the message.

Similar Messages

  • POP3 adapter - Extracting body part

    Hi,
    I am using POP3 adapter, where I need to extract the body of the mail. and then I need to create xml message keeping this body as one of the fields description.
    I am doing this in custom pipeline component. I have working code to create the message, but I am not able extract the body part.
    Issue: The email message processing through pipeline, but resulting in empty message output.
    I tried keeping break point @ disassemble stage, but control not hitting my code. 
    I am using below code in disassemble stage to get the body part.
     IBaseMessagePart currentPart = pInMsg.GetPartByIndex(0, out partName);
                        Stream currentPartStream = currentPart.GetOriginalDataStream();
                        var ms = new MemoryStream();
                        IBaseMessage outMsg;
                        outMsg = pc.GetMessageFactory().CreateMessage();
                        outMsg.AddPart("Body", pc.GetMessageFactory().CreateMessagePart(), true);
                        outMsg.Context = pInMsg.Context;
    below is the adapter config
    Please let me know if any other configurations needs to be done in order to extract the body part
    Thanks in advance.

    Hi,
    I am able to debug the code.
    In the below code 
    currentPartStream.CopyTo(ms); is not working in .Net 3.5, how can I replace this code to extract the body part. please help.
    CopyTo method works in .net 4.0 and above
    public void Disassemble(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage
    inmsg)
                var partName = string.Empty;
                // we start from index 1 because index zero contains the body of the message
                // which we are not interested
                for (int i = 1; i < inmsg.PartCount;
    i++)
                    IBaseMessagePart currentPart = inmsg.GetPartByIndex(i, out partName);
                    Stream currentPartStream = currentPart.GetOriginalDataStream();
                    var ms = new MemoryStream();
                    IBaseMessage outMsg;
                    outMsg = pc.GetMessageFactory().CreateMessage();
                    outMsg.AddPart("Body",
    pc.GetMessageFactory().CreateMessagePart(), true);
                    outMsg.Context = inmsg.Context;
                    currentPartStream.CopyTo(ms);
                    string attachmentContent = Encoding.UTF8.GetString(ms.ToArray());
                    MemoryStream attachmentStream = new System.IO.MemoryStream(
                    System.Text.Encoding.UTF8.GetBytes(attachmentContent));
                    outMsg.GetPart("Body").Data
    = attachmentStream;
                    outMsg.Context.Write("ReceivedFileName","http://schemas.microsoft.com/BizTalk/2003/file-properties  ",
    partName);
                    _msgs.Enqueue(outMsg);

  • Cannot Read Body Parts for certain messages on IMAP Server

    Hi There
    I get the following exception on some (not all) messages when trying to extract and save body parts from an email message on the IMAP server. I can iterate through all the body parts, get the filenames, etc. but when I try to read them I get the following error. Any ideas?
    It is MS Exchange (not sure what version) and seems to happen more when there are multiple file attachments or embedded images. We also have a POP3 option and this seems to work fine, only fails when using IMAP...
    java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
    DataHandler dh = bodyPart.getDataHandler();
    dh.writeTo(baos); // <=== Exception here
    TYPE=TEXT/PLAIN; name="New Text Document.txt"/Disposition=attachment
    java.lang.NullPointerException
         at com.sun.mail.iap.Response.parse(Response.java:130)
         at com.sun.mail.iap.Response.<init>(Response.java:87)
          at com.sun.mail.imap.protocol.IMAPResponse.<init>(IMAPResponse.java:48)
         at com.sun.mail.imap.protocol.IMAPResponse.readResponse(IMAPResponse.java:122)
         at com.sun.mail.imap.protocol.IMAPProtocol.readResponse(IMAPProtocol.java:230)
         at com.sun.mail.iap.Protocol.command(Protocol.java:263)
         at com.sun.mail.imap.protocol.IMAPProtocol.fetch(IMAPProtocol.java:1234)
         at com.sun.mail.imap.protocol.IMAPProtocol.fetch(IMAPProtocol.java:1226)
         at com.sun.mail.imap.protocol.IMAPProtocol.fetchBody(IMAPProtocol.java:994)
         at com.sun.mail.imap.protocol.IMAPProtocol.fetchBody(IMAPProtocol.java:983)
         at com.sun.mail.imap.IMAPBodyPart.getContentStream(IMAPBodyPart.java:169)
         at javax.mail.internet.MimePartDataSource.getInputStream(MimePartDataSource.java:94)
         at javax.activation.DataHandler.writeTo(DataHandler.java:297)
         at com.workpool.interactionservices.EmailMessageUtils.saveBodyPartToFile(EmailMessageUtils.java:250)
         at com.workpool.interactionservices.EmailMessageMimeConvertor.processBodyPart(EmailMessageMimeConvertor.java:305)

    I presume the work around you refer to is to make a copy
    of the message? That's all I could find in the FAQ under
    IMAP. I'll try that.
    Unfortunately the server is sitting with a client on their LAN
    and we don't have remote access for debugging. We don't
    currently have a way to easily enable debugging for testing.
    Getting access for testing can take a few days ... but I shall
    do this if the work around does not work.

  • How can I set body part with byte[]?

    Dear all,
    I stored image in database (BLOB TYPE).
    And I need to send it via e-mail, Can JavaMail set a body part with byte[] that I get it from my database?
    If it can be done, how to do that?

    ...I just wonder if the other receive your mail, they cannot know what the mail exactly for....
    you should-
    1. get the BLOB from database
    2. change it to a image file
    3. add the file as attachment of your mail with valid content type and Content-Transfer-Encoding

  • Displaying fields in the body part

    I have a feeling this is something that should be chrystal clear, but the only record information I'm able to view in Browse mode are the fields that are in the header. I can't get anything in the body part to display. Searched through help but can find any reference to what it is my little pea brain is not getting...
    Any help, I hope? Thx...
    powerbook G4   Mac OS X (10.4.4)  

    I wonder if you are confused about which section the body is: In Layout mode, the body is the part above the horizontal line labelled "body", not below it.
    That line limits the size of the body area. Anything below it will not be displayed in browse mode.

  • CLIENT_HOST the (body part) to be multi line

    Dear All,
    Am using Oracle Developer Suite 10g "Form Builder"
    I am using the following Code:
    CLIENT_HOST('rundll32.exe url.dll, FileProtocolHandler "mailto:xx.xx@com?subject=mysubject&body=mybody"');
    I need the (body part) to be multi line
    Example:
    -- Start example --
    Dear Sir,
    Kindly find the following number ----- for your information
    Best Regards
    -- End example --
    Can anyone help me
    Best Regards
    Adel Hafez

    Have you tried creating a variable for the body and using chr(10) or chr(13) to do the multiline?.
    i.e.
    vc_body :=
    "Dear Sir," || chr(10) ||
    "Kindly find the following number" ||chr(10) ||
    "--------------------------------------------------------------------------------" || chr(10) ||
    " for your information" || chr(10)
    "Best Regards" ;
    Then in your client_host you just concatenate the variable.
    CLIENT_HOST('rundll32.exe url.dll, FileProtocolHandler "mailto:xx.xx@com?subject=mysubject&body=" || vc_body);
    Edited by: Rodolfo Ferrari on Jun 17, 2009 4:00 PM

  • Extracting second  part of string

    hi
    i have a string like abcd~12341sdfs
    I have to extract the string after ~ symbol
    Please let me know how ot do it

    Your same question from last week Extracting a part of Strng.

  • How to use the image manipulation palette to extract a part of an image

    How to use the image manipulation palette to extract a part of an image?I have a parent image from which i need to extract a certain sub part.can somebody pls help me on how to use this particular tool?
    Thanks

    Use the above snippet. You might need to convert the Image Type you are using with picture functions. The above snippet will give you good idea on how to achieve what you intend to.
    -FraggerFox!
    Certified LabVIEW Architect, Certified TestStand Developer
    "What you think today is what you live tomorrow"

  • Access body part of any keynote slide using Applescript

    Hi,
    Is there any way I can access body part of Keynote slide?
    I tried with this code but it doesn't work..
    tell application "Keynote"
    tell slideshow 1
    set slidebody to "Apple"
    set body of slide 1 to slidebody
    -- Title works perfactly
    set slideTitle to "Computer"
    set title of slide 1 to slideTitle
    end tell
    end tell
    Any help will be appreciated.
    Thanks,
    Rohit

    You should try the discussion that covers Apple script:    Apple Technologies

  • Extract a part from a txt file

    Hi, I've a simple problem which unfortunately can not solve.
    I have some txt's that I want only to extract a part o them. (The first 100 characters). Here is my code:
    import java.io.*;
    public class ReadSource {
         public static void main(String[] arguments) {
            try {
              FileReader file = new FileReader("1.txt");
              BufferedReader buff = new BufferedReader(file);
               boolean eof = false;
               while (!eof) {
                    String line = buff.readLine();
                    if (line == null)
                        eof = true;
                     else{
                     int start = line.indexOf("something");
                     int end = line.indexOf("something_else");
                     String str2 = line.substring(start, end);
                      System.out.println(str2);
                buff.close();
            } catch (IOException e) {
                System.out.println("Error -- " + e.toString());
    }and the error tha java displays is:
    java.lang.StringIndexOutOfBoundsException: String index out of range: -1
         at java.lang.String.substring(String.java:1438)
         at ReadSource.main(ReadSource.java:21)
    Exception in thread "main"

    Tim I'm very sorry but is still don't work. It still display the same error.
    Look at my code
    import java.io.*;
    public class ReadSource {
         public static void main(String[] arguments) {
           try {
                   BufferedReader reader = new BufferedReader(new FileReader("1.txt"));
                   BufferedWriter writer = new BufferedWriter(new StringWriter());
                   String line = null;
                   while ((line = reader.readLine()) != null) {
                       writer.write(line);
                       writer.newLine();
                   String content = writer.toString();
                   // Now you have the whole file content into the content String
                   int start = content.indexOf("smth");
                   int end = content.indexOf("smth2");
                   String str2 = content.substring(start,end);
                   System.out.println("start = "+start+", end = "+end);
                   System.out.println(str2);
               reader.close();
         }catch (IOException e) {
                System.out.println("Error -- " + e.toString());
    }It looks very logical, I don't know what happens
    Thank you very much for your help.
    Kostas

  • How to place a html page into body part of mail?

    Hi,
    I want to place a html page into body part of any mail.How can i do this?
    Thanks...

    just set ur message type to text/html and put ur whole html string into the body will do...

  • How Can I extract each part of a string ??

    Dear Sir:
    I have a string like following to connect to Oracle Database:
    JDBC_URL= jdbc:oracle:thin:@localhost:1521:ABChere,
    I have Variables like:
    driverClass="";
    Hostname = "";
    port = "";
    SID="";
    etc
    I try to extract each part from this JDBC_URL,
    then assign them to following variable separately:
    driverClass="jdbc:oracle:thin";
    Hostname = "localhost";
    port = "1521";
    SID="ABC";
    Can some guru help give some good example and show how to do it??
    Thanks and have a nice weekends.

    try using a regular expression (regex).
    here, i am going to try to freeball it:
    // JDBC_URL= jdbc:oracle:thin:@localhost:1521:ABC
    Pattern p = Pattern.compile("(JDBC_URL)(\\s*)(=)(\\s*)(.*?:.*?:.*?)(:)(@)(.*?)(:)(.*?)(:)(.*?)")
    Matcher m = p.matcher(text)
    if(m.matches()) or if(m.lookingAt()){
    String driverclass = m.group(5);
    String hostname = m.group(8);
    ...group(10);
    ...group(12);
    }note that (\\s*) means "any amount of whitespace" and (.*?) means "any amount of any character (reluctantly)".
    i used that because i dont know the constraints on those values. for only numbers you can use (\\d+) etc
    [http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html|http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html]
    also, i put everything into ( ) - which is called a capture group - but that was just to make it clearer. in your final regex you may get
    rid of most of those.

  • How to extract local part from email address

    Hello, dear Colleagues.
    Please, help to extract local part from email address.
    Input string: "From: [email protected]"
    Need to get output string between "space" and "@": "C.Norris"
    Thanks.

    Thanks you, mjolinor.
    It works. 
    Could you show me please how to do the same with regular expression?
    Using -replace:
    $InputString = "From: [email protected]"
    $InputString -replace 'From: (.+?)@.+','$1'
    C.Norris
    Using -match:
    $InputString -match 'From: (.+?)@.+' > $null
    $Matches[1]
    C.Norris
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • Apply color in send mail body part

    Hi SAP Gurs,
    I am creating program for sending mail to user.. in that mail i so many header and line item are there, i want to apply color or bold, italic format in body part.... so its look like seprate in body part
    So is there any possibilty to apply color or bold words in mail body part?
    Please help me......
    Thanks zeni

    You can use the HTML text in the Message body part to get the Colors, Bold, Italics like effect in the mail.
    Please refer my answer in this post.
    formating possible in sending mail program
    Regards,
    Naimesh Patel

  • How to extract multiple parts of a .rar file

    How would I extract files like this

    Usually you just click on the first one and the different parts take care of themselves.
    Try UnRarX - Mac OS X RAR Extraction Utility

Maybe you are looking for

  • Xerox MFP 6110 scanning

    Hi I recently installed the Xerox MFP 6110 multifunctional in my network, by plugging it in in the ethernet port of Airport Extreme. Bonjour printing works perfectly, but how can I scan with this machine over the network (not through USB). Pinging be

  • Editing particular pattern in an input text in ADF

    Hi, I have a requirement in ADF like the user should be able to editable only a particular pattern. Example: Name: Chandramohan Hobbies: My hobbies are {}, {}, {} In the above hobbies filed( say textarea or input text), the user should be able to rep

  • Invoice by IDOC

    Hi All, I am using standard IDOC (Process Code SD08/SD09) which uses FM IDOC_INPUT_INVOIC_MRM to post the incoming invoice against a STO. This FM however, posts the entire price on th GR/IR account and does not recognize purchase price variance. We n

  • Find links to reinstall photo shop and Elements 12

    my computer crashed and need to reload elements and photoshop12 . I have the serial  numbers can you help with the link?

  • Part of my text is missing in FF and IE..What to do?

    This is the first time I have used Edge Animate....Seems pretty simple so far...I am finding it pretty simple so far. I have created a simple line of text that fades in from left to right. In chrome, the HTML file looks great. I FF and IE, the last p