Problem in handling mail attachment by java in Microsoft outlook 2003

I have written code in Java for extracting attachment files from mail message but the same code is working with Microsoft Outlook 2000 but not working with Microsoft Outlook 2003. need solution for this problem ASAP.It is failing in recognizing boundries of attachments.
Mail API version :1.3.3_01
Part part = mimemultipart.getBodyPart(i);
String disposition = part.getDisposition();
objStatement=objConnection.createStatement();
if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)))                System.out.println("****Attachement found****");
rs=objStatement.executeQuery("select KNTA_ATTACHMENT_S.nextval from dual");
while(rs.next())
strAttachementId=rs.getString(1);
System.out.println("Attachement id"+strAttachementId);          strFileName=part.getFileName();          System.out.println("file attach with the mail"+strFileName);     attachementDir=strAttachementId.substring (strAttachementId.length()-2,strAttachementId.length());
System.out.println("Attachement dir"+attachementDir);     storedFileName=strAttachementId+"_"+part.getFileName();     System.out.println("Stored filename"+storedFileName);     OutputStream out=new FileOutputStream(strAttachmentPath+"/"+attachementDir+"/"+storedFileName);     InputStream in=part.getInputStream();          
while ((len = in.read(buf)) > 0)
     {                           //System.out.println("content"+buf);
out.write(buf, 0, len);
in.close();
out.close();
Message was edited by:
Vikas_Rathore_Patni

Hi Vikas_Rathore_Patni
I'm a student in Greece and I'm interested in the way this code of yours actually works. What i really want to do is to find a way of opening e-mail attachments and extracting them to a txt file. Are there any necessary tips for that ?
I would really appreciate it if you could send me this code of yours in this mail :
[email protected]
Regards Marios

Similar Messages

  • Problem in Reading Mail Attachement

    I'm facing a problem while reading mail attachments. Java-mail returns null disposition for the below message,but this message has attachment javamail is not considering the mail attachment .I'm using java-mail 1.3.Can anybody help me to solve this problem ?
    Return-Path: prvs=00548bd8bd=[email protected]
    Received: from PRODTM1.TRUST.UASC.AO ([172.28.2.143])
         by trust.uasc.net
         ; Mon, 14 Mar 2011 11:07:04 +0000
    X-TM-IMSS-Message-ID:<[email protected]>
    Received: from gw.northport.com.my ([202.188.31.130]) by trust.uasc.net ([172.28.2.144])
    with ESMTP (TREND IMSS SMTP Service 7.1) id 45727fb90003495a ; Mon, 14 Mar 2011 11:06:52 +0000
    Received: from [192.1.10.13] (port=59768 helo=nmbsmtp-01.northport.com.my)
         by gw.northport.com.my with esmtp (Exim 4.69)
         (envelope-from <[email protected]>)
         id 1Pz5bs-0003EO-0A; Mon, 14 Mar 2011 19:06:48 +0800
    X-CTCH-RefID: str=0001.0A090205.4D7DF6C8.0116,ss=1,fgs=0
    Date: Mon, 14 Mar 2011 19:05:50 +0800 (SST)
    From: AMTedi-Container Svcs <[email protected]>
    Message-ID: <[email protected]>
    Mime-Version: 1.0
    To: [email protected], [email protected],
    [email protected], [email protected]
    Subject: CODCT1UAS
    Content-Type: multipart/mixed; boundary="-"
    X-TM-AS-Product-Ver: IMSS-7.1.0.1394-6.5.0.1024-18010.003
    X-TM-AS-Result: No--4.942-5.0-31-1
    X-imss-scan-details: No--4.942-5.0-31-1

    If you were assuming that every message would have a valid body part
    and that they would tell you definitively which parts you should consider to
    be "attachments", ya, that won't work. The disposition is a hint at best.
    It can be wrong. It might not even be there.

  • Problems with the e-mails SKY send collapsing my Microsoft Outlook

    I have been forced to unsubscribe from SKY's e-mails as they collapse my Microsoft Outlook multiple times and I have to keep closing and re-opening it at least 6 or 7 times in order to get it into my delete box and delete it.  This has happened the last 4 or 5 times I have received the weekly e-mail from them and I said if it happened again I would unsubscribe.  It has just happended and I have.  They never used to do this so why am I having this problem now?  Does anyone else have this problem?  A good way to get all your subscribers to refuse to receive your offerings.  All large organisations make it impossible to contact them, so no way to let them know other than here.  If they sort it out they can let me know and I'll resubscribe, but not until.  They suggest I keep up with everything on Facebook or Twitter, except I do not and have no intention of using said platforms.  I have subscribed for nearly 25 years, mostly the full package.  I despair.

    Does this help:
    http://helpforum.sky.com/t5/Apps-websites/SKY-use-of-dpm-demdex-kills-e-mail/td-p/2346829/jump-to/first-unread-message

  • How do we transfer contacts and mails from apple mail and address book to Microsoft outlook on my mac

    How do we transfer contacts and mails from apple mail and address book to Microsoft outlook on my mac

    From Contacts, anyway (the new version of Address Book) you can export to a .abbu file and import then into Outlook. I'm not sure about Mail as I only really use Outlook...
    Clinton

  • Mail attachment in java

    hi
    Here is the code i am using for mail attachment without attachment it is working fine
    package com.nihon.login;
    import java.util.Properties;
    import java.util.ResourceBundle;
    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.activation.FileDataSource;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    import javax.mail.Multipart;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    import javax.mail.util.ByteArrayDataSource;
    public class Mail {
    * @param args
    private static String host = null;
    private static String from = null;
    private static String to = null;
    private static String subject = null;
    private static String content = null;
    private static String filename = "D:\\Users
    entry.pdf";
    public static void send(String fromAddress,String toAddress,String subject, String mailContent) throws Exception{
    send(fromAddress,toAddress,null,subject,mailContent);
    public static void send(String fromAddress,String toAddress, String ccAddress,String subject, String mailContent) throws Exception {
    ResourceBundle rb = ResourceBundle.getBundle("com.nihon.login.Application");
    MailInfo mail = new MailInfo();
    mail.setMailServer(rb.getString("nihon.mail.server"));
    if(fromAddress!=null){
    mail.setFromAddress(fromAddress);
    }else{
    mail.setFromAddress(rb.getString("nihon.mail.fromID"));
    host = mail.getMailServer();
    // Get system properties
    Properties props = System.getProperties();
    // Setup mail server
    props.put("mail.smtp.host", host);
    // Get session
    Session session = Session.getDefaultInstance(props, null);
    // Define message
    MimeMessage message = new MimeMessage(session);
    // Set the from address
    message.setFrom(new InternetAddress(mail.getFromAddress()));
    // Set the to address
    if(toAddress!=null)
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
    if(ccAddress!=null){
    message.addRecipient(Message.RecipientType.CC, new InternetAddress(ccAddress));
    // Set the subject
    message.setSubject(subject);
    // Set the content
    message.setText(mailContent);
    For attachment
    BodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);
    // Send message
    Transport.send(message);
    // Method to instantiate once
    public static Mail getInstance() {
    if (instance == null) {
    instance = new Mail();
    return new Mail();
    // Construtctor
    protected Mail() {
    private static Mail instance = null;
    But now i add some code for attachment after that i got the exception in below
    javax.mail.MessagingException: IOException while sending message;
    nested exception is:
    java.io.IOException: No content
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625)
    at javax.mail.Transport.send0(Transport.java:169)
    at javax.mail.Transport.send(Transport.java:98)
    at com.nihon.login.Mail.send(Mail.java:104)
    at com.nihon.login.Mail.send(Mail.java:47)
    at com.nihon.login.Mailsender.sendMail(Mailsender.java:47)
    at com.nihon.login.Mailsender.attributeAdded(Mailsender.java:19)
    at org.apache.catalina.session.StandardSession.setAttribute(StandardSession.java:1334)
    at org.apache.catalina.session.StandardSession.setAttribute(StandardSession.java:1243)
    at org.apache.catalina.session.StandardSessionFacade.setAttribute(StandardSessionFacade.java:130)
    at com.nihon.track.OnsitePlacement.doProcessRequest(OnsitePlacement.java:347)
    at com.nihon.track.OnsitePlacement.doPost(OnsitePlacement.java:420)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:210)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:870)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:685)
    at java.lang.Thread.run(Unknown Source)
    How can i solve this problem.
    Thanks in advance.......

    If the message is in an Exchange server, you can access it with JavaMail
    and extract the attachment. See the JavaMail FAQ and the many sample
    programs that come with JavaMail.
    If the message is in Outlook's message store on your desktop machine,
    it's harder. You need a JavaMail "message store provider" that understands
    the message store format used by Outlook on your local disk. JavaMail
    doesn't come with such a provider, but you might find one in the Third
    Party Products list on the JavaMail web page.

  • Extract Mail Attachment using Java Mail

    Hello Friends
    A day ago I entered into Java Mail , now I am able to send mail from my Java Program.
    The help I need from you is I wanna save the attachment coming in the mail using Java.
    For eg : a mail reched my Inbox contains .xls or .csv file which I wanna save to some place.
    Plss guide me to acheive this friends.
    Regards
    Vicky

    String host = "";
    String username = "";
    String password = "";
    String srcDir = "INBOX";
    String tarDir = "";
         String subject = "";
    String filepath = "C:/Documents and Settings/name/Desktop";
    String filename = "demo";
    Properties props = System.getProperties();
    props.put("mail.host", host);
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imap");
    store.connect(host, username, password);
    Folder folder = store.getFolder(srcDir);
              Folder dFolder = store.getFolder(tarDir);
    folder.open(Folder.READ_WRITE);
              Message message[] = folder.getMessages();
              java.util.Date yesterdayDate = new Date(System.currentTimeMillis() - 24*60*60*1000);
    for (int p = 0; p < message.length; p++) {
                   java.util.Date messageReceivedDate = message[p].getReceivedDate();
                   if(messageReceivedDate.after(yesterdayDate))
                        if (message[p].getSubject().equals(subject)) {
                             Multipart mp = (Multipart)(message[p].getContent());
                             for (int i = 0, n = mp.getCount(); i < n; i++) {
    Part part = mp.getBodyPart(i);
    String disposition = part.getDisposition();
    if ((disposition != null) && (disposition.equals("ATTACHMENT") || disposition.equals("INLINE")))) {
    String fullpath = filepath+"/" + filename+".csv";               
    File file = new File(fullpath);
    InputStream in = part.getInputStream();
    FileOutputStream fos = new FileOutputStream(file);
    byte[] buf = new byte[part.getSize()];
    int c = 0;
                             while ((c = in.read(buf)) != -1) {
    fos.write(buf, 0, c);
                                       in.close();
                                       fos.close();
                                  } // if (disposition) closing
                             }// inner for loop closing
    /* ----------------------------------------------------Move Message to new folder--------------------------------------------------------------------- */
    if (message.length != 0) {
    folder.copyMessages(message, dFolder);
    folder.setFlags(message, new Flags(Flags.Flag.DELETED), true);
    // Dump out the Flags of the moved messages, to insure that
    // all got deleted
    for (int i = 0; i < message.length; i++)
                                  if (!message.isSet(Flags.Flag.DELETED))
                                       System.out.println("Message # " + message[i] + " not deleted");
                             } //for
    }// if (message.length != 0)
    // System.out.println("*** Message moved to "+tarDir+" Directory ***");
                        }//if loop closing - checking message subject
                   }// if loop closing checking date
    }// outer for() loop closing

  • Reader X: Attaching PDF to email in Outlook 2003

    Since installing Reader X, it takes several minutes to attach a PDF to an email when using Outlook 2003 (installed on Windows XP SP3, with Outlook and Windows fully patched, running McAfee VirusScan for AV).
    This occurs with any pdf document, regardless of size (all my tests have been on documents less than 70KB, attached from the local hard drive).  Attaching any other file format is unaffected and only takes a second.
    This problem does not occur for anyone that is using Outlook 2010.
    Can anyone advise what is causing this / how to fix?
    Thanks

    The only solutions I have found are to either downgrade Adobe Reader to 9.3.4 or upgrade Office to at least 2007
    Not really the best solutions - would prefer a proper fix.

  • Forwarding mails from SAP inbox to Microsoft Outlook

    I need to forward notifications in SAP workplace to Microsoft outlook...anybody worked upon,,??
    any function module which will capture the mails in mailbox...how to do??
    Thanks in advance....

    Hi sap technical
    Procedure:
    Go to the Business workflow ...then follow the below steps ...!
    its kind of configuration needed in the SAP System no coding required.
    Step1..go to the Business Workplace
    Step2..
    Access the settings by choosing SETTINGS - OFFICE SETTINGS.
    Choose the automatic forwarding tab.
    Here you can create new forwarding rule using the create button.you will get new window then..
    Step3...
    Insert your email address into the forward to field and choose External address from the drop down box.
    Choose the time period of this forwarding rule. In this example want to keep this forwarding for a long time.
    Step4....
    If you don’t want to keep copies of received SAP office mails remove the option.
    Choose copy to save the values
    If your email address is already maintained in your user profile you will receive a following pop up
    Step5...
    Now you can save the new forwarding rule and all of your SAP Office mails will be forwarded to you outlook inbox.
    You can also remove the forwarding rule anytime you want.
    Sample Code :
    Find the below code.
    DATA : RECEIVER TYPE SOMLRECI1 OCCURS 1 WITH HEADER LINE,
    S_DOC_CHNG TYPE SODOCCHGI1,
    S_OBJECT_ID TYPE SO_OBJ_ID.
    need to fill up the following compulsory
    1. S_DOC_CHNG-OBJ_DESCR = 'Mail subject line here'.
    2. RECEIVER-RECEIVER = '[email protected]'.( or as per ur requirement ).
    3. RECEIVER-REC_TYPE = 'U'. "Internet address
    4. S_OBJCONT contains the content of the mail.
    you have to append it.
    CALL FUNCTION 'SO_NEW_DOCUMENT_SEND_API1'
    EXPORTING
    DOCUMENT_DATA = S_DOC_CHNG
    DOCUMENT_TYPE = 'RAW'
    COMMIT_WORK = 'X'
    IMPORTING
    NEW_OBJECT_ID = S_OBJECT_ID
    TABLES
    OBJECT_CONTENT = S_OBJCONT
    RECEIVERS = RECEIVER
    EXCEPTIONS
    TOO_MANY_RECEIVERS = 1
    DOCUMENT_NOT_SENT = 2
    DOCUMENT_TYPE_NOT_EXIST = 3
    OPERATION_NO_AUTHORIZATION = 4
    PARAMETER_ERROR = 5
    X_ERROR = 6
    ENQUEUE_ERROR = 7
    OTHERS = 8.
    IF SY-SUBRC 0.
    MESSAGE ID SY-MSGID TYPE 'I' NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    Reward if found helpfull,
    Cheers,
    Chaitanya.

  • Problem for synchronizing calendars between my iPOD 30GB and OUTLOOK 2003

    Hello,
    I arrive to synchronize my contacts between my iPOD and OUTLOOK 2003 via iTunes, but not the calendars.
    Thank you for your help

    If you have EVER sync'd Outlook 2003 with a PDA then iTunes will throw an error when trying to sync Calendars.
    THE FIX:
    Delete all calendar entries
    (an easy way to do this is in Calendar select VIEW > Arrange By > Current View > Events)
    Then Delete all entries by highlighting them all right click and select delete!
    NOTE: You may have to repeat VIEW > ARRANGE By > Current View > {other categories in list i.e. "Category" and/or "Annual Events" and/or "Recurring Appointments"} To find all the entries that need to be deleted.
    Once all of the calendar data is deleted you can re-input the data, but you can never sync it with a PDA otherwise you will develop the original problem again.
    WHY DOES THIS WORK? Simply when a PDA syncs with Outlook it places a unique hidden identifer on each entry which screws up iTunes ability to sync with your calendars.
    Hope this is clear and helps someone.

  • Mail and Safari not storing Microsoft Outlook certificates properly

    I have a user on Mavericks who has a persistent problem with messages in her Microsoft 365 hosted spam filter. The email message sent contains a link to release the impounded item. When these links are clicked it works fine, but only for a few days. The link is opened in Safari and the message is released and the server displays a simple webpage to confirm this has happened. After a few days, however, Safari starts complaining about a certificate needing to be trusted, and it then goes into an infinite loop and the message is never released. This can be cured by finding, in Keychain, the certificate/certificates mentioned and deleting them. But this only works for a week or so.
    I've run a keychain repair and a repair permissions, but the problem comes back after 7-14 days.
    I've not seen this anywhere else, just on her account. Has anyone got any ideas?
    Things I could try:
    Set up a new user account and new email under that account. But this is a work environment and I don't think she wants that inconvenience.

    I have a user on Mavericks who has a persistent problem with messages in her Microsoft 365 hosted spam filter. The email message sent contains a link to release the impounded item. When these links are clicked it works fine, but only for a few days. The link is opened in Safari and the message is released and the server displays a simple webpage to confirm this has happened. After a few days, however, Safari starts complaining about a certificate needing to be trusted, and it then goes into an infinite loop and the message is never released. This can be cured by finding, in Keychain, the certificate/certificates mentioned and deleting them. But this only works for a week or so.
    I've run a keychain repair and a repair permissions, but the problem comes back after 7-14 days.
    I've not seen this anywhere else, just on her account. Has anyone got any ideas?
    Things I could try:
    Set up a new user account and new email under that account. But this is a work environment and I don't think she wants that inconvenience.

  • Problem with Contact download from Microsoft Outlook 2003 SP2

    For some strange reason that I cannot, for the life of me, figure out; my contact list ( address book ) downloads, but, even though I specified " sort by last name "; some contacts show up sorted by last name and some show up sorted by first name ! Also, some have commas in the name, even though there are no commas in the record in Outlook !
    Anybody else have this experience ??

    I went to edit-preferences-ipod-contacts tab and
    selected synchcronize from microsoft outlook and
    synchronize all contacts then I select ipod and
    update and doesn't syncronize my contacts, outlook
    was open by the way.
    Any ideas.
    same for calendar.
    it doesnot work itunes 6.0.5.20 the lattest.
    Please help.
    the only way that it works if I do it manually where
    I have to same my contacts 1 by 1 becuase I can't
    export them as .vcf files so I had to same every
    contact as a .vcf file in a private folder and then
    moved to my ipod as a hard drive use. Which takes to
    many steps for a normal user. It should be 1 step
    synchonize.
    I need ipod engineers to give a hand with this.
    Thanks in advance
    There it's only two options microsoft outlook and outlook express on the ipod contacts tab. So I chose microsoft outlook, and the answer for what I have in my computer it's Microsoft Outlook 2003.
    Thanks,
    Rj

  • Mail:send mail:attachment. Is there a simplest way to send a file as an email attachment ? or more correct ?

    <satellite:form  method="post" id="contact-form" enctype="multipart/form-data">
         <input type="file" name="adjunto" />
    </satellite:form>
    FTValList ftListaFichero = new FTValList(1);
    ftListaFichero.setValBLOB(ics.GetVar("adjunto_file"), ics.GetBin("adjunto"));
      <mail:send
           to="<%=to_emailaddress %>"
           from="<%=from_emailaddress%>"
           subject="Subject"
           body="<%=body %>" >
        <mail:attachment value='<%=ftListaFichero.getVal(ics.GetVar("adjunto_file"))%>'/>
      </mail:send>
    http://docs.oracle.com/cd/E29542_01/apirefs.1111/e39371/JSP/mail-attachment.html
    http://docs.oracle.com/cd/E29542_01/apirefs.1111/e39371/JSP/mail-send.html
    Regards,

    Simplest might well be to use javamail API instead of the two tags that Sites provides, e.g. see email - Sending mail attachment using Java - Stack Overflow for a full example.
    Phil

  • E-mail setup for Microsoft Outlook running on iMac

    Took delivery new iMac and set up mail account under Apple "Mail" app.  Subsequently installed Microsoft Outlook for Mac.  Entered details for my main mail account which were the same details entered in Apple Mail account.  I am unable to send mail from Outlook app, but can receive mail.  Have checked settings several times and see no difference from Apple Mail which send mail just fine.  For Microsoft Outlook, when I enter an e-mail message and then hit the send button, the message just disappears and does not show up in sent folder.  Any idea on how to fix appreciated.

    Go to their configuration instructions on the website and follow them, they do not seem to have been updated since Mountain Lion but should still be valid. Set the account up manually in Outlook.

  • Copying Apple mail pop3 account to Outlook 2003

    Hello,
    One of my client recently bought few PCs. They wasnt to use apple mails as well as the PCs. Is there a way to copy all POP 3 emails to Microsoft Outlook 2003. In apple mail, the users have four or five folders and within the folders they have subfolders.
    Operating system Mac os X 10.4.9
    Model: iMAC G5

    Hello UK_STRANGER.
    Selected messages can be exported in standard mbox format doing File > Save As in Mail and choosing Raw Message Source from the Format popup menu. Standard mbox files can be imported into most mail clients. In particular, they can be imported back into Mail doing File > Import Mailboxes and choosing Other as the data format.
    Andreas Amann’s Mail Scripts has an Archive Messages script that you may also find useful.

  • Java Mapping: payload as mail attachment and dynamic file name .

    Hi,
    I have written this piece of java code.
    The code includes XPATH for fetching dynamic filename and the copysource( in, out ) to copy the content of payload as mail attchment.
    The code seems to work fine, when either of the functionality is implemented.
    but when both are implemented together ie parsing for xpath then again parsing to copy payload, then it doesnt executes the latter path i.e the payload is not fetched in the attachment.
    public class MailPackage implements StreamTransformation {
      public void setParameter(Map map) {
      public void execute(InputStream in, OutputStream out)
              throws StreamTransformationException {
      String mailSubject = "test mail";
      String mailSender = "aaaaaaaa";
      String mailReceiver = "[email protected]";
      String attachmentName = null;
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
      factory.setNamespaceAware(false);
    factory.setValidating(false);
         try {
              builder = factory.newDocumentBuilder();
         Document doc = null;
          doc = builder.parse(in);
              String XPATH ="/*/Invoice/InvoiceHeader/InvoiceNumber/text()";
              Node fieldValueNode = org.apache.xpath.XPathAPI.selectSingleNode(doc,XPATH);
              System.out.print(fieldValueNode);
              attachmentName = fieldValueNode.getNodeValue() +".xml";
      String boundary = "--";
      String mailContent = "This is a sample file";
      String CRLF = "\r\n";
        //     create XML structure of mail package
        String output ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
               + "<ns:Mail xmlns:ns=\"http://sap.com/xi/XI/Mail/30\">"
               + "<Subject>" + mailSubject     + "</Subject>"
               + "<From>" + mailSender     + "</From>"
               + "<To>" + mailReceiver     + "</To>"
               + "<Content_Type>multipart/mixed; boundary=\"" + boundary + "\"</Content_Type>"
               + "<Content>";
        out.write(output.getBytes());
        // create the declaration of the MIME parts
        //First part
        output = "--" + boundary + CRLF
               + "Content-Type: text/plain; charset=UTF-8" + CRLF
               + "Content-Disposition: inline" + CRLF + CRLF
               + mailContent + CRLF
        //Second part
        + "--" + boundary + CRLF
        + "Content-Type: application/xml; name=" + attachmentName + CRLF
        + "Content-Disposition: attachment; filename=" + attachmentName + CRLF + CRLF;
        out.write(output.getBytes());
        //Source is taken as attachment
        copySource(in, out);
        out.write("</Content></ns:Mail>".getBytes());
      } catch (Exception ie) {
        throw new StreamTransformationException(ie.getMessage());
    protected static void copySource(InputStream in, OutputStream out)throws IOException {
        byte[] bbuf = new byte[in.available()];
        int bblen = in.read(bbuf);
       if (!(bblen < 0)) {
          String sbuf = new String(bbuf);
           //replace all control characters with escape sequences
         sbuf = sbuf.replaceAll("&", "&amp;");
         sbuf = sbuf.replaceAll("\"", "&quot;");
         sbuf = sbuf.replaceAll("'", "&apos;");
        sbuf = sbuf.replaceAll("<", "&lt;");
        sbuf = sbuf.replaceAll(">", "&gt;");
        out.write(sbuf.getBytes());
    Povide your suggestions.

    Hi,
    This is the sample o/p that I get by opening the mail attachment using notepad.
    <?xml version="1.0" encoding="UTF-8"?>
    <InvoiceTransmission><InvoiceTransmissionHeader><InvoiceCreationDate>2008-12-03T00:00:00</InvoiceCreationDate><Version>2.0.2</Version></InvoiceTransmissionHeader><Invoice><InvoiceHeader><CustomerEntityID>LH</CustomerEntityID><IssuingEntityID>009140559</IssuingEntityID><InvoiceNumber>913353669</InvoiceNumber><InvoiceIssueDate>2008-12-03</InvoiceIssueDate><InvoiceType InvoiceTransactionType="OR">INV</InvoiceType><InvoiceDeliveryLocation>aaa</InvoiceDeliveryLocation><TaxInvoiceNumber>Not Applicable</TaxInvoiceNumber><InvoiceCurrencyCode>USD</InvoiceCurrencyCode><InvoiceTotalAmount>517174.63</InvoiceTotalAmount><InvoiceIDDetails InvoiceIDType="BT"><InvoiceIDVATRegistrationNumber>0000000000</InvoiceIDVATRegistrationNumber><InvoiceIDName1>aaaaaaaaaaaaaaa</InvoiceIDName1><InvoiceIDName2>bbbbbbHKG</InvoiceIDName2><InvoiceIDCity>ccccccccc ccccc</InvoiceIDCity><InvoiceIDCountryCode>HK</InvoiceIDCountryCode></InvoiceIDDetails><InvoiceIDDetails InvoiceIDType="II"><InvoiceIDVATRegistrationNumber>0000000000</InvoiceIDVATRegistrationNumber><InvoiceIDName1>eeeeeeee</InvoiceIDName1><InvoiceIDName2>PAY BY WIRE TRANSFER</InvoiceIDName2><InvoiceIDCity>fffffffffffffff, NA</InvoiceIDCity><InvoiceIDCustomField ID="1"><InvoiceIDCustomFieldDescription>Company Registration Number</InvoiceIDCustomFieldDescription><InvoiceIDCustomFieldValue>0000000000</InvoiceIDCustomFieldValue></InvoiceIDCustomField></InvoiceIDDetails></InvoiceHeader><SubInvoiceHeader><InvoiceLine><ItemNumber>001</ItemNumber><ItemQuantity><ItemQuantityType>IN</ItemQuantityType><ItemQuantityFlag>GR</ItemQuantityFlag><ItemQuantityQty>28134.000</ItemQuantityQty><ItemQuantityUOM>USG</ItemQuantityUOM></ItemQuantity><ItemQuantity><ItemQuantityType>DL</ItemQuantityType><ItemQuantityFlag>GR</ItemQuantityFlag><ItemQuantityQty>106498.775</ItemQuantityQty><ItemQuantityUOM>LT</ItemQuantityUOM></ItemQuantity><ItemDeliveryReferenceValue ItemDeliveryReferenceType="DTN">590365</ItemDeliveryReferenceValue><ItemDeliveryReferenceValue ItemDeliveryReferenceType="!
    ARN">DAL
    CH</ItemDeliveryReferenceValue><ItemDeliveryReferenceValue ItemDeliveryReferenceType="FNO">mmmmmmmmm</ItemDeliveryReferenceValue><ItemDeliveryLocation>pppp</ItemDeliveryLocation><ItemReferenceLocalDate
    If you notice the problem is, the undesired "exclamation mark" that gets added in some fields before the actual value.
    In the above case.. look at "ItemDeliveryReferenceType="! ARN">DAL"
    the exclamation mark before value "ARN is unwanted, which leads to improper XML formation.
    Cant figure out why is this coming.
    Regards,
    Faria Mithani

Maybe you are looking for

  • How Can I Tell If An Image Has A Preview?

    I searched around and couldn't find the answer to this and I'm sure it's been asked and answered. The only way I've been able to tell if an image has a preview is if I see the Loading ... box when I click on an image in the Viewer. Is there another w

  • Creative ZEN Style M300/100: album art & clip?

    Hello, All the info about ZS M sound very interesting, but there are 2 questions: - if there is album art in the file, will be displayed on screen while playing? - is it a way to use this player with clip? All best, Ivo

  • What is "Other" and why does it take up so much space?

    What is "Other" and why does it take up so much space?

  • Quicktime - New Video Recording using Canon HV30 - Codec?

    I'm using Quicktime Pro 7.4.1 with a Canon HV30 connected via firewire. In Quicktime preferences pane, the HV30 is the video source with "Device Native" as the Quality setting. Though, I can't see a preview in the Quicktime window while recording, it

  • Sending smartform through email as PDF attachment

    Hi, I want to send a smartform through email as pdf attachment.In the code I have hardcoded the receiver mail id.But I don't want this to be sent only to a particular receiver.I want this to be sent as many people as I can without hardcoding their ma