How to attach a word file in JAVA mail? Please help

I am a JAVA rookie and I have problem attaching a word file using javamail. I searched almost all the forum but still couldn't find the solution.
Sorry for the reposting. But can anybody please help me out? Your any words or links will be highly appreciated!
Lakobe

If you want to include an attachment with your message, you need to build up the parts, quite literally, because the name of the applicable interface is Part. The content of your Message will consist of multiple parts within a Multipart object. Part one of the message is a BodyPart that contains the message content. Part two of the message is a BodyPart that contains the attachment. The attachment itself is specified as a DataSource. You don't have to actually read the attachment.
You start in the same way as you do for a message without an attachment. Create the message from the session and initialize the headers:
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("JDC Attachment");
However here you need to create the Multipart object:
Multipart multipart = new MimeMultipart();
For part one, create a BodyPart and set the text to be a message. Then, add the BodyPart to the Multipart you just created.
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
multipart.addBodyPart(messageBodyPart);
For part two, you need to create a BodyPart again, but this time you need to create a DataSource for the file.
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
Use a DataHandler object to attach the data source to the message. Simply create a DataHandler for the source and attach it to the message:
messageBodyPart.setDataHandler(
new DataHandler(source));
Remember to set the filename of the attachment. This permits the recipient to know the name (and type) of the received file.
messageBodyPart.setFileName(filename);
Attach part two in the same way as part one:
multipart.addBodyPart(messageBodyPart);
And as a final step before sending, attach the Multipart to the Message:
message.setContent(multipart);

