Solved

Java Mail and Attachment

Posted on 2004-10-26
583 Views
Last Modified: 2013-11-24
I want to create a text file dynamically from database and send it as an attachment using java mail through a email.
How do I do this task. I have tried but keep getting some weird errors.

In the doget method of the servlet, how to convert the resultset output into an text attachment and associate it with the MimeBodyPart of java mail api.

0
Question by:new2j4v4
    9 Comments
     
    LVL 86

    Accepted Solution

    by:
    bodyPart.setContent(stringBuffer.toString(),"text/html");

    where 'stringBuffer' is a StringBuffer to which you've appended in your query
    0
     

    Author Comment

    by:new2j4v4
    sb is the String buffer iam using to store the Resultset as suggested.

    I do not know where i am wrong with the code below
                                                   
     String host = "smtphub.mydomain.com";
    String from = "me@me.com";//frCB;
    String to = "me@me.com";//toCB;
    String sub = "Subject";
          Properties props = System.getProperties();
          props.put("mail.smtp.host", host);
                      
          Session session1 = Session.getDefaultInstance(props, null);
                      
          Message message = new MimeMessage(session1);
          message.setFrom(new InternetAddress(from));
          message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
          message.setSubject(sub);
                      
    //                  Create the message part
           BodyPart messageBodyPart = new MimeBodyPart();
     // Fill the message
           messageBodyPart.setText("Here's the file");

     // Create a Multipart
           Multipart multipart = new MimeMultipart();

     // Add part one
                   multipart.addBodyPart(messageBodyPart);

                       //
    // Part two is attachment
                       //

     // Create second body part
           messageBodyPart = new MimeBodyPart();

                      
          DataSource ds = (DataSource) new ByteArrayDataSource(sb.toString(),"text/html");

     // Set the data handler to the attachment
                      
           System.out.println("EZtwo");
           String applicationType = "text/html";
                      
           messageBodyPart.setDataHandler((DataHandler) ds);
                      
    System.out.println("EZthree");                  
     // Set the filename
           messageBodyPart.setFileName("a.txt");
                      
          System.out.println("EZfour");

     // Add part two
           multipart.addBodyPart(messageBodyPart);

                      System.out.println("EZfive");
                       // Put parts in message
                       message.setContent(multipart);
                      System.out.println("EZsix");
                       // Send the message
                       Transport.send(message);


                      System.out.println("send Email");


    What is wrong with the code above i do not get exception but not even results
    thanks for help CEHJ
    0
     
    LVL 8

    Assisted Solution

    by:kiranhk
    http://www.osix.net/modules/article/?id=39

    import javax.mail.*;
     import javax.mail.internet.*;
     import javax.activation.*;
     import java.io.*;
     import java.util.Properties;
     public class MailClient
     {
     
     
         public void sendMail(String mailServer, String from, String to,
                                 String subject, String messageBody,
                                 String[] attachments) throws
    MessagingException, AddressException
         {
             // Setup mail server
             Properties props = System.getProperties();
             props.put("mail.smtp.host", mailServer);
             
             // Get a mail session
             Session session = Session.getDefaultInstance(props, null);
             
             // Define a new mail message
             Message message = new MimeMessage(session);
             message.setFrom(new InternetAddress(from));
             message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
             message.setSubject(subject);
             
             // Create a message part to represent the body text
             BodyPart messageBodyPart = new MimeBodyPart();
             messageBodyPart.setText(messageBody);
             
             //use a MimeMultipart as we need to handle the file attachments
             Multipart multipart = new MimeMultipart();
             
             //add the message body to the mime message
             multipart.addBodyPart(messageBodyPart);
             
             // add any file attachments to the message
             addAtachments(attachments, multipart);
             
             // Put all message parts in the message
             message.setContent(multipart);
             
             // Send the message
             Transport.send(message);
     
     
         }
     
         protected void addAtachments(String[] attachments, Multipart multipart)
                         throws MessagingException, AddressException
         {
             for(int i = 0; i<= attachments.length -1; i++)
             {
                 String filename = attachments[i];
                 MimeBodyPart attachmentBodyPart = new MimeBodyPart();
                 
                 //use a JAF FileDataSource as it does MIME type detection
                 DataSource source = new FileDataSource(filename);
                 attachmentBodyPart.setDataHandler(new DataHandler(source));
                 
                 //assume that the filename you want to send is the same as the
                 //actual file name - could alter this to remove the file path
                 attachmentBodyPart.setFileName(filename);
                 
                 //add the attachment
                 multipart.addBodyPart(attachmentBodyPart);
             }
         }
     
         public static void main(String[] args)
         {
             try
             {
                 MailClient client = new MailClient();
                 String server="pop3.mydomain.com";
                 String from="myname@mydomain.com";
                 String to = "someuser@somewhere.com";
                 String subject="Test";
                 String message="Testing";
                 String[] filenames =
    {"c:\somefile.txt"};
             
                 client.sendMail(server,from,to,subject,message,filenames);
             }
             catch(Exception e)
             {
                 e.printStackTrace(System.out);
             }
             
         }
     }
     

    0
     

    Author Comment

    by:new2j4v4
    Thanks for example Kiran but i want to know whats wrong

    with these statements

    messageBodyPart.setContent(sb.toString(),"text/html");
                      System.out.println("EZtwo");                   
                       //Get Attachment
                       DataSource ds = (DataSource) new FileDataSource (sb.toString());//(DataSource) new ByteArrayDataSource(sb.toString(),"text/html");

                       // Set the data handler to the attachment
                      System.out.println("EZthree");                   

                       //String applicationType = "text/html";
                      
                      // messageBodyPart.setDataHandler( new DataHandler(ds));
                      messageBodyPart.setDataHandler((DataHandler) ds);
                      
                      
                       // Set the filename
                       messageBodyPart.setFileName("a.txt");


    it gives a java.lang.ClassCastException

    0
     
    LVL 86

    Expert Comment

    by:CEHJ
    >>DataSource ds = (DataSource) new FileDataSource (sb.toString());//

    What's happening here? You've already set the attachment:

    >>messageBodyPart.setContent(sb.toString(),"text/html");



    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    your
    DataSource ds = (DataSource) new FileDataSource (sb.toString());
    is trying to create a data source with a file name which is sb.toString()

    read the constructor of FileDataSource

    http://java.sun.com/j2ee/sdk_1.3/techdocs/api/index.html
    0
     

    Author Comment

    by:new2j4v4
    I got it, I was doing a wrong cast .

    Thanks for the help
    0
     

    Author Comment

    by:new2j4v4
    I hope i have split it correctly. It says assist for one and accept for another

    Thanks for ur help
    0
     
    LVL 86

    Expert Comment

    by:CEHJ
    8-)

    >>I was doing a wrong cast .

    I'm not sure why that line is in at all (?)
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone. Privacy Policy Terms of Use

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Suggested Solutions

    Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
    Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
    Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
    Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

    860 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    13 Experts available now in Live!

    Get 1:1 Help Now