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!

Similar Messages

  • Attachment Name in Content Type

    Hi All,
    I am doing a scenario where I receive messages from ABAP - SRM system through proxy(which isXI sender adapter) . The message contains set of attachments as well . I have certain manipulations to do before sending the attachments to the receiver system which is a third party . The attachments are taken into one of the fields of the target message as base encoded string and sent to the third party. For certain manipulations I need the attachment names . I tried to get the attachment name from runtime by using the method getContentType but it doesnt solve my purpose. But is there a way I can put in the attachment name in content type so that I can get the attachment name using getContentType method.
    I am dealing with a scenario where in I will be strictly using ABAP stack from the sender side ( no java adapters) .
    Can anyone guide me in this case as I am stuck with no ideas .
    Regards
    Nishant Kumar Singh

    Hello Nishant,
    You can acccess names, contents and encoding of the attachments within a message mapping via the Global Container Object
    of the Message Mapping API (Check out the mehtod "getInputAttachments() " of global Container in the official SAP Javadoc: http://help.sap.com/javadocs/pi/SP3/xpi/index.html).e.
    Best regards
                   Sebastian

  • Attach a custom content type and set as default for picture library using client object model

    Hi,
    How to associate custom content type to a picture libraray and set it as default using the client object model?
    Thanks

    Hello,
    Here you go:
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/b1de0697-0006-4f89-8909-1b94aa18ad89/how-to-reorder-content-types-in-list-with-client-context
    http://www.niteenbadgujar.com/2013/05/change-default-content-type.html
    Hope it could help
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • Servlet Responses without a Content-Type

    Hi,
    <p>
    Is it possible to configure OC4J running in a full iAS install not to set a default Content-Type header if the servlet code does not set one?
    <p>
    e.g. Using code such as:
    public class MyServlet extends HttpServlet
        public void doGet(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
            //response.setContentType(CONTENT_TYPE);
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head><title>My Servlet</title></head>");
            out.println("<body>");
            out.println("The servlet has received a GET. This is the reply.");
            out.println("</body></html>");
            out.close();
    }There are no 'default-mime-type' attributes in either the global-web-application.xml or orion-web.xml files. However, a debugger reveals that the AJPHttpServletResponse has a contentType member variable set to 'text/plain' when it is passed to the Servlet. This then gets used as a value for a Content-Type header in the response sent to the browser.
    <p>
    Is there anywhere else in the server's configuration that could be providing this default value? The documentation states that "If default-mime-type is not specified, then there is no default content type."
    <p>
    This is required to allow requests to be proxied through a Servlet and in cases where the proxied response doesn't have a Content-Type set, the Servlet should not set one either.
    <p>
    Thanks,
    <p>
    Andy.

    Hi Andy,
    I am not fully sure I understand your question but I will try and clarfiy the AS architecture which might help answer your question.
    The HTTP server is the "front-end" piece that receives ALL incoming requests. The HTTP server is a licensed version of Apache and we have written a module called mod_oc4j which allows for the HTTP server to communicate with the OC4J instance. We use a protocol called AJP to communicate between HTTP and OC4J.
    The AJPHttpServletResponse is the response that you are seeing being passed between these 2 modules and as the documentation state OC4J does not set any default mime types. This AJPHttpServletResponse is solely used for communication between HTTP and OC4J, I would however check the HTTP configuration to see if there any mime-settings there.
    Hope this helps.
    Deepak

  • Attachment without multipart

    Hi,
    Can anybody tell me if it is possible to send a mail with javamail without using MultiPart?
    thanks

    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!

  • Content type headers and spam checks within Java MAil

    Hello there
    I have successfully created a java mail api to send any one of the following
    plain/text message, with or without attachments, with or without the body of the email to be HTML
    I have a question on how to ensure that the email is not marked spam? Sometimes the Spam score goes high if there is olly html for an email that is text/html type.;
    What are the possible values for content/type of Mime Message header for following scenarios
    An Email message that may have its bodypart as html and may have attachments
    An Email message that will have plain text messages along with attahcments and HTML concattenated with text messages ( LIke google maps along with text message]
    IF I do messaget.set ("This is my message") andthen I add attachments to the message body part, is it advisable to have two seperate content-type mime headers for these messages? wrt not having higher spam score.
    Or Is it advisable to have seperate mime type content headers for text part and sperate for message part.
    IS the attachment part also has a seperate mime header content type value?
    does the header's content type value is plain/text for messages that are text messages with attachments>?
    IS there a way to chek spam scores for messages generated by java mail? The ides is to create java mail API customsied sot hat the sent emails are not marked spams ?
    In order for the mail to be having zero spam scrore, it is helpful to have seprate mime content type headers?
    Edited by: user9328023 on May 23, 2011 1:45 PM

    If you want to create a message that has both plain text and html versions of the main
    message content, you want to create a multipart/alternative message, as described in
    this FAQ entry.
    If that message also needs to have attachments, you should embed the multipart/alternative
    part in a multipart/mixed message, along with the attachment parts.
    If the html part needs to reference images included with the message, you would replace
    the text/html part with a multipart/related part, as described in this FAQ entry.
    Combining all these techniques together can seem a bit complicated unless you understand
    recursion! :-) Remember that in addition to creating a body part with a text content type,
    you can create a body part with a multipart content type, and use that body part in the same
    places you would use a text body part.
    As for making sure your message isn't marked as spam, well, you're probably asking in the
    wrong place, but the simple answer is to make sure that it's actually not spam! Usually the
    structure of the message isn't as important as the content of the message.

  • Protocols or COntent type used by the iPod Maps app

    I use the Map app on my iPod Touch (2G) all the time. Today I am on vacation and in spite of the fact that I have good WiFi connectivity, two apps will not function at all: The NY Times reader and the Apple Maps app. While you can use Safari to bring up the NY Times website (http://www.nytimes.com) and Google maps (http://maps.google.com), you cannot bring up http://mobile.nytimes.com in Safari.
    I believe the local WatchGuard Firewall at this resort is filtering out certain types of content it believes may be somehow destructive. I can see the error message: Unsafe content type "application/xhtml+xml" reported when attempting to access mobile.nytimes.com
    As far as the Maps app goes, one cannot bring up any bookmark nor determine one's current location, viz., "Your location cannot be determined." after some delay. I understand that in certain circumstances the message simply implies that the WiFi access point in use may never have been mapped, but the inability to look up any known good arbitrary address implies to me a communications problem.
    Anyone know what protocol and/or content type may be is use by the Maps app?

    If you want to create a message that has both plain text and html versions of the main
    message content, you want to create a multipart/alternative message, as described in
    this FAQ entry.
    If that message also needs to have attachments, you should embed the multipart/alternative
    part in a multipart/mixed message, along with the attachment parts.
    If the html part needs to reference images included with the message, you would replace
    the text/html part with a multipart/related part, as described in this FAQ entry.
    Combining all these techniques together can seem a bit complicated unless you understand
    recursion! :-) Remember that in addition to creating a body part with a text content type,
    you can create a body part with a multipart content type, and use that body part in the same
    places you would use a text body part.
    As for making sure your message isn't marked as spam, well, you're probably asking in the
    wrong place, but the simple answer is to make sure that it's actually not spam! Usually the
    structure of the message isn't as important as the content of the message.

  • No lists or libraries with InfoPath content types can be found.

    I published an InfoPath form to two libraries in the site, one was a document library and one to a form library. I am using the InfoPath Web Part in the same sight and when I open the toolpane, I get the following message:
    No lists or libraries with InfoPath content types can be found. Use Microsoft InfoPath
    to design a form template for InfoPath Forms Services and publish it to a SharePoint library or list.
    Can you help?

    Looks like it has been a while since this post.  Hope this helps someone still facing this problem.
    If you're publishing the InfoPath form as a Content Type:
    Make sure that the Library (Form Templates) where the form is being published to has Content Types enabled.
    Check that the Library where form is being saved upon submittal (if different from above, as it should be) has Content Types enabled.
    The newly published form Content Type added the Library where forms are submitted.
    If you're publishing the InfoPath form without a Content Type:
    Just make sure that the Library you're publishing to is a Forms Library.
    Enjoy!
    Thank you in advance!

  • SharePoint REST service to add an exsiting site content type to a list/library

    Trying to use SharePoint 2013 REST Service to add existing site content types to a list/library. Below MSDN article suggests that the POST method is available but does not say how to use it.
    http://msdn.microsoft.com/en-us/library/office/jj246793%28v=office.15%29.aspx#postsyntax_htm
    POST http://<sitecollection>/<site>/_api/web/lists(listid)/contenttypes/add(parameters)
    How do we create the body for this rest call?

    Hi You need to use the addAvailableContentType method to attach a Existing Content Type to a list/Library.
    Consider the below Sample. Take the Id of the Content Type and pass it.
    the REST API URL is 
     http://<sitecollection>/<site>/_api/web/lists(listid)/contenttypes/addAvailableContentType(contentTypeId)
    var siteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employees')/ContentTypes/AddAvailableContentType";
        var call = jQuery.ajax({
            url: siteUrl,
            type: "POST",
            data: JSON.stringify({            
                "contentTypeId": "0x0100E5EC1FE6D284A74A972A1776FFFE2DA0"            
            headers:
                   'accept': 'application/json;odata=verbose',
                    "content-type": "application/json;odata=verbose",
                    "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        call.done(function (data, textStatus, jqXHR) {
            var message = jQuery("#message");
            message.text("Added Content Type Successfully");
        call.fail(function (data, errorcode, errormessage) {
            alert("Could not enable content types: " + errormessage);
    Here 0x0100E5EC1FE6D284A74A972A1776FFFE2DA0 is the Content Type Id of my existing Content type "Employees"
    Ensure the AllowContentTypes is set to True for that List/Library
    R.Mani | http://rmanimaran.wordpress.com

  • Custom Action not Binding to custom content type

    I'm trying to create a custom action to replace the save button in the ribbon for publishing pages that have a specific content type. For some reason it isn't showing up on the publishing pages with the specified content type. Here is the xml:
    <CustomAction Id="30c31720-e337-451c-a7ac-a68d09f64a37.RibbonCustomAction2"
                    RegistrationType="ContentType"
          RegistrationId="0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D0095AC9C03A12F40F9A023F6278B841536"
                    Location="CommandUI.Ribbon"
                    Sequence="1006"
                    Title="Invoke &apos;RibbonCustomAction1&apos; action">
        <CommandUIExtension>
          <!-- 
          Update the UI definitions below with the controls and the command actions
          that you want to enable for the custom action.
          -->
          <CommandUIDefinitions>
            <CommandUIDefinition Location="Ribbon.WikiPageTab.EditAndCheckout.Controls._children">
              <Button Id="Ribbon.ListItem.Actions.RibbonCustomAction1Button"
                      Alt="Save"
                      Sequence="1"
                      Command="Invoke_RibbonCustomAction1ButtonRequest"
                      LabelText="Save"
                      TemplateAlias="o1"
                      Image32by32="_layouts/15/1033/images/formatmap32x32.png?rev=38"
                      Image32by32Top="-171"
                      Image32by32Left="-409"
                      Image16by16="_layouts/15/1033/images/formatmap16x16.png?rev=38" />
            </CommandUIDefinition>
          </CommandUIDefinitions>
          <CommandUIHandlers>
            <CommandUIHandler Command="Invoke_RibbonCustomAction1ButtonRequest"
                              CommandAction="~remoteAppUrl/CustomActionTarget.aspx?{StandardTokens}&amp;SPListItemId={SelectedItemId}&amp;SPListId={SelectedListId}"/>
          </CommandUIHandlers>
        </CommandUIExtension >
      </CustomAction>
    However, if I remove the RegistrationType and RegistrationID the custom action does show up but it is on all pages. any ideas?

    Hi David,
    According to your description, my understanding is that you want to add the custom action which bind to the content type to the Ribbon.WikiPage.Tab location.
    I reproduced the issue with the code below, if I add the RegistrationType="ContentType" and  RegistrationId="0x01"
    to the custom action element, the button disappear in the ribbon, if I removed the button will again appear.
    Here is my test code without binding content type snippet:
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <CustomAction
    Id="Ribbon.WikiPageTab.CustomGroup"
    Location="CommandUI.Ribbon">
    <CommandUIExtension>
    <CommandUIDefinitions>
    <CommandUIDefinition
    Location="Ribbon.WikiPageTab.Groups._children">
    <Group
    Id="Ribbon.WikiPageTab.CustomGroup"
    Sequence="55"
    Description="Custom Group"
    Title="Custom"
    Command="EnableCustomGroup"
    Template="Ribbon.Templates.Flexible2">
    <Controls Id="Ribbon.WikiPageTab.CustomGroup.Controls">
    <Button
    Id="Ribbon.WikiPageTab.CustomGroup.CustomGroupHello"
    Command="CustomGroupHelloWorld"
    Image16by16="Insert an image URL here."
    Image32by32="Insert an image URL here."
    LabelText="Hello, World"
    TemplateAlias="o2"
    Sequence="15" />
    <Button
    Id="Ribbon.WikiPageTab.CustomGroup.CustomGroupGoodbye"
    Command="CustomGroupGoodbyeWorld"
    Image16by16="Insert an image URL here."
    Image32by32="Insert an image URL here."
    LabelText="Good-bye, World"
    TemplateAlias="o2"
    Sequence="18" />
    </Controls>
    </Group>
    </CommandUIDefinition>
    <CommandUIDefinition
    Location="Ribbon.WikiPageTab.Scaling._children">
    <MaxSize
    Id="Ribbon.WikiPageTab.Scaling.CustomGroup.MaxSize"
    Sequence="15"
    GroupId="Ribbon.WikiPageTab.CustomGroup"
    Size="LargeLarge" />
    </CommandUIDefinition>
    </CommandUIDefinitions>
    <CommandUIHandlers>
    <CommandUIHandler
    Command="EnableCustomGroup"
    CommandAction="javascript:return true;" />
    <CommandUIHandler
    Command="CustomGroupHelloWorld"
    CommandAction="javascript:alert('Hello, world!');" />
    <CommandUIHandler
    Command="CustomGroupGoodbyeWorld"
    CommandAction="javascript:alert('Good-bye, world!');" />
    </CommandUIHandlers>
    </CommandUIExtension>
    </CustomAction>
    </Elements>
    In this case, I suggest you can add the custom action directly to the ribbon without binding to the content type and it will work as expected.
    Thanks
    Best Regards
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected].

  • OSB defaulting Content-Type to "multipart/related" in case of attachments

    I have scenario where I need to invoke a REST Webservice from OSB which accepts only media types which has "multipart/atom+xml". OSB is used for protocol transformation converting the SOAP request into the HTTP POST request with multipart. I have Proxy Service which will unwrap the message from the SOAP Body and post the same message into the payload of the Business Service and the attachment is passed 'as is' from the SOAP Service. The external REST Service Provider expects the media type to be "multipart/atom+xml", but in OSB when an attachment is present in the message, OSB is overrding the "Content-Type" proeprty to "multipart/related" inspite of me setting the "Content-Type" property of HTTP Transport Header in OSB and as result external RESTFUL Service is throwing "415-Unsupported Media Type" error. Below is the test results. One interesting thing is, it happens only when there is attachment present in the message. In case of a message which doesn't have attachment any "Content-Type" specified in the Transport Header is passed by the OSB to the external service. Any help is highly appreciated.
    OSB Transport Header
    Added the header <http:Content-Type>multipart/atom+xml</http:Content-Type>
    Actual Raw Message
    POST http://xxx7200:7004/XXXInterfaces/identify HTTP/1.1
    Content-Type: multipart/related; type="text/plain"; start="<Root_-328322390>"; boundary=MIME_Boundary; charset=UTF-8
    MIME-Version: 1.0
    User-Agent: Java1.6.0_17
    Host: xxx7200:7004
    Accept: text/html, image/gif, image/jpeg, */*; q=.2
    Proxy-Connection: Keep-Alive
    Content-Length: 4823
    Expected Raw Message
    POST http://xxx7200:7004/XXXInterfaces/identify HTTP/1.1
    Content-Type: multipart/atom+xml; boundary=MIME_Boundary;
    User-Agent: Java1.6.0_17
    Host: xxx7200:7004
    Accept: text/html, image/gif, image/jpeg, */*; q=.2
    Proxy-Connection: Keep-Alive
    Content-Length: 4803
    -KC
    Edited by: 799459 on Apr 8, 2011 5:36 AM
    Edited by: 799459 on Apr 8, 2011 7:02 AM
    Edited by: 799459 on Apr 8, 2011 7:13 AM
    Edited by: 799459 on Apr 8, 2011 7:14 AM

    HTTP content-type header has the following limitation as per osb doc.
    Oracle Service Bus run time may overwrite these headers in the binding layer when preparing the message for dispatch. If these headers are modified, $inbound and $outbound are updated accordingly. So what you are seeing may be working as designed. Cant the remote service accept the multi part related content type set up by osb ?

  • E-Mail recevier with Content-Type: multipart/mixed

    Hi All,
    I am working on proxy to Mail scenario, wherein Pi is receiving data from SAP over proxy, creating a csv of the data and sending it to recipient as the email with the attachment.
    The User is saying that he wants the email content type as Multipart MIME format. I have searched on SDN and web, but couldnu2019t find how to implement in PI.Please provide your inputs.
    Thanks in advance,
    Ruchi

    Hi Ruchi,
    You need to use Java Mapping or UDF to create Multipart/Mime
    Check this excellent blog by stefan.
    http://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/6321
    Also check this thread for your solution
    http://forums.sdn.sap.com/message.jspa?tstart=0&messageID=945095

  • How to set content type for the attachment?

    Hello Everybody,
    I was trying to do the following in my send mail program:-
    1. I am making a file using FileWriter:
    FileWriter fw = new FileWriter(f);
    fw.write(str);
    2. I now want to attach this file with my mail. but before that I want to set the Content type of this as "application/smil". and trying the following code:
    mimebodyparts[0].setContent(fds[0],"application/smil");
    As this is a new MIME type perhaps I need to change the mailcap file. I found the same in the activation jar package but thought instead of chagning the default file i tried putting following code in my program:
                  File capfile = new File("simple.mailcap");
                  if (!capfile.isFile())
                        System.out.println("Cannot locate the \"simple.mailcap\" file.");
                        System.exit(1);
                  CommandMap.setDefaultCommandMap( new MailcapCommandMap(new FileInputStream(capfile)));
    and in simple.mailcap file put the following value
    application/smil;;     x-java-content-handler=com.sun.mail.handlers.application_smil  but I am still getting the following error:
    javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/smil
    Can somebody Please help to sort this out.
    regards,
    Arun

    //add related mutip-part to combine parts
    MimeMultipart multipart = new MimeMultipart("related");
    //attach a pdf
    messageBodyPart = new MimeBodyPart();
    fds = new FileDataSource("h:/something.pdf");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setFileName(fds.getName());
    multipart.addBodyPart(messageBodyPart);
    //add multipart to the message
    message.setContent(multipart);
    //send message
    Transport.send(message);

  • How to set Content-Type of attachment?

    Does anyone know how I can set the Content-Type of an attachment of an outgoing mail?
    I use Apple Mail, and with one correspondent I have this annoying problem that he never receives any excel or word attachments that I send (and possibly other ones, too).
    Our support now says that I should try to set the Content-Type
    of the excel attachments to "Content-Type: application/vnd.ms-excel".
    Apple Mail seems to set it to
    "Content-Type: application/octet-stream"
    and they think that attachments with this content-type might get blocked by the mail server of my correspondent.
    Any suggestions, ideas, etc., will be appreciated.
    Best regards,
    Gabriel.

    Thanks a lot for your test.
    Unfortunately, I get
    Content-Type: application/octet-stream;
    when I try to send an excel attachment to myself.
    Below is the beginning of the email (in "source" format).
    Any ideas why you get the correct mime-type, but I don't?
    Regards,
    Gabriel.
    ---------- beginning of email
    Return-Path: <[email protected]>
    Received: from [80.128.100.143] (account xxxxxxx HELO [192.168.2.100])
    by tu-clausthal.de (CommuniGate Pro SMTP 5.2.4)
    with ESMTPSA id 35503032 for [email protected]; Mon, 30 Jun 2008 21:59:05 +0200
    Message-Id: <[email protected]>
    From: Gabriel Zachmann <[email protected]>
    To: Gabriel Zachmann <[email protected]>
    Content-Type: multipart/signed; boundary=Apple-Mail-13-325543015; micalg=sha1; protocol="application/pkcs7-signature"
    Mime-Version: 1.0 (Apple Message framework v924)
    Subject: test
    Date: Mon, 30 Jun 2008 21:59:04 +0200
    X-Mailer: Apple Mail (2.924)
    --Apple-Mail-13-325543015
    Content-Type: multipart/mixed;
    boundary=Apple-Mail-12-325542957
    --Apple-Mail-12-325542957
    Content-Disposition: attachment;
    filename="Kostenabfrage AVILUS Gesamtinklusive_TPxyz 080606.xls"
    Content-Type: application/octet-stream;
    x-mac-creator=5843454C;
    x-unix-mode=0644;
    x-mac-type=584C5338;
    name="Gesamt.xls"
    Content-Transfer-Encoding: base64

  • Setting attachment content-type manually?

    Hello,
    I am trying to write code that will allow a user to specify the content-type of an attachment when s/he adds it to an email. The following code, which appears to let Java figure out the content-type from the file extension, works just fine:
    Multipart multipart = new MimeMultipart();
    // Part one is the text
    BodyPart bodyPart = new MimeBodyPart();
    bodyPart.setText("Some text");
    multipart.addBodyPart(bodyPart);
    // Part two is the attachment
    bodyPart = new MimeBodyPart();
    DataSource sourceFile = new FileDataSource(FileName);
    bodyPart.setDataHandler(new DataHandler(sourceFile));
    multipart.addBodyPart(bodyPart);
    message.setContent(multipart);
    I attached a .exe file, passed the DataSource into the DataHandler constructor, and it sent the email as expected, with a Content-Type of application/octet-stream. However, if I do the following instead:
    bodyPart.setContent(fileDataSource, "application/octet-stream");
    -or-
    bodyPart.setDataHandler(new DataHandler(fileDataSource, "application/octet-stream");
    I get the dreaded javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/octet-stream. Why do I get this exception when using setContent, but not when I use the DataHandler? It seems it has the same Content-Type either way.
    -Aaron

    Well, I figured out the answer myself by digging into the source code.
    When you create a DataHandler by using the (Object, String) constructor, it expects an Object that is not a DataSource, or so it would seem. So I abducted the BinaryArrayDataSource from the demo classes and instantiated one of it, specifying my desired content type and passing in the FileInputStream from the file that I was creating my FileDataSource from, and it worked like a champ.
    So, the moral is, use DataSources whenever possible!
    -Aaron

Maybe you are looking for