Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2007-11-13
10
Medium Priority
?
7,618 Views
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));
    message.addRecipient(Message.RecipientType.TO,
      new InternetAddress(to));
    message.setSubject("email subject");
    String mailmssg = "Hello World\n";
    mailmssg +=      "Hola Mundo\n";
    message.setText(mailmssg);
    Transport.send(message);
%>

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

0
Comment
Question by:elissaqp
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
10 Comments
 
LVL 5

Accepted Solution

by:
deeppra earned 500 total points
ID: 20277814
0
 
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

http://www.java2s.com/Code/Java/JSP/UploadingFilesinJSP.htm

>> 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.

http://www.java2s.com/Code/Java/Email/HowtousetheFileDataSourcetosendafileviamail.htm


0
 
LVL 3

Author Comment

by:elissaqp
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)
0
RHCE - Red Hat OpenStack Prep Course

This course will provide in-depth training so that students who currently hold the EX200 & EX210 certifications can sit for the EX310 exam. Students will learn how to deploy & manage a full Red Hat environment with Ceph block storage, & integrate Ceph into other OpenStack service

 
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
0
 
LVL 3

Author Comment

by:elissaqp
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?
0
 
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.
0
 
LVL 3

Author Comment

by:elissaqp
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";
0
 
LVL 27

Expert Comment

by:mrcoffee365
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/" ));


0
 
LVL 3

Author Comment

by:elissaqp
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.setSizeThreshold(4096);
factory.setRepository(new File("/www/websites/myweb/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(10000000);
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);
  //session.setDebug(debug);
 

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

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

      // 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));
      mbp2.setFileName(fds.getName());

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

      // add the Multipart to the message
      msg.setContent(mp);

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


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

Expert Comment

by:contactkarthi
ID: 20568193
0

Featured Post

Independent Software Vendors: 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!

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…
A solution for Fortify Path Manipulation.
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.

664 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