• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 670
  • Last Modified:

Sending a pdf file as an attachment doubt in java

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
gaugeta
Asked:
gaugeta
  • 10
  • 8
1 Solution
 
for_yanCommented:
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
 
for_yanCommented:
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
 
gaugetaAuthor Commented:
@for_yan:Thanks for the reply.
I will try this and get back if i face any issues.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
for_yanCommented:
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
 
gaugetaAuthor Commented:
@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
 
gaugetaAuthor Commented:
@for_yan:Please ignore previous comment did not notice that you already specified.
Sorry for that.
0
 
for_yanCommented:
It's OK. No problem
0
 
gaugetaAuthor Commented:
@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
 
for_yanCommented:
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
 
for_yanCommented:
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
 
for_yanCommented:
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
 
gaugetaAuthor Commented:
@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
 
for_yanCommented:
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
 
for_yanCommented:
Javamail should be represented in your classpath by two jars - mail.jar and activation.jar - do you have those ?
0
 
gaugetaAuthor Commented:
@for_yan:Thanks for the reply.
After adding those jars the errors have gone.
I'll test the program and update the status.
0
 
gaugetaAuthor Commented:
@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
 
gaugetaAuthor Commented:
@for_yan:I solved the above issue.
Thanks a lot.
0
 
for_yanCommented:
Great!
I'm happy it worked for you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 10
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now