GetDisposition

I have been using a simple Java Mail program to read an incoming mail and if the mail has an attachment save the attachment as a file. Here is a part of the code:
String fileName = p.getFileName();
String disposition = p.getDisposition();
String contentType = p.getContentType();
System.out.println("File Name is:" + fileName );
System.out.println("Dispostion is:" + disposition );
System.out.println("Content type is:" + contentType );
//Check if fileName exists and disposition=ATTACHMENT
if (fileName != null && Part.ATTACHMENT.equalsIgnoreCase(disposition))
//Create a New File Object
System.out.println("Building Output File");
File f = new File(fileName); //
// find a version that does not yet exist
for (int i = 1; f.exists(); i++)
String newName = fileName + " " + i;
f = new File(newName);
The above code has been working fine for the last couple of years. However lately the getDisposition is returning null in some scenarios even though there is an attacment. See below for part of the output.
I noticed that when the charset is "utf-8" disposition=null and when charset ="us-ascii" dispostion is:attachment.
Multipart Message
File Name is:null
Dispostion is:null
Content type is:text/plain;^M
charset="us-ascii"
File Name is:vsr_0000378445_20080516_0842.htm
Dispostion is:attachment
Content type is:application/octet-stream;^M
name="vsr_0000378445_20080516_0842.htm"
Building Output File
File Created
Multipart Message
File Name is:null
Dispostion is:null
Content type is:text/plain;^M
charset="utf-8"
File Name is:vsr_0000378471_20080516_1244.htm
Dispostion is:null
Content type is:application/octet-stream;^M
name="vsr_0000378471_20080516_1244.htm"
Hopefully someone has encountered this problem before.
Thanks in advance for your help.
Regards,
SK

Thanks for your response again.
I do understand the logic of my program, but I guess I am puzzled at the inconsistency of how it behaves. My program is pretty static and has been working for years. I wanted to make sure that all my loose ends are tied before I go to the mailer.
Also the mail.jar and activation.jar files I have been using are very old(2004). Do you think getting the latest version will help?
Again I understand the fact that the program will only process what it gets, but i expect Javamail API to be smarter, especially when sendmail is doing the same without a problem.
SK