Similar Messages

  • How to attach a word file in JAVA mail

    I am a JAVA rookie and I have a problem in attaching a word file using javamail. I searched almost all the forum but still couldn't find the solution.
    Sorry for the reposting. But can anybody please help me out? Your any words or links will be highly appreciated!
    Lakobe

    Sorry, this forum is for questions about the javadoc tool.
    There won't likely be JavaMail experts here.
    I'm not sure where else to send you.

  • Can any one tell me how to attach a pdf file to the mail through workflow

    I have a smart which i am able  to convert it to a pdf file...now.. can any one tell me how to attach a pdf file to the mail through workflow

    Hi,
    To create the task for attachment
    Use the BOR SELFITEM and method NOTES_APPEND.
    The out come of this task contain a link called attachment with a clip attached. Clisk on that icon and choose the type of attachment u want . RAW , EXCEL , TXT , PDF... Then using the import icon u can attach the document u like.
    But the TYPE : OBJ.
    Similarly using NOTE_DISPLAY method u can display the documents u like.
    In any work item u have the facility to attach any atttchment for further circulation .
    Attchment @ WORKITEM
    1.Click the workitem for which you want to create the attchment
    2.Press create attachment
    3. Add the attachment u like (PDF)
    Reward points for useful answer.
    Richard A

  • How to attach a single file in e-mail (Yosemite)?

    When i am writing a new mail and i try to attach a single file that i have saved a minute ago from certain folder i cannot do that. When i click on the folder to open it and select the specific file to attach, the mail does not open the folder but automatically attach the whole folder to e-mail.
    Any help?
    Thanks.

    Hello dejanfromzagreb,
    That is interesting that it is grabbing the entire folder. Have you tried switching the view within the Finder window to Column View to select the right file to attach? Another alternative is to locate the file in Finder and drag it op top of the Email that you are preparing to attach it. Take a look at the article below. 
    Mail (Yosemite): Add attachments
    https://support.apple.com/kb/PH19142
    Regards,
    -Norm G. 

  • How to embedd Fusion Charts with XML files in java? Please help me.......

    Hi....iam trying to display Fusion Charts. Iam using Hibernate to bring data from database.
    what i want to do is to put data on xml, once my xml gets dynamic data from database, then it will be clubbed with swf files(fusion charts) to show graphs such as line charts,etc.
    I know wat to do. But big Question is how to do ?
    am i right in my Logic ?

    Hi
    Your approach seems to be right.
    Get the data using hibernate into your struts action ( if you are using struts ).
    Set the xml and any other property as request attribute.
    Embed the chart in JSP, by including FusionChartsRenderer.jsp ( found in download package ) and passing xml ( got from request attribute ) and other values as parameters to it.
    Please check the FusionCharts forum for some discussions on Struts, JSP implementation. ( /forum - you could use the search feature available there )
    Please refer to the documentation of FusionCharts as well. ( /docs )
    Hope this helps!
    Srividya

  • How to read a .wav file from a .jar  - Please Help!!!

    Hello,
    I know this is a stupid question but I keep having trouble doing this. My code is the following:
        Display display;
        Alert alert;
        InputStream stream;
        Player player;
    stream = getClass().getResourceAsStream("newalert.wav");
                player = Manager.createPlayer(stream, "audio/wav");
                player.prefetch();
                player.start();
    ...I'm running this Midlet on a Motorola A1000 and I keep getting the following exception:
    java.lang.IllegalArgumentException:
    stream is null
    I've created the .jad package using KToolBar of the J2ME WTK2.2 with the appropriate .wav file on res folder.
    What I'm doing wrong?
    Thanks,
    Paulo

    Hi
    If your stream is null, then the wav file cannot be reached. Try this code:
    stream = getClass().getResourceAsStream("/newalert.wav");If this doesn't work either, make sure your wav file is directly in the res directory and not in another subdirectory of it. I suggets not running your application directly from the phone until it works from the WTK emulator.
    Mihai

  • How to upload  a excel file in webdynpro? Please help!

    Hi Experts,
        I have a requirement where I need to upload a  excel file in my webdynpro for ABAP report.
        I have used the fileupload UI element in my view and a upload button.
        However when I test the application I found that it is getting file data as some junk value like below:
        ###ࡱ#################>########################################################################################################################################################################################################################################
      Why is that so?
      Is there any limitation with fileuplaod reading excel file?
      Do i have to use any encoding option?
      What is the alternative option to read excel file in ABAP webdynpro?
    Thanks
    Gopal

    Hi,
    Check this.. Write this code in Upload button 's method
    ********** Reading data from flat file ****************
      DATA lo_el_context TYPE REF TO if_wd_context_element.
      DATA ls_context    TYPE wd_this->element_context.
      DATA lv_datasource type xstring.
    * get element via lead selection
      lo_el_context = wd_context->get_element(  ).
    * get single attribute
      lo_el_context->get_attribute(
        EXPORTING
          name =  `DATASOURCE`
        IMPORTING
          value = lv_datasource ).
       CALL FUNCTION 'HR_KR_XSTRING_TO_STRING'
        EXPORTING
    *   FROM_CODEPAGE       = '8500'
          IN_XSTRING          = LV_DATASOURCE
    *   OUT_LEN             = '1'
       IMPORTING
         OUT_STRING          = LV_STRING.
    SPLIT LV_STRING AT CL_ABAP_CHAR_UTILITIES=>NEWLINE INTO TABLE IT_STR.
      LOOP AT IT_STR INTO LV_STRING.
        SPLIT LV_STRING AT CL_ABAP_CHAR_UTILITIES=>HORIZONTAL_TAB INTO TABLE FIELDS.
        READ TABLE FIELDS INTO LV_FIELD INDEX 1.                 " Reading 1st field
        ls_header-STATU = LV_FIELD.
         clear LV_FIELD.
        READ TABLE FIELDS INTO LV_FIELD INDEX 2.                " Reading 2st field
         ls_header-LIFNR = LV_FIELD.
         clear LV_FIELD.
        READ TABLE FIELDS INTO LV_FIELD INDEX 3.
         ls_header-BSART = LV_FIELD.
         clear LV_FIELD.
        READ TABLE FIELDS INTO LV_FIELD INDEX 4.
         ls_header-EKORG = LV_FIELD.
         clear LV_FIELD.
        READ TABLE FIELDS INTO LV_FIELD INDEX 5.
         ls_header-EKGRP = LV_FIELD.
         clear LV_FIELD.
        READ TABLE FIELDS INTO LV_FIELD INDEX 6.
         ls_header-BUKRS = LV_FIELD.
         clear LV_FIELD.
         APPEND wa to it.
        append ls_header to lt_header.
        clear: ls_header,wa.
        endloop.
        lo_nd_header->BIND_TABLE( lt_header ).
    Thanks,
    Ramesh
    Edited by: Rameshkumar Raamasamy on Dec 20, 2010 11:16 AM

  • How to parse a MS word file from JAVA

    How do i read the contents of MS word file in java? I know that FileInputStream can be used to read the contents in bytes but i need to parse the content of the file also so any pointers on this would be helpful for me.
    I have tried out the API given out by POI by apache but i am not able to figure any thing out of that so it would be very helpful if some posts a sample code for the above problem.

    but i am not able to figure any thing out of thatUse XML, as DrLJ just proposed. But be warned that if you are going to be dealing with Word documents you will have to spend some time learning how they are formatted, even the XML versions. Don't expect to just throw down a FileInputStream and have things happen automagically. It's a complicated format.

  • How to attach a text file as an attachment to email message?

    Hello Everybody,
    I have a .csv file, in which details about emp-id, emp-name, e-expenses for Reimbursement and email address are stored.
    My application reads this .csv file, and sends a mail to each employee with his id, salary details in text format. (by changing content type to "text/plain") The code is working fine. But,
    My problem is:
    The message is sent as message body to the end user.
    The end user / the person who receives this mail will not be a technical person. So,
    1) If he trys to take a print out of this e-mail, He get only half of it.(as no. of colums will be more than paper size).
    2) I am finding alignment problem. IF employee name is too big, other columns will shift to right and data will not be exactly under column header. (it is going in zig zag way)
    So, I thought sending text file with all the details as an attachment might do well.
    But, I don't know how to attach a text file to email-message body.
    code
    try
                   {               String s1="";
                                  File f1 = new File(the path);
                                  FileInputStream fstream = new FileInputStream(f1); //new
                                  BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
                                  int count=0;
                                  while((s1=br.readLine())!=null )
                                                 count++;
                                                 //out.println("within while loop "+count);
                                                 StringTokenizer st = new StringTokenizer(s1,",");
                                                 if ((st.hasMoreTokens())&&(count>1))
                                            String a=st.nextToken().trim();
                                                 String b=st.nextToken();
                                                 String c=st.nextToken();
                                                 String d=st.nextToken();
                                                 String e=st.nextToken();
                                                 String f=st.nextToken();
                                                 String g=st.nextToken();
                                                 String h=st.nextToken();
                                                 String i=st.nextToken();
                                                 String j=st.nextToken();
                                                 String k=st.nextToken();
                                                 String l=st.nextToken();
                                                 String m=st.nextToken();
                                                 String n=st.nextToken();
                                                 String o=st.nextToken();
                                                 String p=st.nextToken();
                                                 String q=st.nextToken();
                                                 String mail=st.nextToken();
                                                 String s=st.nextToken();
                                                 //out.println("b="+b+"c="+c+"d="+d+"e="+e+"f="+f+"mail="+mail);
                                                 %>
    <%
                                            String to =mail;
                                                 String from =request.getParameter("fromadd");                                        
                                                 String subject ="Statement of Expenses";
                                                 String smtp ="mail.xxxxxxxxxx.com";
                                                 String message="";                                        
                                                 message=message.concat("EMP ID");
                                                 message=message.concat("     ");
                                                 message=message.concat("Name");
                                                 message=message.concat("          ");
                                                 message=message.concat("Dept No.");
                                                 message=message.concat("     ");
                                                 message=message.concat("Acc No.");
                                                 message=message.concat("     ");
                                                 message=message.concat("*****************************************************************************************");     
                                                 message=message.concat(a);
                                                 message=message.concat("     ");
                                                 message=message.concat(b);
                                                 message=message.concat("          ");
                                                 message=message.concat(c);
                                                 message=message.concat("     ");
                                                 message=message.concat(d);
                                                 Properties props = System.getProperties();
                                                 // Puts the SMTP server name to properties object
                                                 props.put("mail.smtp.host", smtp);
                                                 // Get the default Session using Properties Object
                                                 Session session1 = Session.getDefaultInstance(props, null);
                                                 // Create a New message
                                                 MimeMessage msg = new MimeMessage(session1);
                                                 // Set the From address
                                                 msg.setFrom(new InternetAddress(from));
                                                 // Setting the "To recipients" addresses
                                            msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to, false));
                                            /* // Setting the "cc recipients" addresses
                                            msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse(cc, false));
                                            // Setting the "Bcc recipients" addresses
                                            msg.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(bcc, false)); */
                                            // Sets the Subject
                                            msg.setSubject(subject);
                                            // set the meaasge in HTML format
                                            msg.setContent(message,"text/plain");
                                            // Set the Date: header
                                            msg.setSentDate(new java.util.Date());
                                            // Send the message
                                            Transport.send(msg);
                                            // Display Success message
                                            result =result.concat("<tr><td>"+b+"</td>"+"<td>"+to+"</td></tr>");
                                                      }//end of if of hasmore element
                                       }// end of while loop
                        out.println(result);                    
    }catch(Exception e)
                        // If here, then error in sending Mail. Display Error message.
                        result="Unable to send your message";
                        out.println("e="+e);
    Any help will be appreciated.
    Thanks and regards.
    Ashvini

    <html>
    <p>
    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText("Your Messages");
    MimeBodyPart mbp2 = new MimeBodyPart();
    FileDataSource fds = new FileDataSource("Your Attachments");
    mbp2.setDataHandler(new DataHandler(fds));
    mbp2.setFileName(fds.getName());
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);
    mp.addBodyPart(mbp2);
    msg.setContent(mp);
    msg.saveChanges();
    msg.writeTo(System.out);
    msg.setSubject(subject);
    Transport.send(msg);
    </p>
    <B><U>See you can add above code in your program and see the magic</U></B>
    Bye
    regards--
    Ashish
    </html>

  • How to read MS Word file

    Hi,
    How can i read MS word file in java ? My problem is that want to read .doc file and convert this .doc file into .txt tile . I was try with Jakarata POI , but i m not found out POI ?
    How to use Jakarata POI for reading .doc file ?
    Thanks in advance
    madhu
    [email protected]

    I believe your looking for the <input type="file" tag to read a file from the user's browser to the servlet. There are examples of this on line. POI is used after the file is read into the servlet to extract its information.

  • How to read an ARPA file in java

    Hi
    Im new in java and dont know many thing about it, I want to know how can read an ARPA file in java.
    pleas describ it step bye step and esy to understand.
    Edited by: 836719 on Feb 14, 2011 8:15 PM

    836719 wrote:
    ok i explain what i want to do maybe u can help me more,
    i want to read an arpa file and search it to find for example a word.so u think which method that u mentioned above is beter???
    It will be pleasure if u have any tip that can help me.1. Learn the basics of programming as well as how to logically construct and deconstruct a problem domain.
    2. Learn the basics of programming java.
    3. Learn about java.io.*
    4. Learn about java swing
    5. Find documentation that describes the format of the ARPA file.
    6. Read the documentation and understand it.
    7. Find a source for ARPA files (if this is online then there is more java to learn as well.)
    8. Use 1,2 and 3 to write java code that consumes the ARPA file.
    9. Use 4 to ask the user for a word.
    10. Use 1 and 2 to write code that 'searches' what you read in 8.

  • Uplod word file from java

    how we upload word file from java web page?? pls is urgent.

    > i not understand. pls explain?
    Ok. Take a look at the Fundamentals-forum where your post is in. If you look at the 30 most recent threads there are more tthen 10 thread about uploading files. A couple of those have some usefull answers which you probably can use.
    It's always a good habit to search a forum first before you post your question.
    Good luck.

  • Word Files in Java

    Hi everybody,
    I know this question has probably been asked a zillion and one times before, but I think I might be putting a bit of a new spin on it.
    Anyway, I was looking at the Jakarta API's to read and write Microsoft Word Files in Java, and I couldn't make heads or tails of them. Since they have packages you import, though, that means that there must be some Java solution to the problem. So, my question is this--does anyone here know of any Java stream classes, depreciated or otherwise, that can read Microsoft Word's encoding? I've heard rumors that some depreciated classes might be able to do the job; if I'm just completely wrong I'd appreciate it if someone would correct me so I'm not clinging to false hope. Failing an answer to that question, does anyone know if it's possible to get source code of the Jakarta packages?
    Thanks,
    Jezzica85

    Thanks TuringPest,
    I feel a bit stupid for saying this, but I can't make any sense of their source code either or tell which files are supposed to be for Microsoft Word; maybe it's just because of how it's written.
    What exactly does a proprietary format mean? I think I've heard the term, but I'm not sure.
    I'm starting to think my idea of writing some of my own code is too ambitious, but I thought this might be simple. All I want to do is get text out of a Word file, I don't want to open a file to edit it, and I don't care about formatting. Maybe if I understood the file format I could get myself started, I hope I don't sound like a broken record.
    Actually, I've written a macro into Microsoft Word that saves as a text file, so I can do it that way, I was just hoping there might be an easier way so I wouldn't need to deal with the extra file--is this probably the best way to go anyway?
    Thanks again,
    Jezzica85
    Message was edited by:
    jezzica85

  • Attach a word file into transaction me52n

    Hi all,
    i have a report that should  attach a word file into transaction me52n.
    is anyone know how can i do that?
    thanks in advanced,
    dana.

    You can attach documents to purchase orders using the object services button that appears by itself on the title line of the screen above the normal button bar.
    To do this in a program - there are a number of class methods - look at classes beginning with CL_GOS*
    Andrew

  • How to call a .bat file from java code?

    How to call a .bat file from java code? and how can i pass parameters to that .bat file?
    Thanks in advance

    thanks for ur reply
    but still i am getting the same error.
    I am trying to run a .bat file of together tool, my code looks like below
    import java.lang.Runtime;
    import java.lang.Process;
    import java.io.File;
    class SysCall{
         public static void main(String args[]){
              String cmd="D://Borland//Together6.2//bin//Together.bat -script:com.togethersoft.modules.qa.QA -metrics out:D://MySamples//Metrics// -fmt:html D://Borland//Together6.2//samples//java//CashSales//CashSales.tpr";
              //String path="D://Borland//Together6.2//bin//Together.bat ";
              Runtime r= Runtime.getRuntime(); //Declare the system call
              try{
                   System.out.println("Before batch is called");
                   Process p=r.exec(cmd);
                   System.out.println(" Exit value =" + p.exitValue());
                   System.out.println("After batch is called");
              /*can produce errors which must be caught*/
              catch(Exception e) {
                   e.printStackTrace();
                   System.out.println (e.toString());
    I am getting the below exception
    Before batch is called
    java.lang.IllegalThreadStateException: process has not exited
    at java.lang.Win32Process.exitValue(Native Method)
    at SysCall.main(SysCall.java:17)
    java.lang.IllegalThreadStateException: process has not exited

Maybe you are looking for

  • Form field displaying but not in session state

    I have a form which displays data depending on node selected in a tree. The data displays ok and allows me to update but If I try to access a value ( I want to filter a select list ) its empty. Displaying all session values reveals that only the prim

  • HR-SRM question

    Can someone please explain to me the differences between a Standard Organization Sturcture in SRM and the one HR organization structure? We have our users assigned to two clients.And that has really confused me.:)) Moreover..how are the attributes af

  • Urgent: Message not transmitted from AFW to Integration server

    We have trouble with some settings where the message is picked up by the communication channel and passed to the AFW. But, it gets stuck here with an error message "Transmitting the message to endpoint http://<J2EEServer>:<J2EE-Server-Port>/sap/xi/en

  • Printer profile for non canon paper

    Is there a list of profiles for Epson, Kodak, OfficeMax, etc photo papers?

  • Using OR in Contains

    hi .. Using contains i want to search for record containing any word from the given string.... i.e if i use select count(*) title from docs where contains(text,'first',1) > 0 i want the records containing first or document... Where should i place thi