Encoded file name for attachment

Hi
I'm writing a simple email client that connects to an imap server to fetch messages and save attachment files. The server is exchange. This works perfect, but when the mail is sent from lotus notes, the exchange server encodes the filename, even if there is no strange characters!
This is the code I use to get the file:
if (!in.hasNewMessages()) {
  return;
int nrM = in.getMessageCount();
int newM = in.getNewMessageCount();
Message[] messages = in.getMessages(nrM - newM + 1, nrM);
for (int i = 0; i < messages.length; i++) {
  Object content = messages.getContent();
String subject = messages[i].getSubject();
if (content instanceof BASE64DecoderStream) {
saveFile(messages[i]);
} else if (content instanceof Multipart) {
Multipart multi = (Multipart)content;
for (int j = 0; j < multi.getCount(); j++) {
BodyPart part = multi.getBodyPart(j);
saveFile(part);
private void saveFile(Part part) throws Exception {
String fileName = part.getFileName();
if (fileName != null) {
File file = new File(outFolder, fileName);
FileOutputStream fos = new FileOutputStream(file);
part.getDataHandler().writeTo(fos);
fos.close();
The fileName looks like this: =?ISO8859-1?Q?thefile.jpg?=
Is there a way to get the correct file name? Actually, it has to cover cases where the filename has strange characters also like this:
=?ISO8859-1?Q?F=E4lt=F6?=
What I have tried is this:
String newName;
if (fileName.indexOf("=?") != -1) {
  System.out.println(fileName);
  fileName = fileName.substring(fileName.indexOf("=?") + 2, fileName.lastIndexOf("?="));
  System.out.println(fileName);
  StringTokenizer st = new StringTokenizer(fileName, "?");
  String encodingType = st.nextToken();
  System.out.println(ecodingType);
  String type = st.nextToken();
  System.out.println(type);
  String name = st.nextToken();
  System.out.println(name);
  try {
    String newFileName = new String(name.getBytes(), encodingType);
    newName = newFileName;
  } catch (UnsupportedEncodingException uee) {
    newName = name;
System.out.println(newName);This is whats printed:
=?ISO8859-1?Q?F=E4lt=F6.jpg?=
ISO8859-1?Q?F=E4lt=F6.jpg
ISO8859-1
Q
F=E4lt=F6.jpg
F=E4lt=F6.jpg
I've never used new String(byte[] bytes, String charset) before, so It might be that I'm using it wrong?
Well, here's the question:
Is there a way to get the fileName correct directly through the Java mail api? If not, how can I decode the filename to the correct name?
Thanks a lot
Tobias

The String constructor interprets the given raw bytes using a given charset. The encoding in mime messages is more of an 'escape sequence' which includes the charset name and mime-encoded bytes (i.e. base64 or quoted printable etc.). You can reconstruct the original String by using the MimeUtility.decodeWord() method, which decodes the bytes and internally calls the String constructor with the appropriate charset.
try something like
String name = part.getFileName();
if (name != null && name.startsWith("=?"))
name = MimeUtility.decodeWord(name);

Similar Messages

  • Why does the file Name for file attached with Annotations "Attach File" (paperclip) become Unknown when Comments are Published?

    Our company recently purchased Adobe Acrobat Pro XI for the purpose of using it for shared electronic reviews.  We are using Send for Shared Review created in Adobe Acrobat Pro XI, and all the Comment tools work as expectedexcept the paperclip in Annotations.
    When a Word or Excel or Image(png,jpeg) file is attached using the Annotations paperclip, the initiator can initially see and open it. But after Publish Comments is selected and the review file is closed, the file "Name" changes to "Unknown" (although the Description has the correct file name and extension).  The Modified information is Unknown, as is the Size and Compressed Size.
    When the review file is then re-opened, even the initiator cannot open the file, although:
    The file location is marked with the paperclip within the document.
    The file name is shown in the Comments List with the initiator's name.
    In the Attachments list (the paperclip beneath the Thumbnails and Bookmarks) the Name appears as Unknown, Description shows the file name, Modified is Unknown, Size is Unknown, and Compressed Size is Unknown.
    The file Name cannot be edited, although the file Description can be.
    We have followed the procedure described in the tutorials but cannot figure out how to troubleshoot this situation.  Since this feature was the reason for the purchase of Adobe Acrobat Pro IX, we would any help. Please don't leave out any basics since we are all new users.
    We have several people with Adobe Acrobat Pro XI and the rest have Adobe Reader XI and it is a Windows platform.  Can someone please give us some advice how to get this feature to work as described?

    FYI Rave,
    There are some other forum entries with this exact same issue...:
    Cannot Open Attachments in PDF
    Why does the file Name for file attached with Annotations "Attach File" (paperclip) become Unknown when Comments are Published?
    Can someone help us get the COMMENTS ATTACHMENT TOOL to work as described in Acrobat Pro XI?

  • How do i change the HTML file names for existing index

    Hi,
    How do i change my existing HTML file names for indexes. The Html file name is disabled when we click on properties.
    Ex:   Index Keywork : Architecture
            Old HTML Page/URL =: Architecture.htm
    I want to change  Old HTML Page/URL =: Architecture.htm to architecture_new.htm
    Please find the screenshot attached.

    That's because you are looking at the Properties and that is not how you create index entries.
    Highlight the Index keyword ("Paste" in this example). It shows below what is already linked. If you delete that, the keyword will be displayed in bold to show no keyword is attached. You can add further keywords by dragging them from the Topic List.
    See www.grainge.org for RoboHelp and Authoring tips
    @petergrainge

  • Change file name in attachment -- Sales Order

    Hi guys,
    I have to change the file name in attachment (sales order ), a pdf sent via va02 Extras/output/header/edit to mail defined in xd02.
    I used the standard program /SMB40/RVADOR01,
    what I have now : in attachement file is like 'SAPLSTXBE /20080102/174052.pdf'
    in object mail 'SAPLSTXBE /20080102/174052' .
    What can I do for changing those values?
    need urgent help please
    thanks.

    I have tried this but that doiesn't work:
    Changing the subject for email order confirmations
    An output type ZEXT was created to send emails of order confirmations to a certain distribution list in PDF format. (See the SAP Exchange Connector Implementation Documentation for details on this setup.)
    The following code and config was implemented in order to change the email subject line.
    Configuration for ZEXT (External order confirmation by email)
    Transaction: V/30
    General Data: Access Seq: 0009 (SalesOrg./Cust./Order type), Access to Conditions CHECKED.
    Replacement of text symbols – Program: ZEXT. Form routine: TEXT_SYMBOL_REPLACE
    Default Values: Transmission Medium: 5. Communication Strategy CS01.
    Mail and Titles: &KUNNR&:Order &VBELN&
    Processing Routines: Program: RVADOR01, Form Routine: ENTRY, Form: YPCC_ORDCONF_STD
    Condition Record
    Using VV12 you need to add a condition record as applicable. Note that the Communication record must point to your ZMAIL output device and has the following entry as Text for Cover Page: &KUNNR&(&VBELN&)
    Code for ZEXT subject definition
    REPORT zext.
    Author: Kevin Wilson
    Date: 01/07/2003
    Description: This program changes the title of the email for output
                 type ZEXT. Maintain output type ZEXT using V/30.
                 The mail title and texts tab has entry:
                 &KUNNR&:Order &VBELN&
                 The general tab has entry in Replacement of text
                 symbols: Program ZEXT. Form:TEXT_SYMBOL_REPLACE
    tables: kna1.
    FORM text_symbol_replace TABLES xtlines STRUCTURE tline
                             USING xthead STRUCTURE thead
                                   snast  STRUCTURE nast.
      data: t_vbeln(10) type c.
      DESCRIBE TABLE xtlines LINES  sy-tabix.
      CHECK sy-tabix GT 0.
      LOOP AT xtlines.
        move snast-objky to t_vbeln.
        replace '&VBELN&' with t_vbeln into xtlines-tdline.
        select single name1 into kna1-name1
          from kna1
          where kunnr = snast-parnr.
        replace '&KUNNR&' with kna1-name1 into xtlines-tdline.
        condense xtlines-tdline.
        modify xtlines.
      ENDLOOP.
    ENDFORM.

  • How to create Same file names for source and target.

    hi
    Can any body send Procedure for below requirement.
    how to create the dynamic file names for a source and save the file with same name in the Target, because it has to identify that which sender had sent the file and the target file should be again sent back to the customer as a link.
    Please help me.
    Thanks

    Hi,
    See the below link
    /people/michal.krawczyk2/blog/2005/11/10/xi-the-same-filename-from-a-sender-to-a-receiver-file-adapter--sp14 - sender file name as receiver file name
    Regards
    Chilla

  • I just found an error in the file name for my Camera Raw Cache file.  How do I correct it?

    I just found an error in the file name for my camera raw cache file.  The error is in my username.  I don't know how to correct the error or if I should just leave it.  I'm not sure where my cache file is stored on my computer.  Any help would be appreciated.
    Thank you

    Since you are on a Mac if when you first set up your account you left out the i in Wilson nothing you do will change that. The REAL account name will always be alicewlson. Once an account is created you can't actually change the name of it. You can change the name that is displayed but not the REAL account name.
    Simplest thing to do is stop worrying about it. Everything is as it should be, that is except Wilson being spelled without the i.
    Lilac50 wrote:
    When I searched finder for "alicewlson" I found a long list of files like this:
    2014-07-22 12.50/File005.nef[15:16:35.212] (debug) src/ImageLoader.cpp:363: File: /Users/alicewlson/Recovered/2014-07-22 12.50/File002.nef[15:18:02.173] (debug) src/StoreXMLFile.cpp:21: /Users/alicewlson//.rpro/rpro.cfg
    I believe I made the error in my user name when I first got my computer a year ago. I then corrected it under my user name but not in my Lightroom files. I also looked for files with a .lrdata extension and didn't find any.

  • Proper syntax of the file name to attach files in FNDATTCH.fmb

    Can you please tell me the proper syntax of the file name to attach files in FNDATTCH.fmb ?
    i am not able to open attached document if it contains & in the file name..So i wanted to know the rules to give the file name

    This has nothing to do with the TB display.  You should repost in the computer forum

  • Assign Logical file name for the physical file path through Program

    Hi all,
    I am having a physical file which is getting generated dynamically. It is having the date and time stamp in its name which is added at runtime.
    Now I need to assign a logical file name for the physical file path through the program.
    Is there any FM or any other method to assign the same.
    Gaurav

    I think it is not possible. becuase the date & time added at runtime. so if you check the table  PATH you can find filename and their definitions

  • How do I change the .php file name for a page of my site?

    how do I change the .php file name for a page of my site? The only link to the page is the nav. button link for it in the global nav. The reason I need to change the file name is we want the breadcrumbing name to change and the breadcrumbing is linked to the file name.

    The reason I need to change the file name is we want the breadcrumbing name to change and the breadcrumbing is linked to the file name.
    I don't understand this reason. How would changing the file extension solve your breadcrumb issue? Why don't you explain the issue in more detail.

  • Displaying File Name for Photo and Video Clips in Premiere Elements 10

    I am using Premier Elements 10 on a Windows 7 Pro desktop computer to create
    a project consisting of 128 jpg photo and mp4 video clips.  Before creating
    the project I created a short file name for each clip describing its
    content.  I've added menu tags at locations which separate the project into
    discrete segments.  I've selected a disc menu which utilizes the menu tags I
    created.  I previewed the project and I'm satisfied that the DVD disc I
    intend to create will display everything I want except for one thing.  I
    have spent several hours trying to find out how to have each displayed clip
    include the file name (without extension) somewhere near the edge of each
    window as it is opened in the finished production.  I sure would appreciate
    some help with the steps needed to accomplish this.

    Welcome to the forum.
    This can most easily be accomplished by adding a Title (maybe from a Lower-Thirds Title Template), above each Clip/Still Image.
    I would create one such Title, and manually add the "File Name" in the location desired. Then, place that on a higher Video Track, above the Clip/Still. Then, just use the Duplicate Title function, to create a new Title, with the Text and Style, per the first - edit the Text for each, as required.
    I know of no automated method to grab the Clip's/Still's File Name, and add that to a Title, as PrE does not support any scripting.
    Good luck,
    Hunt

  • Import tables using same file name for all tables

    hi,
    We are using oracle 11.2.0.3.0, we have taken export of multiple tables in schema, unfortunately in exp command we have mention same file name for all the tables, now it has created one file for all export but the size of that file shows that all the tables included in it , when we try to import the tables only last table mention in export command is imported for other tables it hangs, example of code show below.
    Is there any way to import the remaining tables.
    exp system file =exp05042013.dmp tables=gr.table1
    exp system file =exp05042013.dmp tables=gr.table2
    exp system file =exp05042013.dmp tables=gr.table3

    Hi,
    You can use as :
    exp username@database tables=table1,table2 file=tabledata.dmpDid you have any RMAN full backup?
    Why you are not recover crash database?
    Mahir

  • File names for photos on iPad?

    How do find the file name for photos in iPhoto on the iPad?

    To the best of my knowledge, you can't do it on the iPad. But after syncing, you can just click on a given photo in iPhoto and the name will appear in the "title" field in the Information box on the left-hand side of the iPhoto window.
    (Make sure you have that little icon of an "i" in a circle checked in the bottom left corner next to the search bar, or you won't see the Information pane.)

  • Unique Render File Name For Clips?

    How do I create a unique output file name for each clip in my timeline that is edited?
    Example:
    REEL_123.MOV appears 3 times on my timeline at different edit points. I need the output to  be REEL_123_1.MOV REEL_123_2.MOV etc. etc. Or something similar.
    I tried Src.FileName + General.RenderStartTime12hrs thinking that would give me a unique output name but it doesn't. Well, it kinda does, but if the clips are too close together on the timeline it looks like they all get created the same time resulting in a non-unique filename.
    Any suggestions?
    Cheers.

    Add General.EditNumberPadded.4 (from the Common catagory) as the first or the last string to your output name.

  • What are shortest file names for outlook express and PSE11 to import photos pls

    what are shortest file names for outlook express and PSE11 to import photos pls

    Hi, Troubled. The size of the file name is pretty much irrelevant here to PSE, but to answer your question directly, you will be able to import a file that has only a single character as its file name (plus the file name needs to have the required extension, such as .jpg)

  • Specifying file name for ServletOutputStream ?

    Hello,
    How can I specify a file name for a ServletOutputStream ? The code below always defaults to file name "MinimalBinaryStream" ?
    Thanks for your help !!!
    James
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class MinimalBinaryStream extends HttpServlet
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        doGet(request, response);
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/octet-stream");
        response.setContentLength(3);
        ServletOutputStream bout = response.getOutputStream();
        bout.write(0x31);
        bout.write(0x32);
        bout.write(0x33);
        bout.flush();
        bout.close();
    }

    Thanks nantucket,
    I have solved the problem by editing my "web.xml" file, for example:
    <web-app>
        <servlet-mapping>
            <servlet-name>MinimalBinaryStream</servlet-name>
            <url-pattern>/myfile.bin</url-pattern>
        </servlet-mapping>
    </web-app>

Maybe you are looking for