[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 652
  • Last Modified:

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

I have to send an Email in java script function which will be called when onUnload event occured.
1 Solution
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.
Vasanth_KumarAuthor Commented:
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.
Here is my source for server side script, it is implemented in Java

package com.mobinex.blog;

import java.io.IOException;
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 {
                        //java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                        Properties props = new Properties();
                    props.setProperty("mail.transport.protocol", "smtp");
                    props.setProperty("mail.smtp.host", 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_HOST = smtp.gmail.com
FROM_EMAIL = anemail@gmail.com
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 = '&toEmail=abc@gmail.com';
            new Ajax.Request(
                        onComplete: function() {
                              alert("Email is sent!");
Above I used a library called Prototype, you can read about this lib:
Or download:
Michel PlungjanIT ExpertCommented:
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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now