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

x
?
Solved

JSP - Problem sending form mail with attachment

Posted on 2008-10-09
8
Medium Priority
?
1,786 Views
Last Modified: 2013-11-24
I have an online email form which allows users to send an attachment. I have read through the following tutorials but I keep getting errors and I can't get my code to work.

The tutorial I have used are:
http://java.sun.com/developer/onlineTraining/JavaMail/contents.html#JavaMailAttachments
http://java.sun.com/developer/onlineTraining/JavaMail/exercises/MailAttach/solution/AttachExample.java
http://www.jguru.com/faq/view.jsp?EID=30251

The errors I keep getting are:
An error occurred at line: 13 in the jsp file: /submit2.jsp
Generated servlet error:
Duplicate local variable session

An error occurred at line: 13 in the jsp file: /submit2.jsp
Generated servlet error:
The constructor MimeMessage(HttpSession) is undefined

Do I need to create a location on the server for the uploaded file first and then attach to the email OR is it possible for the file to be stored in memory when uploaded? I would prefer the second option if possible.

Can someone please help me out.
<%@page import="java.util.*"%>
<%@page import="javax.mail.*"%>
<%@page import="javax.mail.internet.*"%>
<%@page import="javax.mail.internet.MimeMessage.RecipientType"%>
<%@page import="java.io.*"%>
<%@page import="java.util.Properties"%> 
<%@page import="java.lang.*"%>
<%@page import="javax.naming.*"%>
<%@page import="javax.activation.DataHandler"%>
<%@page import="javax.activation.DataSource"%>
<%@page import="javax.activation.FileDataSource"%>
<%@page import="java.util.Date"%>
<%
  String smtpServer = "mail.myhost.no"; // put here SMTP server address or IP you use for sending email
  request.setCharacterEncoding("UTF-8");
  
  // take the submitted form values from the request
  String toAddress = "me@myemail.no";
  String fromAddress = request.getParameter("epost");
  String hvaSlags = request.getParameter("onatype");
  String gjelder = request.getParameter("message"); 
  String produkt = request.getParameter("produkt");
  String viktighet = request.getParameter("grad");
  String navn = request.getParameter("navn");
  String adresse = request.getParameter("adresse");
  String postnr = request.getParameter("postnr");
  String poststed = request.getParameter("poststed");
  String telefon = request.getParameter("telefon");      
  String fileName = request.getParameter("file1");  //this is the name of the file from the form field
  boolean sessionDebug = false;
  
  // create some properties and get the default Session
  Properties props = new Properties();
  props.put("mail.smtp.host", smtpServer);
  
  try {
  Session session = Session.getInstance(props, null);
  
  //create a message
  MimeMessage message = new MimeMessage(session);  
  InternetAddress from = new InternetAddress(fromAddress);
  message.setFrom(from);  
  InternetAddress to = new InternetAddress(toAddress);
  message.addRecipient(Message.RecipientType.TO, to);  
  message.setSubject("Tilbakemelding");
  
  // create the Multipart
  Multipart multipart = new MimeMultipart();
    
  // create part 1 and fill the first message part
  BodyPart mbpText = new MimeBodyPart();
  mbpText.setText("Melding til Sjøkartverket\n" + 
                  "Hva Slags type melding: " + hvaSlags + 
		  "\nMelding gjelder: " + gjelder + 
		  "\nProdukt: " + produkt + 
		  "\nViktighet: " + viktighet + 
		  "\nNavn: " + navn + 
                  "\nAdresse: " + adresse + 
		  "\nPostnr: " + postnr + 
		  "\nPoststed: " + poststed + 
		  "\nTelefon: " + telefon + 
		  "\nEpost: " + fromAddress); 
  multipart.addBodyPart(mbpText);			  
 		  
  // create part 2, attach file
  mbpText = new MimeBodyPart();  
  DataSource source = new FileDataSource(fileName);
  mbpText.setDataHandler(new DataHandler(source));
  mbpText.setFileName(fileName);
  multipart.addBodyPart(mbpText);
  
  // add the Multipart to the message
  message.setContent(multipart);
  
  // set the Date: header
  message.setSentDate(new Date());
  
  Transport.send(message);
  
  }
  catch (MessagingException mex) {
       // Prints all nested (chained) exceptions as well
	  System.out.println("ERROR SENDING EMAIL:"+ mex);
           mex.printStackTrace();
		 
  }
