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

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 = "";
    String from = "";
    String to = "";
    Properties props = System.getProperties();
    props.put("", 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!!

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
>> 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.

elissaqpAuthor Commented:
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: C:\web.txt (No such file or directory)
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
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
elissaqpAuthor Commented:
Thanks for your quick answer but same error: 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?
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
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.
elissaqpAuthor Commented:
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";
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/" ));

elissaqpAuthor Commented:
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);
String path="/www/websites/myweb/";
String fileName="nuevo.xls";
fi.write(new File(path, fileName));
String to = "";
  String from = "";
  String host = "";
 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("", 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?
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.

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.