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

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 = "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!!

2 Solutions
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:
      java.io.FileNotFoundException: C:\web.txt (No such file or directory)
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

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:
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?
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)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?
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

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

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