Java Mail and Attachment

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.

new2j4v4Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
CEHJConnect With a Mentor Commented:
bodyPart.setContent(stringBuffer.toString(),"text/html");

where 'stringBuffer' is a StringBuffer to which you've appended in your query
0
 
new2j4v4Author Commented:
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
 
kiranhkConnect With a Mentor Commented:
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
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
new2j4v4Author Commented:
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
 
CEHJCommented:
>>DataSource ds = (DataSource) new FileDataSource (sb.toString());//

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

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



0
 
kiranhkCommented:
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
 
new2j4v4Author Commented:
I got it, I was doing a wrong cast .

Thanks for the help
0
 
new2j4v4Author Commented:
I hope i have split it correctly. It says assist for one and accept for another

Thanks for ur help
0
 
CEHJCommented:
8-)

>>I was doing a wrong cast .

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

From novice to tech pro — start learning today.