?
Solved

Sending a pdf file as an attachment doubt in java

Posted on 2011-10-14
18
Medium Priority
?
643 Views
Last Modified: 2012-05-12
Hi Experts...
I have a function which takes in string data and sends the content of the string as a html report in the body of the mail as shown below.
I want to send the same mail but also i want a pdf document say sample.pdf to be sent as an attachment with this mail.
How do i achieve this.
Please help...
public static void sendEmail(String htmlString, Vector OAEmailAddresses, String userAddress, String subject)
{
String adrFrom = userAddress;
String signature = "";
String sepp = System.getProperty("line.separator");
InternetAddress [] intAdd;
InternetAddress [] intAddcc;

intAdd = new InternetAddress[OAEmailAddresses.size()];
//intAddcc = new InternetAddress[emailAddressesCC.size()];

try 
{
		for(int j=0; j<OAEmailAddresses.size(); j++)
		intAdd[j] = new InternetAddress((String)OAEmailAddresses.elementAt(j));

		//for(int j=0; j<emailAddressesCC.size(); j++)
		//	intAddcc[j] = new InternetAddress((String)emailAddressesCC.elementAt(j));


		Properties props = new Properties();
		String host = "sendmail.mailserv.com"; 
		props.put("mail.smtp.host", host);
		Session session = Session.getDefaultInstance(props, null);
		Message msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(adrFrom));

		msg.setRecipients(Message.RecipientType.TO, intAdd);
		//msg.setRecipients(Message.RecipientType.CC, intAddcc);
		msg.setSubject(subject );

		msg.setSentDate(new java.util.Date());
		msg.setText(htmlString);
		msg.setHeader("Content-Type","text/html");  // this is important header

		Transport.send(msg);
}
catch (Exception e) 
{
		System.out.println("Error sending e-mail : " + e.toString()); e.printStackTrace(); 
}
System.out.println("E-mail message sent!");
}

Open in new window

0
Comment
Question by:gaugeta
  • 10
  • 8
18 Comments
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36967020
This is how you send email with attachments:

public void sendEmailWithAttachments(String from, String to, String subject,
String body, Vector attachments) {

     String adrFrom = from;
      String signature = "";
     String sepp = System.getProperty("line.separator");


      
       try {

	Properties props = new Properties();
	props.put("mail.smtp.host", mailer);
	Session session = Session.getDefaultInstance(props, null);
	    Message msg = new MimeMessage(session);
	    msg.setFrom(new InternetAddress(adrFrom));

   StringTokenizer st = new StringTokenizer(to,",;");
   InternetAddress [] toAdd;
   toAdd = new InternetAddress[st.countTokens()];
   int numAdd = 0;
   while(st.hasMoreTokens()){toAdd[numAdd] = new InternetAddress(st.nextToken());
            numAdd++;
     }



	    msg.setRecipients(Message.RecipientType.TO, toAdd);
	    msg.setSubject(subject);
	    msg.setSentDate(new Date());
  
  MimeMultipart mp = new MimeMultipart();
        MimeBodyPart [] bps;
     int numberOfParts = 1;
    if(attachments != null)numberOfParts = attachments.size() + 1;
      bps = new MimeBodyPart[numberOfParts];
     bps[0] = new MimeBodyPart();
       bps[0].setText(body);
      mp.addBodyPart(bps[0]);

     if(attachments != null && attachments.size() > 0){
     for(int ja=0; ja<attachments.size(); ja++){
       String attachmentFile = (String)attachments.elementAt(ja);
       bps[ja+1] = new MimeBodyPart();
       bps[ja+1].setDisposition(Part.ATTACHMENT);
     bps[ja+1].setFileName(attachmentFile.substring(attachmentFile.lastIndexOf("/")+1));
  bps[ja+1].setDataHandler(new DataHandler(new ByteArrayDataSource(new FileInputStream(attachmentFile),
"application/csv")));
    mp.addBodyPart(bps[ja+1]);
      }
    }
msg.setContent(mp);








	    Transport.send(msg);
           }
       catch (Exception e) {System.out.println("Error sending e-mail : " + e.toString()); e.printStackTrace(); }
     System.out.println("E-mail message sent!");


}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36967024
The above code sends csv file - but  I don't think it should matter
You may change this to
 bps[ja+1].setDataHandler(new DataHandler(new ByteArrayDataSource(new FileInputStream(attachmentFile),
"application/pdf")));

Vector attachments - filnemse of the attached fuiles


0
 

Author Comment

by:gaugeta
ID: 36967044
@for_yan:Thanks for the reply.
I will try this and get back if i face any issues.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 47

Expert Comment

by:for_yan
ID: 36967085
Sure, try and let me know - I'm mostly sending text attachemnet, bt I tghink binary files should also work.
Make sure you are using the latest JavaMail, as I'm afraid older javaMail had bug somewhere around this
attachemnet issues - was sending files but they simetimes were corrupted
0
 

