How to send an email from jsp/servlet?
Asked Answered
B

4

8

How to send an email from JSP/servlet? Is it necessary to download some jars or can you send an email from JSP/servlets without any jars?

  • What would my Java code look like?

  • What would my HTML code look like (if any)?

  • Are multiple classes necessary, or can you use just one class?

Butterfish answered 21/9, 2010 at 5:4 Comment(4)
Google is bound to popular results. People use StackOverflow to get actual people opinion as opposed to Mountain View algorithms. That's the whole point of StackOverflow IMHO.Drifter
getting meta, that's the point of the point system. good q/a gets more points, shows up more in searches, etc...but, yes, better results (hopefully). similar idea to page rank, tho.Acherman
@NitheshChandra Google brought me here ;)Mulligrubs
@crm Things have changed in 4 years. Stackoverflow became the authoritative source for most programming problems so I don't think my earlier comment still applies.Handfast
C
23

The mailer logic should go in its own standalone class which you can reuse everywhere. The JSP file should contain presentation logic and markup only. The Servlet class should just process the request the appropriate way and call the mailer class. Here are the steps which you need to take:

  1. First decide which SMTP server you'd like to use so that you would be able to send emails. The one of your ISP? The one of Gmail? Yahoo? Website hosting provider? A self-maintained one? Regardless, figure the hostname, port, username and password of this SMTP server. You're going to need this information.


  2. Create a plain vanilla Java class which uses JavaMail API to send a mail message. The JavaMail API comes with an excellent tutorial and FAQ. Name the class Mailer and give it a send() method (or whatever you want). Test it using some tester class with a main() method like this:

    public class TestMail {
        public static void main(String... args) throws Exception {
            // Create mailer.
            String hostname = "smtp.example.com";
            int port = 2525;
            String username = "nobody";
            String password = "idonttellyou";
            Mailer mailer = new Mailer(hostname, port, username, password);
    
            // Send mail.
            String from = "[email protected]";
            String to = "[email protected]";
            String subject = "Interesting news";
            String message = "I've got JavaMail to work!";
            mailer.send(from, to, subject, message);
        }
    }
    

    You can make it as simple or advanced as you want. It doesn't matter, as long as you have a class with which you can send a mail like that.


  3. Now the JSP part, it's not entirely clear why you mentioned JSP, but since a JSP is supposed to represent only HTML, I bet that you'd like to have something like a contact form in a JSP. Here's a kickoff example:

    <form action="contact" method="post">
        <p>Your email address: <input name="email"></p>
        <p>Mail subject: <input name="subject"></p>
        <p>Mail message: <textarea name="message"></textarea></p>
        <p><input type="submit"><span class="message">${message}</span></p>
    </form>
    

    Yes, plain simple, just markup/style it whatever way you want.


  4. Now, create a Servlet class which listens on an url-pattern of /contact (the same as the form is submitting to) and implement the doPost() method (the same method as the form is using) as follows:

    public class ContactServlet extends HttpServlet {
        private Mailer mailer;
        private String to;
    
        public void init() {
            // Create mailer. You could eventually obtain the settings as
            // web.xml init parameters or from some properties file.
            String hostname = "smtp.example.com";
            int port = 2525;
            String username = "nobody";
            String password = "forgetit";
            this.mailer = new Mailer(hostname, port, username, password);
            this.to = "[email protected]";
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String email = request.getParameter("email");
            String subject = request.getParameter("subject");
            String message = request.getParameter("message");
            // Do some validations and then send mail:
    
            try {
                mailer.send(email, to, subject, message);
                request.setAttribute("message", "Mail succesfully sent!");
                request.getRequestDispatcher("/WEB-INF/contact.jsp").forward(request, response);
            } catch (MailException e) {
                throw new ServletException("Mailer failed", e);
            }
        }
    }
    

    That's it. Keep it simple and clean. Each thing has its own clear responsibilities.

Coeval answered 21/9, 2010 at 12:41 Comment(4)
The JavaMail API is full of static method calls that will make your code hard to test. If you have the option of using Spring, check out the MailSender API (static.springsource.org/spring/docs/3.0.x/…).Speculative
It looks like your send(from, to, subject, message) is a little different from oracle.com/webfolder/technetwork/tutorials/obe/java/javamail/… (sendMail method).Spermiogenesis
What was your Mailer's send() method look like?Spermiogenesis
The message is sent from our own mail server? Like, I go to my GMail, compose a letter and send it to my self... it's the equivalent. Is this right, @Coeval ?Tabescent
A
4

You can send mail from jsp or servlet as we send from class file using java mail api. Here is link which will help you for that:

http://www.java-samples.com/showtutorial.php?tutorialid=675

Ankerite answered 21/9, 2010 at 7:19 Comment(0)
I
2

I'm using javamail package and it works very nice. The samples shown above are good but as I can see they didn't define parameters in external file (for example web.xml) which is recommended...

Imagine that you want to change your email address or SMTP host .. It is much easier to edit web.xml file than 10 servlets where you used mail function. For example add next lines in web.xml

<context-param>
<param-name>smtp_server</param-name>
<param-value>smtp.blabla.com</param-value></context-param>

Then you can access those parameters from servlet with

// 1 - init
    Properties props = new Properties();
    //props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", smtp_server);
    props.put("mail.smtp.port", smtp_port); 
Inclined answered 21/9, 2010 at 12:5 Comment(0)
U
1

JSP page:

<form action="mail.do" method="POST">
<table>
    <tr>
    <td>To Email-id :<input type="text" name="email" /></td> <!--enter the email whom to send mail --> 
    <td><input type="submit" value="send"></input></td>
    </tr>
</table>
</form>

Here's the Servlet code:

String uri=req.getRequestURI();

if(uri.equals("/mail.do"))
        {
            SendEmail sa=new SendEmail();
                        String to_mail=request.getParameter("email");
                        String body="<html><body><table width=100%><tr><td>Hi this is Test mail</td></tr></table></body></html>";
            sa.SendingEmail(to_email,body);

        }

And the SendEmail class:

 package Email;

import java.util.Properties;

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;

public class SendEmail {

    public void SendingEmail(String Email,String Body) throws AddressException, MessagingException
    {

             String host ="smtp.gmail.com";
             String from ="yourMailId";  //Your mail id
             String pass ="yourPassword";   // Your Password
             Properties props = System.getProperties();
             props.put("mail.smtp.starttls.enable", "true"); // added this line
             props.put("mail.smtp.host", host);
             props.put("mail.smtp.user", from);
             props.put("mail.smtp.password", pass);
             props.put("mail.smtp.port", "25");
             props.put("mail.smtp.auth", "true");
             String[] to = {Email}; // To Email address
             Session session = Session.getDefaultInstance(props, null);
             MimeMessage message = new MimeMessage(session);
             message.setFrom(new InternetAddress(from));
             InternetAddress[] toAddress = new InternetAddress[to.length];        
             // To get the array of addresses
              for( int i=0; i < to.length; i++ )
              { // changed from a while loop
                  toAddress[i] = new InternetAddress(to[i]);
              }
             System.out.println(Message.RecipientType.TO);
             for( int j=0; j < toAddress.length; j++)
             { // changed from a while loop
             message.addRecipient(Message.RecipientType.TO, toAddress[j]);
             }
             message.setSubject("Email from SciArchives");

             message.setContent(Body,"text/html");
             Transport transport = session.getTransport("smtp");
             transport.connect(host, from, pass);
             transport.sendMessage(message, message.getAllRecipients());
                 transport.close();
        }
    }
Unmitigated answered 20/12, 2013 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.