How to send an Email in JavaScript function which will be called when onUnload event occured?

Posted on 2006-05-23
Last Modified: 2008-02-01
I have to send an Email in java script function which will be called when onUnload event occured.
Question by:Vasanth_Kumar
    LVL 12

    Expert Comment

    You can call a mailto: link onunload, but that only opens the e-mail in the client's email program of choice.  To send an e-mail discreetly (no user interaction) you have to use server side scripting.

    Author Comment

    To send an e-mail discreetly (no user interaction) ,I have to use server side scripting.Can we execute that server side scripting in javascript function which will be called when onUnload event occured?

    My actual requirement is that when i am leaving the current page to another page by clicking back or forward buttons
    and by closing the window and by clicking any one of the href links in the current page , then i have to send the Email.
    Can u give me the idea how to do that.
    LVL 1

    Accepted Solution

    Here is my source for server side script, it is implemented in Java


    import java.util.Properties;
    import java.util.ResourceBundle;

    import javax.activation.DataHandler;
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.Multipart;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.lang.StringUtils;

     * Servlet implementation class for Servlet: SendMailServlet
     public class SendMailServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
          private static String      EMAIL_HOST;
          private static String      FROM_EMAIL;
          private static String      USER;
          private static String      PWD;
                ResourceBundle bundle = ResourceBundle.getBundle("appConfiguration");
                EMAIL_HOST = bundle.getString("EMAIL_HOST");
                FROM_EMAIL = bundle.getString("FROM_EMAIL");
                USER = bundle.getString("EMAIL_USER");
                PWD = bundle.getString("EMAIL_PWD");
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doPost(request, response);

          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                String toEmail = request.getParameter("toEmail");
                String fromEmail = request.getParameter("fromEmail");
                String bodyText = request.getParameter("text");
                if(StringUtils.isEmpty(fromEmail)) {
                      fromEmail = FROM_EMAIL;
                if(StringUtils.isNotEmpty(toEmail)) {
                      try {
                            Properties props = new Properties();
                        props.setProperty("mail.transport.protocol", "smtp");
                        props.setProperty("", EMAIL_HOST);
                        props.setProperty("mail.port", "465");
                        props.put("mail.smtp.starttls.enable", "true");
                        props.put("mail.smtp.auth", "true");
                            Session session = Session.getInstance(props, new MyPasswordAuthenticator(USER, PWD));
                            MimeMessage message = new MimeMessage(session);
                            message.setFrom(new InternetAddress(fromEmail));
                            // get recipient's emails
                            String[] emails = toEmail.split(",");
                            if((emails == null) || (emails.length <= 0)) {
                                  throw new Exception("Invalid Email Addresses!");
                            for(int emailIdx = 0; emailIdx < emails.length; emailIdx++) {
                                  message.addRecipient(Message.RecipientType.TO, new InternetAddress(emails[emailIdx]));
                            //      Setting the Subject and Headers
                            message.setSubject("Invitation Email From Mobinex Blog Site");
                            //Setting the Message body
                            String body = "";
                            if(StringUtils.isEmpty(bodyText)) {
                                  body = "This is a test email";
                            } else {
                                  body = bodyText;
                            Multipart mailBody = new MimeMultipart();
                            MimeBodyPart mainBody=new MimeBodyPart();
                            mainBody.setDataHandler(new DataHandler(body, "text/plain"));
                      } catch(Exception ex) {

          /** This is the authenticator for SMTP session */
          public static class MyPasswordAuthenticator extends Authenticator {
                private String username = null;

                private String password = null;

                public MyPasswordAuthenticator(String username, String password) {
                      this.username = username;
                      this.password = password;

                public PasswordAuthentication getPasswordAuthentication() {
                      return new PasswordAuthentication(username, password);

    Here is the configuration:
    EMAIL_USER = email_user
    EMAIL_PWD = email_pwd

    You create a sendEmail function in your Javascript side, like this:
    function sendEmail() {
                var servletUrl = './SendMailServlet';
                var params = '&';
                new Ajax.Request(
                            onComplete: function() {
                                  alert("Email is sent!");
    Above I used a library called Prototype, you can read about this lib:
    Or download:
    LVL 75

    Expert Comment

    by:Michel Plungjan
    And to make sure you send it, you would have to open the fully qualified url to the program in a new window which can be blocked by popup blockers...
    I will want to see the ajax method actually run over the net on a standard box since onUnload may unload all scripts before they are executed

    What is the aim of this email?

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    "That which we persist in doing becomes easier, not that the task itself has become easier, but that our ability to perform it has improved." Ralph Waldo Emerson Introduction: One of the wonderful things about the web is that it makes it s…
    Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
    The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
    The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

    729 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

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now