Author Comment

by:gaugeta
ID: 36979513
@for_yan:In the vector for attachement do i just give the csv/pdf filename for the file to be attached to the mail.
Please help...
0
 

Author Comment

by:gaugeta
ID: 36979547
@for_yan:Please ignore previous comment did not notice that you already specified.
Sorry for that.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36980381
It's OK. No problem
0
 

Author Comment

by:gaugeta
ID: 36984509
@for_yan:I tried the code and i got the following errors in the following lines.
Please help...
1) mp.addBodyPart(bps[0]);
Error:The method addBodyPart(MimeBodyPart) in the type MimeMultipart is not applicable for the 
 arguments (MimeBodyPart)

2)bps[ja+1].setFileName(attachmentFile.substring(attachmentFile.lastIndexOf("/")+1));bps[ja+1].setDataHandler(new DataHandler(new ByteArrayDataSource(new FileInputStream(attachmentFile),"application/csv")));
Error:The constructor ByteArrayDataSource(FileInputStream, String) is undefined

3)mp.addBodyPart(bps[ja+1]);
The method setContent(Multipart) in the type Message is not applicable for the arguments 
 (MimeMultipart)

4)msg.setContent(mp);
The method setContent(Multipart) in the type Message is not applicable for the arguments 
 (MimeMultipart)

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36984536
That's extremely strange - I took it form the working code

What kind of JavaMail jars you have in the classpath ?

Can you post some bigger chunk of your code?
Potetntially even which I could try to compile

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36984576
check attentively and compare the imports - I'm afraid you have wriong imports

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

public class MailWithAttachment {

    public void sendEmailWithAttachments(String from, String to, String subject,
String body, Vector attachments) {

     String adrFrom = from;

      String signature = "";
     String sepp = System.getProperty("line.separator");



       try {

	Properties props = new Properties();
	props.put("mail.smtp.host", mailer);
	Session session = Session.getDefaultInstance(props, null);
	    Message msg = new MimeMessage(session);
	    msg.setFrom(new InternetAddress(adrFrom));

   StringTokenizer st = new StringTokenizer(to,",;");
   InternetAddress [] toAdd;
   toAdd = new InternetAddress[st.countTokens()];
   int numAdd = 0;
   while(st.hasMoreTokens()){toAdd[numAdd] = new InternetAddress(st.nextToken());
            numAdd++;
     }



	    msg.setRecipients(Message.RecipientType.TO, toAdd);
	    msg.setSubject(subject);
	    msg.setSentDate(new Date());

  MimeMultipart mp = new MimeMultipart();
        MimeBodyPart[] bps;
     int numberOfParts = 1;
    if(attachments != null)numberOfParts = attachments.size() + 1;
      bps = new MimeBodyPart[numberOfParts];
     bps[0] = new MimeBodyPart();
       bps[0].setText(body);
      mp.addBodyPart(bps[0]);

     if(attachments != null && attachments.size() > 0){
     for(int ja=0; ja<attachments.size(); ja++){
       String attachmentFile = (String)attachments.elementAt(ja);
       bps[ja+1] = new MimeBodyPart();
       bps[ja+1].setDisposition(Part.ATTACHMENT);
     bps[ja+1].setFileName(attachmentFile.substring(attachmentFile.lastIndexOf("/")+1));
  bps[ja+1].setDataHandler(new DataHandler(new ByteArrayDataSource(new FileInputStream(attachmentFile),
"application/csv")));
    mp.addBodyPart(bps[ja+1]);
      }
    }
msg.setContent(mp);








	    Transport.send(msg);
           }
       catch (Exception e) {System.out.println("Error sending e-mail : " + e.toString()); e.printStackTrace(); }
     System.out.println("E-mail message sent!");


}



}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36984667
You should have mail.jar and activation.jar form JavaMail in your classpath

That my code above  all compiled with these jars
(only one compliant - mailer of course should be specified; otherwise all methods were recognized and compiled)
0
 

Author Comment

by:gaugeta
ID: 36984767
@for_yan:Thanks for the reply.
I have JAVAMAIL 1.3.3 in my classpath.
The code which send attachments as weel is in the function sendEmailWithAttachments().
Please help...
import java.io.FileInputStream;
import java.sql.Date;
import java.util.Properties;
import java.util.Vector;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeMultipart;
import com.sun.xml.internal.ws.util.ByteArrayDataSource;

