Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Java Mail and Attachment

Posted on 2004-10-26
9
Medium Priority
?
605 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
Comment
Question by:new2j4v4
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
9 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 100 total points
ID: 12414625
bodyPart.setContent(stringBuffer.toString(),"text/html");

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

Author Comment

by:new2j4v4
ID: 12414992
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
kiranhk earned 100 total points
ID: 12414998
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:new2j4v4
ID: 12415429
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
ID: 12415633
>>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
ID: 12415639
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
ID: 12415689
I got it, I was doing a wrong cast .

Thanks for the help
0
 

Author Comment

by:new2j4v4
ID: 12415718
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
ID: 12415727
8-)

>>I was doing a wrong cast .

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

Featured Post

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

636 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