Similar Messages

  • Problem about  getDisposition()

    Hi guys:
    I encountered a problem in the development process. I sned a mail with attachement file to my mailbox and use JavaMail to receive the mail. I use getDiposition() to check whether the mail has attachement files. Even the mail has it, everytime, the method will return NULL. The following is the header info of the mail:
    This is a multi-part message in MIME format.
    --------------070404050408020008050203
    Content-Type: text/plain; charset=GB2312
    Content-Transfer-Encoding: 7bit
    asdasdasdas
    --------------070404050408020008050203
    Content-Type: image/gif;
    name="test.gif"
    Content-Transfer-Encoding: base64
    Content-Disposition: inline;
    filename="test.gif"
    As you can see, here is [Content-Disposition: inline; filename="test.gif"]. However, the return value of getDiposition() is always NULL....
    Any comments? Any Idea?
    Many thanks!!!!
    Nick

    Here is the code:
    import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    public class RMail {
         private Properties props;
         private Session session;
         private Store store;
         private Folder folder;
         private Message msg;
         private StringBuffer content= new StringBuffer();
         public RMail()
              props=System.getProperties();
              props.put("mail.imap.auth.plain.disable","true");
              session=Session.getDefaultInstance(props, null);
              session.setDebug(true);
         public void setHost(String HostName)
              props.put("mail.host", HostName);
         public boolean getFolder(String protocol, String user, String password)
              try
                   store=session.getStore("imap");
                   store.connect("imap.qq.com","[email protected]","nicksun860204");
                   folder=store.getFolder("INBOX");
                   folder.open(folder.READ_ONLY);
                   msg = (MimeMessage)folder.getMessage(9);
                   MimeMultipart mp =(MimeMultipart)msg.getContent();
                   int k =0;
                   int number_2 = mp.getCount();
                   System.out.println(number_2);
                   for(;k<number_2;k++)
                        MimeBodyPart mbp = (MimeBodyPart)mp.getBodyPart(k);
                        ProcessMailContent(mbp);
                        String disp = mbp.getDisposition();
                        System.out.println(disp);
                        return true;
              catch (Exception e)
                   e.printStackTrace();
                   return false;
         public void ProcessMailContent(MimeBodyPart mbp)
              try{
                   String contentType = mbp.getContentType().toLowerCase();
                   System.out.println(contentType);
                   if(contentType.startsWith("text"))
                        content.append((String)mbp.getContent());
                   else if(contentType.startsWith("multipart"))
                        MimeMultipart mp_nest= (MimeMultipart)mbp.getContent();
                        int flag = mp_nest.getCount();
                        int m;
                        for(m=0;m<flag;m++)
                             MimeBodyPart mbp_nest =(MimeBodyPart)mp_nest.getBodyPart(m);
                             ProcessMailContent(mbp_nest);
                   else
                   MimeMultipart mp_nest = (MimeMultipart)mbp.getContent();
                        int flag = mp_nest.getCount();
                        int m;
                        for(m=0;m<flag;m++)
                             MimeBodyPart mbp_nest =(MimeBodyPart)mp_nest.getBodyPart(m);
                             String disp = mbp_nest.getDisposition();
                             disp.equals(Part.ATTACHMENT);
                             System.out.println(disp);
              catch (Exception e)
                   e.printStackTrace();
    }

  • Error in cast to MULTIPART

    Hi, I test the follow Jguru tutorial code for getting atacchements
    Multipart multipart = (Multipart)message.getContent();
    for (int i=0, n=multipart.getCount(); i<n; i++) {
    Part part = multipart.getBodyPart(i));
    String disposition = part.getDisposition();
    if ((disposition != null) &&
    ((disposition.equals(Part.ATTACHMENT) ||
    (disposition.equals(Part.INLINE))) {
    saveFile(part.getFileName(), part.getInputStream());
    But i have a problem of cast in this line
    Multipart mp = (Multipart)message.getContent();
    the error of CastClass is:
    java.lang.String cannot be cast to javax.mail.Multipart
    why????? Please help me
    Thanks

    Most likely you don't have a multipart message. See the msgshow.java
    demo program that comes with JavaMail.

  • How to get All Mails from outlook

    Hi am reading mail from outlook.. It reads only unread mails. But i want to read all mails. if any one knows please help me..My code is..
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    import java.io.*;
    public class AllPartsClient {
      public static void main(String[] args) {
    Properties props = new Properties();
        String host = "myhost";
        String username = "myuser";
        String password = "mypass";
        String provider = "pop3";
        try {
          Session session = Session.getDefaultInstance(props, null);
          // Connect to the server and open the folder
          Store store = session.getStore(provider);
          store.connect(host, username, password);
          Folder folder = store.getFolder("INBOX");
          if (folder == null) {
            System.out.println("Folder " + folder.getFullName() + " not found.");
            System.exit(1);
        folder.open(Folder.READ_ONLY);
          // Get the messages from the server
          Message[] messages = folder.getMessages();
          for (int i = 0; i < messages.length; i++) {
            System.out.println("------------ Message " + (i+1)
             + " ------------");
            // Print message headers
            Enumeration headers = messages.getAllHeaders();
    while (headers.hasMoreElements()) {
    Header h = (Header) headers.nextElement();
    System.out.println(h.getName() + ": " + h.getValue());
    System.out.println();
    // Enumerate parts
    Object body = messages[i].getContent();
    if (body instanceof Multipart) {
    processMultipart((Multipart) body);
    else { // ordinary message
    processPart(messages[i]);
    System.out.println();
    // Close the connection
    // but don't remove the messages from the server
    folder.close(true);
    catch (Exception e) {
    e.printStackTrace();
    // Since we may have brought up a GUI to authenticate,
    // we can't rely on returning from main() to exit
    System.exit(0);
    public static void processMultipart(Multipart mp)
    throws MessagingException {
    System.out.println("mp.getCount() = "+mp.getCount());
    for (int i = 0; i < mp.getCount(); i++) {
    processPart(mp.getBodyPart(i));
    public static void processPart(Part p) {
    try {
    String fileName = p.getFileName();
    String disposition = p.getDisposition();
    String contentType = p.getContentType();
    if (fileName == null && (Part.ATTACHMENT.equals(disposition)
    || !contentType.equalsIgnoreCase("text/plain"))) {
    // pick a random file name. This requires Java 1.2 or later.
    fileName = File.createTempFile("attachment", ".txt").getName();
    if (fileName == null) { // likely inline
    p.writeTo(System.out);
    else {
    File f = new File(fileName);
    // find a version that does not yet exist
    for (int i = 1; f.exists(); i++) {
    String newName = fileName + " " + i;
    f = new File(newName);
    FileOutputStream out = new FileOutputStream(f);
    // We can't just use p.writeTo() here because it doesn't
    // decode the attachment. Instead we copy the input stream
    // onto the output stream which does automatically decode
    // Base-64, quoted printable, and a variety of other formats.
    InputStream in = new BufferedInputStream(p.getInputStream());
    int b;
    while ((b = in.read()) != -1) out.write(b);
    out.flush();
    out.close();
    in.close();
    catch (Exception e) {
    System.err.println(e);
    e.printStackTrace();
    In this code if Content is Multipart then it is not displaying content..
    Thanks

    Hi
    if i use String provider = "imap"; then it shows the following error message..
    javax.mail.MessagingException: Connection refused: connect
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:479)
    at javax.mail.Service.connect(Service.java:275)
    at javax.mail.Service.connect(Service.java:156)
    at javamail.AllPartsClient.main(AllPartsClient.java:39)
    Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:364)
    at java.net.Socket.connect(Socket.java:507)
    at java.net.Socket.connect(Socket.java:457)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.iap.Protocol.<init>(Protocol.java:84)
    at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:87)
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:446)
    ... 3 more
    pls any one give idea

  • Getting javax.mail.AuthenticationFailedException: EOF on socket. Need Help

    I am trying to get hotmail emails and store in Oracle 10g database.
    When I am executing receivemail procedure from Oracle 10g database. I am getting following error.
    connect to ESIMSCO_UTIL_OWNER
    SQL> set serveroutput on
    SQL>
    SQL> Declare
    2 v_error_msg varchar2(10000);
    3 Begin
    4 v_error_msg:=receivemail('pop3.live.com', '<My email address>@hotmail.com', '<My email password>');
    5 dbms_output.put_line(v_error_msg);
    6 End;
    7 /
    javax.mail.AuthenticationFailedException: EOF on socket
    PL/SQL procedure successfully completed.
    SQL>
    I did following steps, but still I am getting this error. Can somebady help me to solve this problem.
    connect sys/<password>@esimsco as sysdba
    connect to sys
    SQL*Plus: Release 10.2.0.1.0 - Production on Wed May 30 16:02:04 2012
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    SQL> begin
    1 dbms_java.grant_permission( 'ESIMSCO_UTIL_OWNER', 'SYS:java.util.PropertyPermission', '*', 'read,write' );
    2 commit;
    3 end;
    4 /
    PL/SQL procedure successfully completed.
    SQL> begin
    2 dbms_java.grant_permission(
    3 grantee => 'ESIMSCO_UTIL_OWNER',
    4 permission_type => 'SYS:java.net.SocketPermission',
    5 permission_name => '*',
    6 permission_action => 'connect,resolve'
    7 );
    8 end;
    9 /
    PL/SQL procedure successfully completed.
    SQL> begin
    2 dbms_java.grant_permission(
    3 grantee => 'ESIMSCO_UTIL_OWNER',
    4 permission_type => 'SYS:java.util.PropertyPermission',
    5 permission_name => '*',
    6 permission_action => 'read,write'
    7 );
    8 end;
    9 /
    PL/SQL procedure successfully completed.
    SQL> commit;
    Commit complete.
    SQL>
    Then I connect ESIMSCO_UTIL_OWNER.
    connect to ESIMSCO_UTIL_OWNER
    Create 2 tables.
    create table attachment(
    at_file varchar2(500),
    at_mimetype varchar2(500),
    at_attachment blob
    create table email (
    em_incident integer,
    em_from varchar2(1000),
    em_subject varchar2(1000),
    em_body nclob
    Then Create java source named receivemail.
    create or replace and compile java source named receivemail as
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    import java.io.*;
    import java.sql.*;
    import sqlj.runtime.*;
    import oracle.sql.BLOB;
    public class ReceiveMail
    static void getAttachments(Message message, int incidentNo)
    throws MessagingException, IOException, SQLException {
    //String attachments = "";
    Object content = message.getContent();
    if (content instanceof Multipart)
    // -- Multi part message which may contain attachment
    Multipart multipart = (Multipart)message.getContent();
    // -- Loop through all parts of the message
    for (int i=0, n=multipart.getCount(); i<n; i++) {
    Part part = multipart.getBodyPart(i);
    String disposition = part.getDisposition();
    if ((disposition != null) &&(disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
    //-- This part is a file attachment
    String fileName = incidentNo+"_"+part.getFileName().replace(' ','_');
    System.out.println("FILE: " + fileName);
    String contentType = part.getContentType();
    String mimeType = contentType.substring(0,contentType.indexOf(";"));
    System.out.println("FILETYPE: " + mimeType);
    InputStream is = part.getInputStream();
    // -- To work with a BLOB column you have to insert a record
    // -- with an emptly BLOB first.
    #sql { insert into attachment(at_file, at_mimetype, at_attachment)
    values (:fileName, :mimeType, empty_blob()) };
    // -- Retrieve the BLOB
    BLOB attachment = null;
    #sql { select at_attachment into :attachment
    from attachment where at_file = :fileName };
    // -- Fill the BLOB
    OutputStream os = attachment.getBinaryOutputStream();
    int j;
    while ((j = is.read()) != -1) {
    os.write(j);
    is.close();
    os.close();
    // -- Set the BLOB by updating the record
    #sql { update attachment set at_attachment = :attachment
    where at_file = :fileName };
    static String getPlainTextBody(Message message)
    throws MessagingException, IOException
    Object content = message.getContent();
    if (message.isMimeType("text/plain")) {
    // -- Message has plain text body only
    System.out.println("SIMPLE TEXT");
    return (String) content;
    } else if (message.isMimeType("multipart/*")) {
    // -- Message is multipart. Loop through the message parts to retrieve
    // -- the body.
    Multipart mp = (Multipart) message.getContent();
    int numParts = mp.getCount();
    System.out.println("MULTIPART: "+numParts);
    for (int i = 0; i < numParts; ++i) {
    System.out.println("PART: "+mp.getBodyPart(i).getContentType());
    if (mp.getBodyPart(i).isMimeType("text/plain")) {
    // -- Return the plain text body
    return (String) mp.getBodyPart(i).getContent();
    } else if (mp.getBodyPart(i).isMimeType("multipart/*")) {
    // -- Body is also multipart (both plain text and html).
    // -- Loop through the body parts to retrieve plain text part.
    MimeMultipart mmp = (MimeMultipart) mp.getBodyPart(i).getContent();
    int numBodyParts = mmp.getCount();
    System.out.println("MULTIBODYPART: "+numBodyParts);
    for (int j = 0; j < numBodyParts; ++j) {
    System.out.println("BODYPART: "+mmp.getBodyPart(j).getContentType());
    if (mmp.getBodyPart(j).isMimeType("text/plain")) {
    // -- Return the plain text body
    return (String) mmp.getBodyPart(j).getContent();
    return "";
    } else {
    System.out.println("UNKNOWN: "+message.getContentType());
    return "";
    static void saveMessage(Message message)
    throws MessagingException, IOException, SQLException
    //String body = "";
    int incidentNo;
    // -- Get a new incident number
    #sql { select seq_incident.nextval into :incidentNo from dual };
    // -- Get the header information
    String from = ((InternetAddress)message.getFrom()[0]).getAddress();
    System.out.println("FROM: "+ from);
    String subject = message.getSubject();
    System.out.println("SUBJECT: "+subject);
    // -- Retrieve the plain text body
    String body = getPlainTextBody(message);
    // -- Store the message in the email table
    #sql { insert into email (em_incident, em_from, em_subject, em_body)
    values (:incidentNo, :from, :subject, :body) };
    // -- Retrieve the attachments
    getAttachments(message, incidentNo);
    #sql { commit };
    // -- Mark message for deletion
    // message.setFlag(Flags.Flag.DELETED, true);
    public static String Receive(String POP3Server, String usr, String pwd)
    Store store = null;
    Folder folder = null;
    try
    // -- Get hold of the default session --
    Properties props = System.getProperties();
    props.put("mail.pop3.connectiontimeout", "60000");
    Session session = Session.getDefaultInstance(props, null);
    // -- Get hold of a POP3 message store, and connect to it --
    store = session.getStore("pop3");
    store.connect(POP3Server,995, usr, pwd);
    System.out.println("Connected");
    // -- Try to get hold of the default folder --
    folder = store.getDefaultFolder();
    if (folder == null) throw new Exception("No default folder");
    // -- ...and its INBOX --
    folder = folder.getFolder("INBOX");
    if (folder == null) throw new Exception("No POP3 INBOX");
    // -- Open the folder for read_write (to be able to delete message) --
    folder.open(Folder.READ_WRITE);
    // -- Get the message wrappers and process them --
    Message[] msgs = folder.getMessages();
    for (int msgNum = 0; msgNum < msgs.length; msgNum++){
    saveMessage(msgs[msgNum]);
    System.out.println("No more messages");
    return ("SUCCESS");
    catch (Exception ex){
    ex.printStackTrace();
    return ex.toString();
    finally{
    // -- Close down nicely --
    try{
    // close(true), to expunge deleted messages
    if (folder!=null) folder.close(true);
    if (store!=null) store.close();
    catch (Exception ex){
    //ex.printStackTrace();
    return ex.toString();
    Then create function receivemail.
    create or replace function receivemail(pop3_server in string,
    pop3_usr in string,
    pop3_pwd in string)
    return varchar2
    is language java name
    'ReceiveMail.Receive(java.lang.String,
    java.lang.String,
    java.lang.String) return String';
    And then trying to execute function receivemail, but I am getting following error.
    SQL> set serveroutput on
    SQL>
    SQL> Declare
    2 v_error_msg varchar2(10000);
    3 Begin
    4 v_error_msg:=receivemail('pop3.live.com', '<Hotmail email address>@hotmail.com', 'Hotmail password');
    5 dbms_output.put_line(v_error_msg);
    6 End;
    7 /
    javax.mail.AuthenticationFailedException: EOF on socket
    PL/SQL procedure successfully completed.
    SQL>
    I am requesting, please help me to solve this problem.
    I will be very thankful for your kind help and support.
    Amol......
    Edited by: Amol Karyakarte on 31-May-2012 7:27 AM

    Hello,
    I don't think this is the right forum, as this question seems to have nothing to do with the Oracle Forms tool.
    You'd better ask it in the database forum.
    Francois

  • I can't compile the JavaMail demo

    Can somebody please help me out. I am trying to compile one of the demos in JavaMail. It compiles successfully but it won't execute. It keeps giving me the normal exception when there is no 'main()' in a code. The code is below:
    import java.util.*;
    import java.io.*;
    import javax.mail.*;
    import javax.mail.event.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    * Demo app that exercises the Message interfaces.
    * Show information about and contents of messages.
    * @author John Mani
    * @author Bill Shannon
    public class msgshow {
    static String protocol;
    static String host = null;
    static String user = null;
    static String password = null;
    static String mbox = null;
    static String url = null;
    static int port = -1;
    static boolean verbose = false;
    static boolean debug = false;
    static boolean showStructure = false;
    static boolean showMessage = false;
    static boolean showAlert = false;
    static boolean saveAttachments = false;
    static int attnum = 1;
    public static void main(String argv[]) {
         int msgnum = -1;
         int optind;
         InputStream msgStream = System.in;
         for (optind = 0; optind < argv.length; optind++) {
         if (argv[optind].equals("-T")) {
              protocol = argv[++optind];
         } else if (argv[optind].equals("-H")) {
              host = argv[++optind];
         } else if (argv[optind].equals("-U")) {
              user = argv[++optind];
         } else if (argv[optind].equals("-P")) {
              password = argv[++optind];
         } else if (argv[optind].equals("-v")) {
              verbose = true;
         } else if (argv[optind].equals("-D")) {
              debug = true;
         } else if (argv[optind].equals("-f")) {
              mbox = argv[++optind];
         } else if (argv[optind].equals("-L")) {
              url = argv[++optind];
         } else if (argv[optind].equals("-p")) {
              port = Integer.parseInt(argv[++optind]);
         } else if (argv[optind].equals("-s")) {
              showStructure = true;
         } else if (argv[optind].equals("-S")) {
              saveAttachments = true;
         } else if (argv[optind].equals("-m")) {
              showMessage = true;
         } else if (argv[optind].equals("-a")) {
              showAlert = true;
         } else if (argv[optind].equals("--")) {
              optind++;
              break;
         } else if (argv[optind].startsWith("-")) {
              System.out.println(
    "Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
              System.out.println(
    "\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]");
              System.out.println(
    "or msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
              System.exit(1);
         } else {
              break;
    try {
         if (optind < argv.length)
         msgnum = Integer.parseInt(argv[optind]);
         // Get a Properties object
         Properties props = System.getProperties();
         // Get a Session object
         Session session = Session.getInstance(props, null);
         session.setDebug(debug);
         if (showMessage) {
              MimeMessage msg;
              if (mbox != null)
              msg = new MimeMessage(session,
                   new BufferedInputStream(new FileInputStream(mbox)));
              else
              msg = new MimeMessage(session, msgStream);
              dumpPart(msg);
              System.exit(0);
         // Get a Store object
         Store store = null;
         if (url != null) {
              URLName urln = new URLName(url);
              store = session.getStore(urln);
              if (showAlert) {
              store.addStoreListener(new StoreListener() {
                   public void notification(StoreEvent e) {
                   String s;
                   if (e.getMessageType() == StoreEvent.ALERT)
                        s = "ALERT: ";
                   else
                        s = "NOTICE: ";
                   System.out.println(s + e.getMessage());
              store.connect();
         } else {
              if (protocol != null)          
              store = session.getStore(protocol);
              else
              store = session.getStore();
              // Connect
              if (host != null || user != null || password != null)
              store.connect(host, port, user, password);
              else
              store.connect();
         // Open the Folder
         Folder folder = store.getDefaultFolder();
         if (folder == null) {
         System.out.println("No default folder");
         System.exit(1);
         if (mbox == null)
              mbox = "INBOX";
         folder = folder.getFolder(mbox);
         if (folder == null) {
         System.out.println("Invalid folder");
         System.exit(1);
         // try to open read/write and if that fails try read-only
         try {
              folder.open(Folder.READ_WRITE);
         } catch (MessagingException ex) {
              folder.open(Folder.READ_ONLY);
         int totalMessages = folder.getMessageCount();
         if (totalMessages == 0) {
              System.out.println("Empty folder");
              folder.close(false);
              store.close();
              System.exit(1);
         if (verbose) {
              int newMessages = folder.getNewMessageCount();
              System.out.println("Total messages = " + totalMessages);
              System.out.println("New messages = " + newMessages);
              System.out.println("-------------------------------");
         if (msgnum == -1) {
              // Attributes & Flags for all messages ..
              Message[] msgs = folder.getMessages();
              // Use a suitable FetchProfile
              FetchProfile fp = new FetchProfile();
              fp.add(FetchProfile.Item.ENVELOPE);
              fp.add(FetchProfile.Item.FLAGS);
              fp.add("X-Mailer");
              folder.fetch(msgs, fp);
              for (int i = 0; i < msgs.length; i++) {
              System.out.println("--------------------------");
              System.out.println("MESSAGE #" + (i + 1) + ":");
              dumpEnvelope(msgs);
              // dumpPart(msgs[i]);
         } else {
              System.out.println("Getting message number: " + msgnum);
              Message m = null;
              try {
              m = folder.getMessage(msgnum);
              dumpPart(m);
              } catch (IndexOutOfBoundsException iex) {
              System.out.println("Message number out of range");
         folder.close(false);
         store.close();
         } catch (Exception ex) {
         System.out.println("Oops, got exception! " + ex.getMessage());
         ex.printStackTrace();
         System.exit(1);
         System.exit(0);
    public static void dumpPart(Part p) throws Exception {
         if (p instanceof Message)
         dumpEnvelope((Message)p);
         /** Dump input stream ..
         InputStream is = p.getInputStream();
         // If "is" is not already buffered, wrap a BufferedInputStream
         // around it.
         if (!(is instanceof BufferedInputStream))
         is = new BufferedInputStream(is);
         int c;
         while ((c = is.read()) != -1)
         System.out.write(c);
         String ct = p.getContentType();
         try {
         pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
         } catch (ParseException pex) {
         pr("BAD CONTENT-TYPE: " + ct);
         String filename = p.getFileName();
         if (filename != null)
         pr("FILENAME: " + filename);
         * Using isMimeType to determine the content type avoids
         * fetching the actual content data until we need it.
         if (p.isMimeType("text/plain")) {
         pr("This is plain text");
         pr("---------------------------");
         if (!showStructure && !saveAttachments)
              System.out.println((String)p.getContent());
         } else if (p.isMimeType("multipart/*")) {
         pr("This is a Multipart");
         pr("---------------------------");
         Multipart mp = (Multipart)p.getContent();
         level++;
         int count = mp.getCount();
         for (int i = 0; i < count; i++)
              dumpPart(mp.getBodyPart(i));
         level--;
         } else if (p.isMimeType("message/rfc822")) {
         pr("This is a Nested Message");
         pr("---------------------------");
         level++;
         dumpPart((Part)p.getContent());
         level--;
         } else {
         if (!showStructure && !saveAttachments) {
              * If we actually want to see the data, and it's not a
              * MIME type we know, fetch it and check its Java type.
              Object o = p.getContent();
              if (o instanceof String) {
              pr("This is a string");
              pr("---------------------------");
              System.out.println((String)o);
              } else if (o instanceof InputStream) {
              pr("This is just an input stream");
              pr("---------------------------");
              InputStream is = (InputStream)o;
              int c;
              while ((c = is.read()) != -1)
                   System.out.write(c);
              } else {
              pr("This is an unknown type");
              pr("---------------------------");
              pr(o.toString());
         } else {
              // just a separator
              pr("---------------------------");
         * If we're saving attachments, write out anything that
         * looks like an attachment into an appropriately named
         * file. Don't overwrite existing files to prevent
         * mistakes.
         if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
         String disp = p.getDisposition();
         // many mailers don't include a Content-Disposition
         if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
              if (filename == null)
              filename = "Attachment" + attnum++;
              pr("Saving attachment to file " + filename);
              try {
              File f = new File(filename);
              if (f.exists())
                   // XXX - could try a series of names
                   throw new IOException("file exists");
              ((MimeBodyPart)p).saveFile(f);
              } catch (IOException ex) {
              pr("Failed to save attachment: " + ex);
              pr("---------------------------");
    public static void dumpEnvelope(Message m) throws Exception {
         pr("This is the message envelope");
         pr("---------------------------");
         Address[] a;
         // FROM
         if ((a = m.getFrom()) != null) {
         for (int j = 0; j < a.length; j++)
              pr("FROM: " + a[j].toString());
         // TO
         if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
         for (int j = 0; j < a.length; j++) {
              pr("TO: " + a[j].toString());
              InternetAddress ia = (InternetAddress)a[j];
              if (ia.isGroup()) {
              InternetAddress[] aa = ia.getGroup(false);
              for (int k = 0; k < aa.length; k++)
                   pr(" GROUP: " + aa[k].toString());
         // SUBJECT
         pr("SUBJECT: " + m.getSubject());
         // DATE
         Date d = m.getSentDate();
         pr("SendDate: " +
         (d != null ? d.toString() : "UNKNOWN"));
         // FLAGS
         Flags flags = m.getFlags();
         StringBuffer sb = new StringBuffer();
         Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
         boolean first = true;
         for (int i = 0; i < sf.length; i++) {
         String s;
         Flags.Flag f = sf[i];
         if (f == Flags.Flag.ANSWERED)
              s = "\\Answered";
         else if (f == Flags.Flag.DELETED)
              s = "\\Deleted";
         else if (f == Flags.Flag.DRAFT)
              s = "\\Draft";
         else if (f == Flags.Flag.FLAGGED)
              s = "\\Flagged";
         else if (f == Flags.Flag.RECENT)
              s = "\\Recent";
         else if (f == Flags.Flag.SEEN)
              s = "\\Seen";
         else
              continue;     // skip it
         if (first)
              first = false;
         else
              sb.append(' ');
         sb.append(s);
         String[] uf = flags.getUserFlags(); // get the user flag strings
         for (int i = 0; i < uf.length; i++) {
         if (first)
              first = false;
         else
              sb.append(' ');
         sb.append(uf[i]);
         pr("FLAGS: " + sb.toString());
         // X-MAILER
         String[] hdrs = m.getHeader("X-Mailer");
         if (hdrs != null)
         pr("X-Mailer: " + hdrs[0]);
         else
         pr("X-Mailer NOT available");
    static String indentStr = " ";
    static int level = 0;
    * Print a, possibly indented, string.
    public static void pr(String s) {
         if (showStructure)
         System.out.print(indentStr.substring(0, level * 2));
         System.out.println(s);

    Oh, I didn't specify any command line argument. I don't really get what arguments I should specify. Could please explain it to me. My main objective is to learn and be able to apply this to my personal project.
    One more thing if you don't mind. I was very good at java (then I used Jdk 1.2) but I have lost touch due to not using Java for a very long time. I am also learning to Servlets at the moment but I just can't deploy it. In the past we used deploytool and I could get that to work but I just don't get how to deploy the servlet I wrote.
    Thanks ever so much!

  • ParseException Content-Disposition filename spaces

    Hello All,
    I have an email generated from Thunderbird 1.5.0.9 (Windows/20061207) which contains an attachment whose filename has spaces.
    JavaMail (1.4) throws a javax.mail.internet.ParseException on the MimeBodyPart.getDisposition() call:
    javax.mail.internet.ParseException: Expected ';', got "-"
    javax.mail.internet.ParameterList.<init>(ParameterList.java:179)
    javax.mail.internet.ContentDisposition.<init>(ContentDisposition.java:87)
    javax.mail.internet.MimeBodyPart.getDisposition(MimeBodyPart.java:1039)
    javax.mail.internet.MimeBodyPart.getDisposition(MimeBodyPart.java:299) The offending attachment part has a part header which looks like this:
    Content-Disposition: inline;
         filename*0=Test - Test.pdf
    Clearly the parser is failing due to the spaces in the filename. Bugzilla for Thunderbird (Bug 221028 - https://bugzilla.mozilla.org/show_bug.cgi?id=221028) discusses this issue, however the status of the bug is VERIFIED WONTFIX.
    According to the Mozilla discussion, their implementation is conformant to the RFC:
    ...Just two days ago I was talking about this issue in #mozillazine with Christian
    Biesinger and Boris Zbarsky, and they said that this is the proper behaviour
    according to the RFC...
    Whether it IS conformant to all relevant RFCs I don't know, but it seems it won't be changed any time soon.
    This issue also exists for the Content-Type header in the same email which has the same format:
    Content-Type: application/pdf;
         name*0=Test - Test.pdfAnyone know if there is a way I can "safely" parse these headers? Is this a JavaMail bug?
    Thanks

    Absolutely, and please don't take my posting as a complaint - well over 99.9% of our emails are consumed flawlessly. I'm expressing more of (my opinion only) a high-level philosophical argument about of why I think good software (JavaMail) should try to by-default interact with not-so-good software. I'm not basing this not on "technical correctness", but rather the following unfortunate scenario:
    One particular example would be certain products made by a company with the initals "MS". These products almost always hide brokenness (they act as highly liberal consumers). Outlook, Internet Explorer, are the 2 primary examples. So a user (and unfortunately most users have never read or care about an RFC) opens the email with Outlook, or the web page with Explorer, etc. It "works". Now, we programmers certainly know better, but remember that we aren't buying or choosing products or services, we're offering them. User then opens with Java-based product (stack trace). User buys or chooses MS-based product, MS-based product retains market stranglehold, commercial email providers test their products with Outlook, and in the end, brokenness is propagated anyway. It's kind of like reverse-Darwinism for software (survival of the most-broken).
    Some customers complain that JavaMail doesn't strictly enforce every requirement of the standards
    As an SMTP producer, I might see that, but personally I can never recall seeing a single problem with outgoing email from JavaMail. As a client consumer, I'm not sure why they would take that philosophy, unless maybe they are using JavaMail to test RFC-compliance.
    there are forms of brokenness that go beyond what can be handled at the JavaMail API level.
    Of course, but I have yet to see a message that the "MS" client could not read. So perhaps they are working around some of these at a higher level (in the GUI, maybe?)
    But for developers who don't think about this problem...
    Most developers most likely aren't using JavaMail to read in over 25,000 emails a day. So admittedly, I'm in a unique situation.
    Having made that decision it's relatively straightforward to configure JavaMail appropriately. Not really, one change required updating the jar file, others require obscure uses of the API. And a developer/administrator is only going to make those changes after seeing the problem.
    to avoid propagating brokenness as you suggest.
    Brokenness will get propagated anyway (see reverse-Darwinism, or the Theory of De-evolution above).
    I'm looking forward to trying out 1.4.1, and thanks again for all the assistance, a very thorough FAQ, and overall a great API. I think the opensourcing was a good idea, JavaMail really is by far the best API that I have seen for this type of high-volume work.

  • Reading attachments within attachments

    Hi,
    I tested this code that I found and I was wondering if it's possible to read attachments within attachments. We are receiving forwarded messages that have an attachment of type message. The attachment then has its own attachment of type doc. We can break it into 2 parts but we don't know how to break it into 3 parts. I'm sure this sounds confusing so here is the code example:
    Object content = message.getContent();
    if (content instanceof Multipart) {
    handleMultipart((Multipart)content,msgName, mailFr, mailTo);
    } else {
    handlePart(message[i],msgName, mailFr, mailTo);
    public static void handleMultipart(Multipart multipart, String msgName, String mailFr, String mailTo)
    throws MessagingException, IOException {
              for (int i=0, n=multipart.getCount(); i<n; i++) {
                                  handlePart(multipart.getBodyPart(i),msgName, mailFr, mailTo);
    public static void handlePart(Part part, String msgName, String mailFr, String mailTo)
    throws MessagingException, IOException {
    String disposition = part.getDisposition();
    String contentType = part.getContentType();
    if (disposition == null) { if ((contentType.length() >= 10) &&
    (contentType.toLowerCase().substring(
    0, 10).equals("text/plain"))) {
    //part.writeTo(System.out);
    } else {
    //part.writeTo(System.out);
         saveFile(part.getFileName(), part.getInputStream(),msgName, mailFr, mailTo);
    } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
                   saveFile(part.getFileName(), part.getInputStream(),msgName, mailFr, mailTo);
                   System.out.println("This is an attachment");
    } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
                        saveFile(part.getFileName(), part.getInputStream(),msgName, mailFr, mailTo);

    If you have an attachment that's a message, then try to cast it to something of class Message or MimeMessage, then you can get parts from that.

  • How to get the whole attachment as a MimeMessage?

    I'm finding a way to deal with base64 encoded .eml attachment. I need to parse it to MimeMessage for further process
       for (i=0; i<part.getCount(); i++) {
            currentPart = (MimePart) part.getBodyPart(i);
            if ( file extension is .eml ) {
                InputStream input = currentPart.getInputStream();
                currentPart = new MimeMessage(null, input);
            }with the above code, I would only get the decoded body of the email content, all header information are missing.
    From JavaMail API, getInputStream() and writeTo() would only get/write the content part, so I've tried to use:
       for(Enumeration enum = currentPart.getAllHeaderLines(); enum.hasMoreElements();)     {
            currentPart.addHeaderLine((String)enum.nextElement());
       }          I suppose currentPart is a MimeMessage now, but when I try this:
       request.setAttribute("part", (MimeMessage) currentPart.getContent());I would get a ClassCastException
    Would anyone give me some suggestion?

    I am a little unsure as to what exactly you are trying to achieve, but I will assume you are trying to extract the attachment from one message and parse this attachment as a MimeMessage.
    First, the parts in a MimeMessage are grouped in a tree structure so you can't just iterate over the list of parts and expect to get them all, you have to do it recursively.
    eg., (pseudo code only)
    public void getParts(Part p, List parts) {
      if(p.getContent() != null) {
        if(p.getContent() instanceof Multipart) {
          Multipart mp = (Multipart) content;
          for(int i = 0; i < mp.getCount(); i++) {
            getParts(mp.getBodyPart(i), parts);
        else
           parts.add(p);
    // Then call it like:
    List parts = new LinkedList();
    getParts(part, parts);
    // Where "part" is your original messageOnce you have the list of parts, you need to find the attachment. This is done by looking at the "disposition" of the part.
    An attachment will usually (although not always) be of type MimeMessage.INLINE or MimeMessage.ATTACHMENT
    So... iterate though your parts list looking for attachments
    Iterator i = parts.iterator();
    Part p = null;
    MimeMessage attachment = null;
    while(i.hasNext()) {
      p = (Part)i.next();
      // NOTE: p.getDisposition() may be null here
      if(p.getDisposition().equals(MimeMessage.INLINE) || p.getDisposition().equals(MimeMessage.ATTACHMENT)) {
        // You have an attachment
        // Use the data handler to get the stream
        InputStream input= p.getDataHandler().getInputStream();
        // Construct you new MimeMessage
        attachment = new MimeMessage(null, input);
        // Exit the loop
        break;
    }The simplest way to test is you have your attachment is to print it's filename with p.getFileName();
    You can also bypass creating the part list by adding the disposition check to the first getParts method.

  • Problem to get file with special characters in the message

    Hi, I'm developing an application that read the email and save the attached file. However, some files have special characters in the name, like: Documento de EspecificaÇÂO.doc
    I noticed the de name of the file in de message head is:
    "=?iso-8859-1?Q?Documento_de_Especifica=E7=E3o.doc?="
    I'm already using the JavaMil 1.4.5
    Tha is my code:
    package br.com.cesan.helpdesk;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    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 javax.mail.search.FlagTerm;
    public class LerEmail2 {
         * @param args
         * @throws MessagingException
         * @throws IOException
         public static void main(String[] args) throws MessagingException, IOException {
              // TODO Auto-generated method stub
              // Get session
         Session session = Session.getInstance(new Properties(), null);
         // Get the store
         Store store = session.getStore("pop3");
         store.connect("pop.xxxxx.com.br", "user", "password");
         Folder folder = store.getFolder("INBOX");
              //folder.open(Folder.READ_ONLY);
              folder.open(Folder.READ_WRITE);
              // Show only unreaded Messages
              FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
              // Get directory
         Message message[] = folder.getMessages();     
         //Message messages[] = folder.search(ft);
         for (int i=0, n=message.length; i<n; i++) {
              System.out.println(i + " - "+ message.getSubject() +" - " + message[i].getSentDate() );
              Object content = message[i].getContent();
              if (content instanceof Multipart) {
         handleMultipart((Multipart)content);
         } else {
         handlePart(message[i]);
         // Close connection
         folder.close(false);
         store.close();
         public static void handleMultipart(Multipart multipart) throws MessagingException, IOException {
              for (int i=0, n=multipart.getCount(); i<n; i++) {
                   handlePart(multipart.getBodyPart(i));
         public static void handlePart(Part part) throws MessagingException, IOException {
              String disposition = part.getDisposition();
         String contentType = part.getContentType();
         if (disposition == null) { // When just body
              System.out.println("Null: " + contentType);
              // Check if plain
              if ((contentType.length() >= 10) && (contentType.toLowerCase().substring(0, 10).equals("text/plain"))) {
                   part.writeTo(System.out);
              } else { // Don't think this will happen
                   System.out.println("Other body: " + contentType);
                   part.writeTo(System.out);
         } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
              System.out.println("Attachment: " + part.getFileName() + " : " + contentType);
              saveFile(part.getFileName(), part.getInputStream());
         } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
         System.out.println("Inline: " +
         part.getFileName() +
         " : " + contentType);
         saveFile(part.getFileName(), part.getInputStream());
         } else {  // Should never happen
         System.out.println("Other: " + disposition);
         public static void saveFile(String filename, InputStream input) throws IOException {
              if (filename == null) {
                   filename = File.createTempFile("xx", ".out").getName();
              // Do no overwrite existing file
              File file = new File(filename);
              for (int i=0; file.exists(); i++) {
                   file = new File(filename+i);
              System.setProperty("file.encoding", "iso-8859-1");
              FileOutputStream fos = new FileOutputStream(file);
              BufferedOutputStream bos = new BufferedOutputStream(fos);
              BufferedInputStream bis = new BufferedInputStream(input);
              int aByte;
              while ((aByte = bis.read()) != -1) {
                   bos.write(aByte);
              bos.flush();
              bos.close();
              bis.close();
    The problem occurs in:
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    BufferedInputStream bis = new BufferedInputStream(input);
    int aByte;
    while ((aByte = bis.read()) != -1) {
    bos.write(aByte);
    Thanks
    Edited by: user10283976 on 30/03/2012 07:36
    Edited by: user10283976 on 30/03/2012 07:37
    Edited by: user10283976 on 30/03/2012 07:37
    Edited by: user10283976 on 30/03/2012 07:38
    Edited by: user10283976 on 30/03/2012 07:40
    Edited by: user10283976 on 30/03/2012 07:41
    Edited by: user10283976 on 30/03/2012 07:42

    http://www.oracle.com/technetwork/java/javamail/faq/index.html#encodefilename

  • Null Pointer Exception while reading inbox

    Hi Experts
    I am getting the Null Pointer Exception when I execute the following code. Can anybody please suggest where i am going wrong.
      public void readInbox( )
        //@@begin readInbox()
         while (! wdContext.nodeEmail().isEmpty()) {
              wdContext.nodeEmail().removeElement(wdContext.nodeEmail().getElementAt(0) );
         wdContext.nodeEmail().invalidate();   
         Message[] message = new Message[1000];
         IPublicEmailInteractiveFormComp.IEmailElement newEmailNodeElement;
         //Set properties
         // @TODO Enter your email server address here by replacing the text in angle brackets.
         String host = "otemail.otegroup.com";
         // @TODO Enter your email account here by replacing the text in angle brackets.
         String username = "[email protected]";
         // @TODO Enter your email account password here by replacing the text in angle brackets.
         String password = "password";
         Properties props = new Properties();     
         props.put("mail.smtp.host", host);
         //Set Session
         Session session = Session.getInstance(props, null);
         //Set the store
         try {
              Store store = session.getStore("imap");
              store.connect(host,username,password);
              //Get folder
              Folder folder = store.getFolder("INBOX");
              folder.open(Folder.READ_ONLY);
              //Get Mails
              message = folder.getMessages();
              //Fill table with mails
              for (int i = 0; i < message.length; i++)
                   if (message<i>.isSet(Flags.Flag.SEEN) == false)
                        if (message<i>.getSubject().equals("Travel Request Form"))
                             newEmailNodeElement = wdContext.createEmailElement();                 
                             newEmailNodeElement.setFrom(message<i>.getFrom()[0].toString());
                             newEmailNodeElement.setSubject(message<i>.getSubject());
                             newEmailNodeElement.setSentDate(message<i>.getSentDate().toString());
                             //Check for right Attachment
                             Object content = message<i>.getContent();
                             if ( content != null  && content instanceof Multipart)
                                  for (int j = 0 , n = ((Multipart)content).getCount(); j < n; j++)
                                       Part part = ((Multipart)content).getBodyPart(j);
                                       String disposition = part.getDisposition();
                                       if ( disposition != null && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)))
                                            if (part.getFileName().equals("TravelRequest.pdf"))
                                                 newEmailNodeElement.setAttachment(true);
                                                 newEmailNodeElement.setContentType(part.getContentType().toString());
                                                 InputStream is = part.getInputStream();
                                                 ByteArrayOutputStream bo = new ByteArrayOutputStream();                                                                                
                                                 int c;
                                                 while ((c = is.read()) > -1) bo.write(c);
                                                 byte[] pdfSource = bo.toByteArray();
                                                 newEmailNodeElement.setPdfSource(pdfSource);
                                                 break;     
                                            else
                                                 newEmailNodeElement.setAttachment(false);     
                             wdContext.nodeEmail().addElement(newEmailNodeElement);
              //Close connection
              folder.close(true);
              store.close();          
         catch (MessagingException e)
              wdComponentAPI.getMessageManager().reportSuccess(e.getMessage());
              e.printStackTrace();
         catch (IOException e)
              wdComponentAPI.getMessageManager().reportSuccess(e.getMessage());
              e.printStackTrace();
         catch (NullPointerException e)
              wdComponentAPI.getMessageManager().reportSuccess(e.getMessage());
              e.printStackTrace();
        //@@end
    Regards
    Abdullah

    The error was caused when the subject used to return null

  • Problem with attachment saving to db

    Hi,
    I've encountered the following problem when writing a small app. to receive e-mails and subsequently storing them in a database.
      private  void handlePart(Part part) throws IOException, MessagingException {
             String disposition = part.getDisposition();
             if (disposition == null) { //body
                // do something dull
             } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
                  try {
                     saveAttachmentToDB(part.getFileName(), part.getInputStream(), part.getSize());
                 } catch (SQLException e) {
                     System.err.print("SQL Error: ");
                     System.err.println(e.getMessage());
                     System.exit(-1);
             } else if (disposition.equalsIgnoreCase(Part.INLINE) && part.getSize()>9) {
               // do something to store to db 
         }and
    public void saveAttachmentToDB(String filename, InputStream input, int size)
          throws IOException, SQLException {
            PreparedStatement pstmt;
            String Query = "insert Attachment VALUES(?,?)";
            pstmt = con.prepareStatement(Query);
            pstmt.setString(1, filename);
            pstmt.setBinaryStream(2, input, size); //method to insert a stream of bytes
            pstmt.executeUpdate();
          }Now the problem is that upon exection the system hangs on the first insert.
    Probably this is because the size aint right...
    I've tried it using different attachments, like MS Word documents, plain textfiles. Is this the way to do this?
    Or must I use a DataHandler object, but if the latter is true can someone pinpoint me to a good tutorial on datahandlers.
    I rewrote the former code using a part.WriteTo() writing to a ByteArrayOutPutstream --> converting that stream to a ByteArrayInputStream and calling setBinaryStream on that using the size of ByteArrayOutputStream.
    If I did this the system wouldn't hang but it wrote the contentHeader and the body to the database. The body would than be in Base64 format, wich is not what I want... Please can somebody set me on the right track here?
    Grts
    Joer

    Hai I am getting the attachments from the inbox.But I have also need the same to store my attachmnts i db can u explain it or send me the code
    thanks

  • Problem in retrieving email using java mail api

    hi,
    In my project,i am retrieving mails from a particular email id.
    I am able to retrieve the latest mails and save it in a folder in my system.
    The problem is whenever i run the program eventhough the most recently received mail in inbox is retrieved and saved,again it is retrieving the same one and saving it in the same folder(not repeating).
    I tried to check the newmessages in the inbox using the folder.hasNewMessage() method in java mail api,but the method is returning false only regardless new mail is there in inbox or not.
    I want to read the unread messages only.Dont want to retrieve the already read mails.
    I got the mail retrieving code from the below site.(sorry not posting the code because it is so long and having 4 classes)
    http://www.builderau.com.au/program/java/soa/Getting_the_mail_in_receiving_in_JavaMail/0,39024620,39228060,00.htm
    Can anyone tell me how to read unread mails in the inbox?
    Thanks a lot

    hi parvathi
    i think your mail program is receving mails using imap
    the imap is only receve the mail from server but the pop is deleting the mails after receving
    use the following sample code
    package com.sfrc.mail.pop;
    import javax.mail.*;
    import javax.mail.internet.*;
    import com.sun.mail.handlers.message_rfc822;
    import java.util.*;
    import java.io.*;
    * Owner: SFRC IT Solutions Pvt Ltd
    * Author:Arunkumar Subramaniam
    * Date :12-06-2006
    * File Name: AttachRecive.java
    public class AttachRecive
    public static void main(String args[])
    try
    String popServer="192.168.1.1";
    String popUser="pl";
    String popPassword="password";
    // Create empty properties
    Properties props = new Properties();
    // Get session
    Session session = Session.getDefaultInstance(props, null);
    // Get the store
    Store store = session.getStore("pop3");
    store.connect(popServer, popUser, popPassword);
    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);
    // Get directory
    Message message =folder.getMessages();
    Multipart mp = (Multipart)message.getContent();
    for (int i=0, n=mp.getCount(); i<n; i++) {
    Part part = mp.getBodyPart(i);
    String disposition = part.getDisposition();
    // Close connection
    folder.close(false);
    store.close();
    catch (Exception ex)
    System.out.println("Usage: "
    +" popServer popUser popPassword");
    System.exit(0);
    Regards
    Arunkumar Subramaniam
    SFRC IT Solutions Pvt Ltd
    Chennai

  • Help to solve javax.mail.AuthenticationFailedException: EOF on socket

    I am trying to get hotmail emails and store in Oracle 10g database.
    When I am executing receivemail procedure from Oracle 10g database. I am getting following error.
    connect to ESIMSCO_UTIL_OWNER
    SQL> set serveroutput on
    SQL>
    SQL> Declare
    2 v_error_msg varchar2(10000);
    3 Begin
    4 v_error_msg:=receivemail('pop3.live.com', '<My email address>@hotmail.com', '<My email password>');
    5 dbms_output.put_line(v_error_msg);
    6 End;
    7 /
    javax.mail.AuthenticationFailedException: EOF on socket
    PL/SQL procedure successfully completed.
    SQL>
    I did following steps, but still I am getting this error. Can somebady help me to solve this problem.
    connect sys/<password>@esimsco as sysdba
    connect to sys
    SQL*Plus: Release 10.2.0.1.0 - Production on Wed May 30 16:02:04 2012
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    SQL> begin
    1 dbms_java.grant_permission( 'ESIMSCO_UTIL_OWNER', 'SYS:java.util.PropertyPermission', '*', 'read,write' );
    2 commit;
    3 end;
    4 /
    PL/SQL procedure successfully completed.
    SQL> begin
    2 dbms_java.grant_permission(
    3 grantee => 'ESIMSCO_UTIL_OWNER',
    4 permission_type => 'SYS:java.net.SocketPermission',
    5 permission_name => '*',
    6 permission_action => 'connect,resolve'
    7 );
    8 end;
    9 /
    PL/SQL procedure successfully completed.
    SQL> begin
    2 dbms_java.grant_permission(
    3 grantee => 'ESIMSCO_UTIL_OWNER',
    4 permission_type => 'SYS:java.util.PropertyPermission',
    5 permission_name => '*',
    6 permission_action => 'read,write'
    7 );
    8 end;
    9 /
    PL/SQL procedure successfully completed.
    SQL> commit;
    Commit complete.
    SQL>
    Then I connect ESIMSCO_UTIL_OWNER.
    connect to ESIMSCO_UTIL_OWNER
    Create 2 tables.
    create table attachment(
    at_file varchar2(500),
    at_mimetype varchar2(500),
    at_attachment blob
    create table email (
    em_incident integer,
    em_from varchar2(1000),
    em_subject varchar2(1000),
    em_body nclob
    Then Create java source named receivemail.
    create or replace and compile java source named receivemail as
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    import java.io.*;
    import java.sql.*;
    import sqlj.runtime.*;
    import oracle.sql.BLOB;
    public class ReceiveMail
    static void getAttachments(Message message, int incidentNo)
    throws MessagingException, IOException, SQLException {
    //String attachments = "";
    Object content = message.getContent();
    if (content instanceof Multipart)
    // -- Multi part message which may contain attachment
    Multipart multipart = (Multipart)message.getContent();
    // -- Loop through all parts of the message
    for (int i=0, n=multipart.getCount(); i<n; i++) {
    Part part = multipart.getBodyPart(i);
    String disposition = part.getDisposition();
    if ((disposition != null) &&(disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
    //-- This part is a file attachment
    String fileName = incidentNo+"_"+part.getFileName().replace(' ','_');
    System.out.println("FILE: " + fileName);
    String contentType = part.getContentType();
    String mimeType = contentType.substring(0,contentType.indexOf(";"));
    System.out.println("FILETYPE: " + mimeType);
    InputStream is = part.getInputStream();
    // -- To work with a BLOB column you have to insert a record
    // -- with an emptly BLOB first.
    #sql { insert into attachment(at_file, at_mimetype, at_attachment)
    values (:fileName, :mimeType, empty_blob()) };
    // -- Retrieve the BLOB
    BLOB attachment = null;
    #sql { select at_attachment into :attachment
    from attachment where at_file = :fileName };
    // -- Fill the BLOB
    OutputStream os = attachment.getBinaryOutputStream();
    int j;
    while ((j = is.read()) != -1) {
    os.write(j);
    is.close();
    os.close();
    // -- Set the BLOB by updating the record
    #sql { update attachment set at_attachment = :attachment
    where at_file = :fileName };
    static String getPlainTextBody(Message message)
    throws MessagingException, IOException
    Object content = message.getContent();
    if (message.isMimeType("text/plain")) {
    // -- Message has plain text body only
    System.out.println("SIMPLE TEXT");
    return (String) content;
    } else if (message.isMimeType("multipart/*")) {
    // -- Message is multipart. Loop through the message parts to retrieve
    // -- the body.
    Multipart mp = (Multipart) message.getContent();
    int numParts = mp.getCount();
    System.out.println("MULTIPART: "+numParts);
    for (int i = 0; i < numParts; ++i) {
    System.out.println("PART: "+mp.getBodyPart(i).getContentType());
    if (mp.getBodyPart(i).isMimeType("text/plain")) {
    // -- Return the plain text body
    return (String) mp.getBodyPart(i).getContent();
    } else if (mp.getBodyPart(i).isMimeType("multipart/*")) {
    // -- Body is also multipart (both plain text and html).
    // -- Loop through the body parts to retrieve plain text part.
    MimeMultipart mmp = (MimeMultipart) mp.getBodyPart(i).getContent();
    int numBodyParts = mmp.getCount();
    System.out.println("MULTIBODYPART: "+numBodyParts);
    for (int j = 0; j < numBodyParts; ++j) {
    System.out.println("BODYPART: "+mmp.getBodyPart(j).getContentType());
    if (mmp.getBodyPart(j).isMimeType("text/plain")) {
    // -- Return the plain text body
    return (String) mmp.getBodyPart(j).getContent();
    return "";
    } else {
    System.out.println("UNKNOWN: "+message.getContentType());
    return "";
    static void saveMessage(Message message)
    throws MessagingException, IOException, SQLException
    //String body = "";
    int incidentNo;
    // -- Get a new incident number
    #sql { select seq_incident.nextval into :incidentNo from dual };
    // -- Get the header information
    String from = ((InternetAddress)message.getFrom()[0]).getAddress();
    System.out.println("FROM: "+ from);
    String subject = message.getSubject();
    System.out.println("SUBJECT: "+subject);
    // -- Retrieve the plain text body
    String body = getPlainTextBody(message);
    // -- Store the message in the email table
    #sql { insert into email (em_incident, em_from, em_subject, em_body)
    values (:incidentNo, :from, :subject, :body) };
    // -- Retrieve the attachments
    getAttachments(message, incidentNo);
    #sql { commit };
    // -- Mark message for deletion
    // message.setFlag(Flags.Flag.DELETED, true);
    public static String Receive(String POP3Server, String usr, String pwd)
    Store store = null;
    Folder folder = null;
    try
    // -- Get hold of the default session --
    Properties props = System.getProperties();
    props.put("mail.pop3.connectiontimeout", "60000");
    Session session = Session.getDefaultInstance(props, null);
    // -- Get hold of a POP3 message store, and connect to it --
    store = session.getStore("pop3");
    store.connect(POP3Server,995, usr, pwd);
    System.out.println("Connected");
    // -- Try to get hold of the default folder --
    folder = store.getDefaultFolder();
    if (folder == null) throw new Exception("No default folder");
    // -- ...and its INBOX --
    folder = folder.getFolder("INBOX");
    if (folder == null) throw new Exception("No POP3 INBOX");
    // -- Open the folder for read_write (to be able to delete message) --
    folder.open(Folder.READ_WRITE);
    // -- Get the message wrappers and process them --
    Message[] msgs = folder.getMessages();
    for (int msgNum = 0; msgNum < msgs.length; msgNum++){
    saveMessage(msgs[msgNum]);
    System.out.println("No more messages");
    return ("SUCCESS");
    catch (Exception ex){
    ex.printStackTrace();
    return ex.toString();
    finally{
    // -- Close down nicely --
    try{
    // close(true), to expunge deleted messages
    if (folder!=null) folder.close(true);
    if (store!=null) store.close();
    catch (Exception ex){
    //ex.printStackTrace();
    return ex.toString();
    Then create function receivemail.
    create or replace function receivemail(pop3_server in string,
    pop3_usr in string,
    pop3_pwd in string)
    return varchar2
    is language java name
    'ReceiveMail.Receive(java.lang.String,
    java.lang.String,
    java.lang.String) return String';
    And then trying to execute function receivemail, but I am getting following error.
    SQL> set serveroutput on
    SQL>
    SQL> Declare
    2 v_error_msg varchar2(10000);
    3 Begin
    4 v_error_msg:=receivemail('pop3.live.com', '<Hotmail email address>@hotmail.com', 'Hotmail password');
    5 dbms_output.put_line(v_error_msg);
    6 End;
    7 /
    javax.mail.AuthenticationFailedException: EOF on socket
    PL/SQL procedure successfully completed.
    SQL>
    I am requesting, please help me to solve this problem.
    I will be very thankful for your kind help and support.
    Amol......

    Amol Karyakarte wrote:
    I am requesting, please help me to solve this problem.
    I will be very thankful for your kind help and support.
    Amol......since you asked for it:
    http://lmgtfy.com/?q=javax.mail.AuthenticationFailedException
    First hit
    Session session = Session.getDefaultInstance(props, null);Is null correct?
    Regards

  • Attachment without multipart content type

    Hello,
    My application receives mails sent from some different customers and parses the mail's attachments. The problem is that all these customers send their mails in a very different ways. Some of them send mails with "Content-Type: multipart/mixed;" header while some others send mail with the following headers (among some other):
    MIME-Version: 1.0
    Content-Type: application/xml
    Date: Tue, 11 Feb 2014 18:33:26 +0000
    From: <[email protected]>
    Message-ID: <1392143606.220.1@cls0361>
    Subject: orders000005311382.xml
    To: <[email protected]>
    There is no "Content-Type: multipart/mixed;" header at all. When I look at these messages with MS Outlook I can see that they have proper attachements.
    Now I have 2 problems:
    1. I would like to produce such an email myself since resending the received emails changes the message headers. There are lots of examples how to send a message with an attachment in Java with MimeMultipart object (this produces "Content-Type: multipart/mixed;") but I could not find one which sends the message with "Content-Type: application/xml" header only without any multipart header. I suspect that there are some specific applications which send mails in that way - not standard mail clients.
    2. I would like to get the attachment of a received mail with "Content-Type: application/xml" header. The following code works for "Content-Type: multipart/mixed;" only:
    public void invoke() throws Exception {
      /* Available Variables: DO NOT MODIFY
        In  : String mimeMessage
        In  : String encoding
        Out : String[] mimeParts
      * Available Variables: DO NOT MODIFY *****/
      javax.mail.util.ByteArrayDataSource ds = new javax.mail.util.ByteArrayDataSource(mimeMessage, "multipart/mixed");
      javax.mail.internet.MimeMultipart mm = new javax.mail.internet.MimeMultipart(ds);
      java.util.ArrayList<String> al = new java.util.ArrayList<String>();
      getAttachements(mm, al, 1);
      mimeParts = new String[0];
      mimeParts = al.toArray(mimeParts);
    private void getAttachements(javax.mail.internet.MimeMultipart mm, ArrayList<String> al, int depth) throws Exception {
      if (depth > 9) {
        return;
      int mimePartsCount = mm.getCount();
      for (int i = 0; i < mimePartsCount; i++){
        javax.mail.internet.MimeBodyPart mbp = (javax.mail.internet.MimeBodyPart)mm.getBodyPart(i);
        //System.out.println(depth + ": " + mbp + " " + mbp.getContentType() + " " + mbp.getContentID() + " " + mbp.getDisposition());
        if(mbp.getContentType().startsWith("multipart")){
          javax.mail.util.ByteArrayDataSource ds2 = new javax.mail.util.ByteArrayDataSource(mbp.getInputStream(), "multipart/mixed");
          javax.mail.internet.MimeMultipart mm2 = new javax.mail.internet.MimeMultipart(ds2);
          getAttachements(mm2, al, depth+1);
        } else {
          if (mbp.getDisposition() != null && mbp.getDisposition().startsWith("attachment") && !mbp.getContentType().contains("signature")){
            BufferedReader br = new BufferedReader(new InputStreamReader(mbp.getInputStream(),encoding));
            String s = br.readLine();
            StringBuffer sb = new StringBuffer();
            while (s != null) {
              sb.append(s);
              s = br.readLine();
            al.add(sb.toString());
    Could anyone suggest anything which may be helpful for resolving 1 or 2?
    Best regards

    You are right! parsing of such not-multipart mail may look like that:
    if (contentType.startsWith("application/xml")) {
                //just a plain attachement which is a mail's content and not a multipart.
                mimeParts = new String[1];
                //according to RFC 2822 empty line separates headers from the body
                mimeParts[0] = mimeMessage.substring(mimeMessage.indexOf("\n\r")).trim();
    } else {
                //multipart mail
                javax.mail.util.ByteArrayDataSource ds = new javax.mail.util.ByteArrayDataSource(mimeMessage, "multipart/mixed");
                javax.mail.internet.MimeMultipart mm = new javax.mail.internet.MimeMultipart(ds);
                java.util.ArrayList<String> al = new java.util.ArrayList<String>();
                getAttachements(mm, al, 1);
                mimeParts = new String[0];
                mimeParts = al.toArray(mimeParts);
    Thanks!

Maybe you are looking for

  • Mozilla problems

    I downloaded Mozilla firefox and whenever I want to connect to the internet it can't find the server, even though Safari can and I have full Wi-fi connection. Can anyone help?

  • Example of Blend Mode

    I am feeling difficult to use blend mode property of Display Object. Do anybody have example of having blendMode. I want to use in pratically. Here box is movie clip with single frame with 100 width and height with red color. Now, I want to use blend

  • Save a photo from facetime to camera roll

    When I receive a photo as an attachment in FaceTime I sometimes wish to save this photo. At present the only way I know how to do this on my iPad is: to touch the photo, then copy it, then past it into an email which I sent to myself. When I receive

  • Troubles with the sleeper: how can I avoid it restarting on its own?

    When on sleeper, my MacPro early 2008 restarts on its own after a while. Until very recently, it worked perfectly well.

  • What is mean by  help path in dialog?

    HI , I am working on list component that is provided by cq5 out of box. ther ia one property called helpPath whose value is  en/cq/current/wcm/default_components.html#List. What is this helppath. Any help would be appreciated. Thanks, Amit