%>
 
<html>
<p align="center">
  A Message has been sent by submit2.jsp<br>
   Check your inbox.
</p>
 
<p align="center">
   <a href="testmail.html">Click here to send another! - Hallelujah</a>
</p>
</html>

Open in new window

0
Comment
Question by:mbjorge
[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
  • 4
  • 4
8 Comments
 
LVL 25

Assisted Solution

by:Tomas Helgi Johannsson
Tomas Helgi Johannsson earned 750 total points
ID: 22677726
   Hi!

What you need to do is change the line 37 to
Session mysession = Session.getInstance(props, null)
and line 40 to
MimeMessage message = new MimeMessage(mysession);  

as the session variable is the default name used by the JSP HttpSession.

http://java.sun.com/products/javamail/javadocs/javax/mail/internet/MimeMessage.html

Regards,
  Tomas Helgi
0
 

Author Comment

by:mbjorge
ID: 22677852
Many thanks Tomas,

I have tried your suggestion and I still get errors.  I can't see what the problem is

org.apache.jasper.JasperException: Exception in JSP: /mailer2.jsp:43

40:  
41:   //create a message
42:   MimeMessage message = new MimeMessage(s);  
43:   InternetAddress from = new InternetAddress(fromAddress);
44:   message.setFrom(from);  
45:   InternetAddress to = new InternetAddress(toAddress);
46:   message.addRecipient(Message.RecipientType.TO, to);  
0
 
LVL 25

Expert Comment

by:Tomas Helgi Johannsson
ID: 22677961
change 43 to
message.addFrom(from);

setFrom does not take any parameters. see manual. :)

Regards,
   Tomas Helgi
0
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!

 

Author Comment

by:mbjorge
ID: 22678340
I have had a look at the manual.  

There is the setFrom(Address address) method which I have used in this form
     message.setFrom(new InternetAddress(fromAddress));

It has worked for emails without attachments.  Do you have any idea why?
0
 
LVL 25

Expert Comment

by:Tomas Helgi Johannsson
ID: 22678645
      Hi!

Sorry, that's right, it does take InternetAddress as parameter. My mistake.

Print out the error that you are getting by catching the exception and use
System.out.println(ex.getMessage()); where ex is the Exception instance.

InternetAddress uses strict parsing so it WILL fail with an exception if the address is in wrong syntax. Make sure that the email address is valid.

http://java.sun.com/products/javamail/javadocs/javax/mail/internet/InternetAddress.html#InternetAddress(java.lang.String)

Regards,
   Tomas Helgi
0
 

Author Comment

by:mbjorge
ID: 22680164
Many thanks,

That worked.  Now I have another error:

org.apache.jasper.JasperException: Exception in JSP: /mailer2.jsp:77

74:                
75:   // create part 2, attach file
76:   mbpText = new MimeBodyPart();  
77:   DataSource source = new FileDataSource(fileName);
78:   mbpText.setDataHandler(new DataHandler(source));
79:   mbpText.setFileName(fileName);
80:   multipart.addBodyPart(mbpText);

On line 77, I have used the filename of the attachment  from the form field
           String fileName = request.getParameter("file1");  

What I want is to get the filename and the file as an attachment to the email.  I'm not quite show how to do this.

Do you have a simpler way to send form mail with an attachment?
0
 
LVL 25

Accepted Solution

by:
Tomas Helgi Johannsson earned 750 total points
ID: 22685281
Take a look at this example:
http://www.java2s.com/Code/Java/Email/HowtousetheFileDataSourcetosendafileviamail.htm

Change the lines 77 and 79 accordingly
That is to
FileDataSource source = new FileDataSource(fileName);

mpbText.setFileName(source.getName());

Regards,
   Tomas Helgi
0
 

Author Comment

by:mbjorge
ID: 22685895
Many thanks...it works
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Shoutout to Emily Plummer (http://www.experts-exchange.com/members/eplummer26.html) for giving me this article! She did most of it, I just finished it up and posted it for her :)    Introduction In a previous article (http://www.experts-exchang…
Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

730 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