Go Premium for a chance to win a PS4. Enter to Win


How to send an email with attachment on a JSP file?

Posted on 2007-11-13
Medium Priority
Last Modified: 2013-11-24
Dear experts,

I'm developing a JSP file where i can send emails, but i cannot get to send the attachment. These are the details.
file1.jsp -> Form where the user fill the information to send the mail (To, subject, body)
file2.jsp -> This is where the email is actually sent.

this is the code i'm using: (i'm not using servlets just jsp files)

    String host = "mailhost.mycompany.com";
    String from = "you@mymail.com";
    String to = "me@mymail.com";
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    Session session1 = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session1);
    message.setFrom(new InternetAddress(from));
      new InternetAddress(to));
    message.setSubject("email subject");
    String mailmssg = "Hello World\n";
    mailmssg +=      "Hola Mundo\n";

These are what i need:

1. How to create in the file1.jsp a browse button to upload the file?
2. How to send the attachment on file 2?

Please help me experts!!

Question by:elissaqp

Accepted Solution

deeppra earned 500 total points
ID: 20277814
LVL 23

Assisted Solution

by:Siva Prasanna Kumar
Siva Prasanna Kumar earned 500 total points
ID: 20277871
>> 1. How to create in the file1.jsp a browse button to upload the file?

You need to use commons upload framework for this. Or you can use this I believe


>> 2. How to send the attachment on file 2?

Then Once you get the uploaded File to the server use this program in a JSP suitably to send the mail with file attachment.



Author Comment

ID: 20280917
when trying to send the mail, i get the error:

javax.servlet.ServletException: Sending failed;
  nested exception is:
      javax.mail.MessagingException: IOException while sending message;
  nested exception is:
      java.io.FileNotFoundException: C:\web.txt (No such file or directory)
Industry Leaders: 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!

LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 20281014
The file you are trying to attach must not be reference using Drive names. As it is a web application you need to use files present in local folders like lets say img/2.gif.

whose location in web applciation will be parllel to that of WEB-INF folder of your application

i.e yourApp
     == WEB-IBF
     == img
          == 2.gif

Author Comment

ID: 20281355
Thanks for your quick answer but same error:
java.io.FileNotFoundException: images/calendario.gif (No such file or directory)

But how can i get that the file which user is uploading (file1.jsp) is going to be send on file2.jsp?
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 20281512
When the user uploads it will be stored on the server at some particular location you pass this location on the server to files2.jsp which will attach and sends the mail.

Author Comment

ID: 20283984
yes, that's correct but how to upload the file?

It is working when the file is on the web server, i've added this to the code:
String filename = "/www/websites/example/images/calendario.gif";
LVL 27

Expert Comment

ID: 20284011
When we do a file upload, we have to specify the physical file location where the uploaded file will go (if we are saving it on the server).  Then that physical file location would be used to reference the saved file for sending the email.

So, on a Windows system, the drive letter is required, e.g.,
c:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/
as the directory location of the uploaded file, and calendario.gif as the file name in that directory.

If you don't need to save the uploaded file, then you could just keep it in memory, and attach the file to the email from memory rather than the saved file location.

The error messages you're getting mean that the Java IO method cannot resolve your directory name on your server.  So, even if you don't save the file, you need to give a valid directory on the server as the location for the uploaded file.

Using jakarta commons fileupload, which is what we use, the commands are something like this:
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setRepository( new File("c:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/" ));


Author Comment

ID: 20292018
Finally this is the code i'm using but i need to refresh it several times so the file can be uploaded:

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
System.out.println("Is multipart="+isMultipart);
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File("/www/websites/myweb/"));
ServletFileUpload upload = new ServletFileUpload(factory);
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
FileItem fi = (FileItem)i.next();
String path="/www/websites/myweb/";
String fileName="nuevo.xls";
fi.write(new File(path, fileName));
String to = "me@mymail.com";
  String from = "you@mymail.com";
  String host = "mailhost.mymweb.com";
 String filename = "/www/websites/myweb/nuevo.xls";
 // boolean debug = Boolean.valueOf(args[4]).booleanValue();
  String msgText1 = "Sending a file.\n";
  String subject = "Sending a file";
  // create some properties and get the default Session
  Properties props = System.getProperties();
  props.put("mail.smtp.host", host);
  Session session1 = Session.getInstance(props, null);

      // create a message
      MimeMessage msg = new MimeMessage(session1);
      msg.setFrom(new InternetAddress(from));
      InternetAddress[] address = {new InternetAddress(to)};
      msg.setRecipients(Message.RecipientType.TO, address);

      // create and fill the first message part
      MimeBodyPart mbp1 = new MimeBodyPart();

      // create the second message part
      MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
      mbp2.setDataHandler(new DataHandler(fds));

      // create the Multipart and add its parts to it
      Multipart mp = new MimeMultipart();

      // add the Multipart to the message

      // set the Date: header
      //msg.setSentDate(new Date());
      // send the message

Any ideas why i need to execute the file several times, before the email is sent with the attachment?
LVL 17

Expert Comment

ID: 20568193

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

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

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…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

876 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