public class sendMail 
{
	/*-
	********************************************************************************************************** 
 	* Method Name : sendEmail
	* 
	* Purpose : This function sends the generated report to the Distribution List Personel.
 	*
	* Arguments : String,Vector,String,String
	*
	* Return Type : void
 	*********************************************************************************************************           
 	*/
	@SuppressWarnings("unchecked")
	public static void sendEmail(String htmlString, Vector OAEmailAddresses, String userAddress, String subject)
		{


			String adrFrom = userAddress;
			String signature = "";
	
			String sepp = System.getProperty("line.separator");

			InternetAddress [] intAdd;
			InternetAddress [] intAddcc;


			intAdd = new InternetAddress[OAEmailAddresses.size()];

			//intAddcc = new InternetAddress[emailAddressesCC.size()];



			try 
			{
					for(int j=0; j<OAEmailAddresses.size(); j++)
						intAdd[j] = new InternetAddress((String)OAEmailAddresses.elementAt(j));

					//for(int j=0; j<emailAddressesCC.size(); j++)
					//	intAddcc[j] = new InternetAddress((String)emailAddressesCC.elementAt(j));



					Properties props = new Properties();

					String host = "sendmailer.stu.com"; 
					props.put("mail.smtp.host", host);
					Session session = Session.getDefaultInstance(props, null);
					Message msg = new MimeMessage(session);
					msg.setFrom(new InternetAddress(adrFrom));


					msg.setRecipients(Message.RecipientType.TO, intAdd);
					//msg.setRecipients(Message.RecipientType.CC, intAddcc);
					msg.setSubject(subject );


					msg.setSentDate(new java.util.Date());

					msg.setText(htmlString);
					msg.setHeader("Content-Type","text/html");  // this is important header

					Transport.send(msg);
			}
			catch (Exception e) 
			{
				System.out.println("Error sending e-mail : " + e.toString()); e.printStackTrace(); 
			}
			System.out.println("E-mail message sent!");


}
	public void sendEmailWithAttachments(String from,Vector OAEmailAddresses, String subject,String body, Vector attachments) 
	{

		String adrFrom = from;
		String signature = "";
		String sepp = System.getProperty("line.separator");


		try 
		{

				Properties props = new Properties();
				String host = "sendmailer.stu.com"; 
				props.put("mail.smtp.host", host);
				Session session = Session.getDefaultInstance(props, null);
			    Message msg = new MimeMessage(session);
			    msg.setFrom(new InternetAddress(adrFrom));
			    
			    InternetAddress [] toAdd;
			    for(int j=0; j<OAEmailAddresses.size(); j++)
					toAdd[j] = new InternetAddress((String)OAEmailAddresses.elementAt(j));



				    msg.setRecipients(Message.RecipientType.TO, toAdd);
				    msg.setSubject(subject);
				    msg.setSentDate(new Date(0));
			  
				 MimeMultipart mp = new MimeMultipart();
			     MimeBodyPart [] bps;
			     int numberOfParts = 1;
			     if(attachments != null)numberOfParts = attachments.size() + 1;
			     bps = new MimeBodyPart[numberOfParts];
			     bps[0] = new MimeBodyPart();
			     bps[0].setText(body);
			     mp.addBodyPart(bps[0]);
			     
			    
			     if(attachments != null && attachments.size() > 0)
			     {
			    	 for(int ja=0; ja<attachments.size(); ja++)
			    	 {
			    		String attachmentFile = (String)attachments.elementAt(ja);
			    		bps[ja+1] = new MimeBodyPart();
			    		bps[ja+1].setDisposition(Part.ATTACHMENT);
			    		bps[ja+1].setFileName(attachmentFile.substring(attachmentFile.lastIndexOf("/")+1));bps[ja+1].setDataHandler(new DataHandler(new ByteArrayDataSource(new FileInputStream(attachmentFile),"application/csv")));
			    		mp.addBodyPart(bps[ja+1]);
			    	 }
			    }
			     msg.setContent(mp);
				 Transport.send(msg);
		}
		catch (Exception e) 
		{
			System.out.println("Error sending e-mail : " + e.toString()); e.printStackTrace(); 
			
		}
		System.out.println("E-mail message sent!");

} 	
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36984775
you should remove these - they casue your problem:

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeMultipart;
import com.sun.xml.internal.ws.util.ByteArrayDataSource;
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36984776
Javamail should be represented in your classpath by two jars - mail.jar and activation.jar - do you have those ?
0
 

Author Comment

by:gaugeta
ID: 36984825
@for_yan:Thanks for the reply.
After adding those jars the errors have gone.
I'll test the program and update the status.
0
 

Author Comment

by:gaugeta
ID: 36984957
@for_yan:I tried the code and it workked perfectly for sending the csv file.
But the content which was sent in html format as the body of the mail appears as the view source code as it would appear in a notepad.
Here instead of the html content the code is being displayed in the message body.
The code is shown below.

And if insert the foll lines:
msg.setText(htmlString);
msg.setHeader("Content-Type","text/html");  // this is important header
Then the html content is obtained but csv file attachment is missing.

I need a way to get both the things in the sendEmailWithAttachments() function.
Please help...
import java.io.FileInputStream;
import java.sql.Date;
import java.util.Properties;
import java.util.Vector;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;


public class sendMail 
{
	/*-
	********************************************************************************************************** 
 	* Method Name : sendEmail
	* 
	* Purpose : This function sends the generated report to the Distribution List Personel.
 	*
	* Arguments : String,Vector,String,String
	*
	* Return Type : void
 	*********************************************************************************************************           
 	*/
	@SuppressWarnings("unchecked")
	public static void sendEmail(String htmlString, Vector OAEmailAddresses, String userAddress, String subject)
		{


			String adrFrom = userAddress;
			String signature = "";
	
			String sepp = System.getProperty("line.separator");

			InternetAddress [] intAdd;
			InternetAddress [] intAddcc;


			intAdd = new InternetAddress[OAEmailAddresses.size()];

			//intAddcc = new InternetAddress[emailAddressesCC.size()];



			try 
			{
					for(int j=0; j<OAEmailAddresses.size(); j++)
						intAdd[j] = new InternetAddress((String)OAEmailAddresses.elementAt(j));

					//for(int j=0; j<emailAddressesCC.size(); j++)
					//	intAddcc[j] = new InternetAddress((String)emailAddressesCC.elementAt(j));



					Properties props = new Properties();

					String host = "sendmailer.stu.com"; 
					props.put("mail.smtp.host", host);
					Session session = Session.getDefaultInstance(props, null);
					Message msg = new MimeMessage(session);
					msg.setFrom(new InternetAddress(adrFrom));


					msg.setRecipients(Message.RecipientType.TO, intAdd);
					//msg.setRecipients(Message.RecipientType.CC, intAddcc);
					msg.setSubject(subject );


					msg.setSentDate(new java.util.Date());

					msg.setText(htmlString);
					msg.setHeader("Content-Type","text/html");  // this is important header

					Transport.send(msg);
			}
			catch (Exception e) 
			{
				System.out.println("Error sending e-mail : " + e.toString()); e.printStackTrace(); 
			}
			System.out.println("E-mail message sent!");


}
	public static void sendEmailWithAttachments(String from,Vector OAEmailAddresses, String subject,String body, Vector attachments) 
	{

		String adrFrom = from;
		String signature = "";
		String sepp = System.getProperty("line.separator");
		InternetAddress [] toAdd;

		toAdd = new InternetAddress[OAEmailAddresses.size()];
		
		try 
		{

				Properties props = new Properties();
				String host = "sendmailer.stu.com"; 
				props.put("mail.smtp.host", host);
				Session session = Session.getDefaultInstance(props, null);
			    Message msg = new MimeMessage(session);
			    msg.setFrom(new InternetAddress(adrFrom));
			    
			    
			    for(int j=0; j<OAEmailAddresses.size(); j++)
					toAdd[j] = new InternetAddress((String)OAEmailAddresses.elementAt(j));



				    msg.setRecipients(Message.RecipientType.TO, toAdd);
				    msg.setSubject(subject);
				    msg.setSentDate(new Date(0));
			  
				 MimeMultipart mp = new MimeMultipart();
			     MimeBodyPart [] bps;
			     int numberOfParts = 1;
			     if(attachments != null)numberOfParts = attachments.size() + 1;
			     bps = new MimeBodyPart[numberOfParts];
			     bps[0] = new MimeBodyPart();
			     bps[0].setText(body);
			     mp.addBodyPart(bps[0]);
			     
			    
			     if(attachments != null && attachments.size() > 0)
			     {
			    	 for(int ja=0; ja<attachments.size(); ja++)
			    	 {
			    		String attachmentFile = (String)attachments.elementAt(ja);
			    		bps[ja+1] = new MimeBodyPart();
			    		bps[ja+1].setDisposition(Part.ATTACHMENT);
			    		bps[ja+1].setFileName(attachmentFile.substring(attachmentFile.lastIndexOf("/")+1));bps[ja+1].setDataHandler(new DataHandler(new ByteArrayDataSource(new FileInputStream(attachmentFile),"application/csv")));
			    		mp.addBodyPart(bps[ja+1]);
			    	 }
			    }
			     msg.setContent(mp);
				 Transport.send(msg);
		}
		catch (Exception e) 
		{
			System.out.println("Error sending e-mail : " + e.toString()); e.printStackTrace(); 
			
		}
		System.out.println("E-mail message sent!");

} 	
}

Open in new window

0
 

Author Comment

by:gaugeta
ID: 36985045
@for_yan:I solved the above issue.
Thanks a lot.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36987192
Great!
I'm happy it worked for you.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
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 “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
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…
Suggested Courses
Course of the Month15 days, 15 hours left to enroll

850 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