-1

I need a coding for email with attachment using servlet. Please help me. I am new to Servlets & JSPs. I need JSP and Servlet coding both.

Here is what I have tried so far -

<%@page contentType="text/html" pageEncoding="UTF-8"%>        
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Sending email</title>
    <link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
    <center>        
        <form action="EmailServlet" method="post" name="ss">   
            <table>
                <tr>
                    <td>To</td>
                    <td><input type="text" name="to"></td>
                </tr>
                <tr>
                    <td>cc</td>
                    <td><input type="text" name="cc"></td>
                </tr>
                <tr>
                    <td>bcc</td>
                    <td><input type="text" name="bcc"></td>
                </tr>
                <tr>
                    <td>From</td>
                    <td><input type="text" name="from"></td>
                </tr>
                <tr>
                    <td>Subject</td>
                    <td><input type="text" name="subject"></td>
                </tr>
                <tr>
                    <td>attach</td>
                    <td><input type="file" name="file1"></td>
                </tr>
                <tr>
                    <td>attach2</td>
                    <td><input type="file" name="file2"></td>
                </tr>        
                <tr>
                    <td>Message</td>
                    <td><textarea cols="25" rows="8" name="message"></textarea></td>
                </tr>
                <tr>
                    <td>password</td>
                    <td><input type="password" name="password"></td>
                </tr>
            </table>
            <br>
            <input type="submit" value="submit" onclick=" return soora();">
        </form>
    </center>
</body>
</html>

MY Servlet page is:

import java.io.*;
import java.net.*;

import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;

public class EmailServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, 
                                  HttpServletResponse response)
                   throws IOException, ServletException {

        final String err = "/error.jsp";
        final String succ = "/success.jsp";

        String from = request.getParameter("from");
        String to = request.getParameter("to");
        String subject = request.getParameter("subject");
        String message = request.getParameter("message");
        String login = request.getParameter("login");
        String password = request.getParameter("password");

        try {
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            Authenticator auth = new SMTPAuthenticator(login, password);

            Session session = Session.getInstance(props, auth);

            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);

        } catch (AuthenticationFailedException ex) {
            request.setAttribute("ErrorMessage", "Authentication failed");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        } catch (AddressException ex) {
            request.setAttribute("ErrorMessage", "Wrong email address");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        } catch (MessagingException ex) {
            request.setAttribute("ErrorMessage", ex.getMessage());

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
        }
            RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
            dispatcher.forward(request, response);

    }

    private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }
}

I got error below like this:

java.lang.IllegalStateException: Cannot forward after response has been committed
EmailServlet.processRequest(EmailServlet.java:71)
EmailServlet.doPost(EmailServlet.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
MD Sayem Ahmed
  • 28,628
  • 27
  • 111
  • 178
ramesh mesh
  • 11
  • 1
  • 2

3 Answers3

0

Use commons-fileupload & commons-mail to do this job

jmj
  • 237,923
  • 42
  • 401
  • 438
0

You can use Java Mail for this, it's a free download. It's much the same in a servlet or JSP as it would be without, except that you can use context.xml and JNDI to get the connection intead of having to hard-code all that. But I'm not convinced you're ready for any of this if you don't know servlets or JSP.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

You're sending a forward to the err page in the catch blocks which will commit the response, but you're not returning from there, so the code continues to the bottom where you're sending another forward to the succ page. Effectively, you're sending two forwards in case of an exception and the second forward can't take place and causes the particular exception which you're facing.

You need to add return; to the end of catch blocks so that the method returns and don't execute the remaining of the code. See also java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

As to JavaMail not working, it would be more helpful if you print the stack trace of the real exception you're getting, so that you know more precisely what failed. Right now you're only setting the message as a request attribute (which apparently needs to show up in the forwarded error page) and you're concentrating on the "wrong" exception. Note that sending mails is not different in a servlet class than in a normal Java class. I'd suggest to put the servlet code aside and get it to work in a normal Java class first.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555