Send E-mail with JavaScript

Note:
I’m far away from my safe “pure JavaScript” world here – if someone have any comments on this approach i will gladly listen!


In this article I will give an example of how to send e-mail (with CC, Bcc and HTML body) from SharePoint with JavaScript and the help of some server-side files (two variants of the aspx-page and a code-behind .cs file placed in the Layouts directory of your 12′ hive). This approach requires server access for placing the files.

I will first show you how to create a simple “contact-form”, secondly i will show you how to send the contents of a DispForm as a HTML-bodied email (in a follow-up post).

The method used passes the variables collected with javascript to the server-side file “SendMailBySessvars.aspx” or “SendMailNewWindow.aspx”. This page uses javascript to populate some hidden controls. The hidden controls is used to pass the variables to the server-side code as javascript cannot pass it’s variables directly. When the controls are populated, the server-side code is called to do the actual sending of the e-mail.

I will provide two options for sending the email:

  • The current page redirects to the “SendMailBySessvars.aspx” – sends the email and redirects back.
  • A new window is opened – the email is sent – and the window is closed.

The server-side files

In your SharePoint server – add these files to your 12’hive (C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TEMPLATELAYOUTSSendMailWithJavascript)
IMG

The sourcecode for the files “SendMailBySessvars.aspx”, “SendMailNewWindow.aspx” and “SendMail.aspx.cs” is provided below. The file “sessvars.js” is found here.

SourceCode for “SendMailBySessvars.aspx” – used for sending mail in the current window

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SendMail.aspx.cs" Inherits="Enquiry" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<style>
.mailStatusMsg
{
	color:#666666;
	font-size:large;
	border:5px gray double;
	text-align:center;
}

</style>
<title>Send Mail</title>
</head>
<body>

<form id="formSendMail" runat="server">
	<div style="display:none">
		<asp:HiddenField ID="txtSMTP" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtSMTP_Port" runat="server"></asp:HiddenField>		
		<asp:HiddenField ID="txtEmailSubject" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtHtmlBody" runat="server"></asp:HiddenField>		
		<asp:HiddenField ID="txtFromEmail" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtToEmail" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtCCEmail" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtBccEmail" runat="server"></asp:HiddenField>
		<asp:HiddenField ID="txtNewWindow" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtShowSplash" runat="server"></asp:HiddenField>
		<asp:HiddenField ID="txtRedirUrl" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtTimer" runat="server"></asp:HiddenField>
		<asp:HiddenField ID="txtSuccessMsg" runat="server"></asp:HiddenField>
		<asp:HiddenField ID="txtErrorMsg" runat="server"></asp:HiddenField>		
		<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"/>
	</div>
</form>

<script type="text/javascript" src="sessvars.js"></script>
<script type="text/javascript">

if(sessvars.emailBySessvars!=undefined){
	if("<%=SendFunctionTriggered%>" != 1){
		document.getElementById('txtSMTP').value=sessvars.emailBySessvars.SMTP;
		document.getElementById('txtSMTP_Port').value=sessvars.emailBySessvars.SMTP_Port;
		document.getElementById('txtEmailSubject').value=sessvars.emailBySessvars.EmailSubject;
		document.getElementById('txtHtmlBody').value=sessvars.emailBySessvars.htmlBody;
		document.getElementById('txtFromEmail').value=sessvars.emailBySessvars.fromEmail;
		document.getElementById('txtToEmail').value=sessvars.emailBySessvars.toEmail;
		document.getElementById('txtCCEmail').value=sessvars.emailBySessvars.ccEmail;
		document.getElementById('txtBccEmail').value=sessvars.emailBySessvars.BccEmail;	
		document.getElementById('txtNewWindow').value="0";
		document.getElementById('txtShowSplash').value=sessvars.emailBySessvars.ShowSplash;
		document.getElementById('txtRedirUrl').value=sessvars.emailBySessvars.RedirUrl;
		document.getElementById('txtTimer').value=sessvars.emailBySessvars.RedirTimer;
		document.getElementById('txtSuccessMsg').value=sessvars.emailBySessvars.SuccessMsg;
		document.getElementById('txtErrorMsg').value=sessvars.emailBySessvars.ErrorMsg;
	
		// Clear sessvars 
		sessvars.$.clearMem();
		//if(confirm("Sessvars - send mail?")){
			document.getElementById('btnSubmit').click();
		//}
	}
}
</script>    
</body>
</html>

SourceCode for “SendMailNewWindow.aspx” – used for sending mail in new window

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SendMail.aspx.cs" Inherits="Enquiry" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<style>
.mailStatusMsg
{
	color:#666666;
	font-size:large;
	border:5px gray double;
	text-align:center;
}

</style>
<title>Send Mail</title>
</head>
<body>

<form id="formSendMail" runat="server">
	<div style="display:none">
		<asp:HiddenField ID="txtSMTP" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtSMTP_Port" runat="server"></asp:HiddenField>		
		<asp:HiddenField ID="txtEmailSubject" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtHtmlBody" runat="server"></asp:HiddenField>		
		<asp:HiddenField ID="txtFromEmail" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtToEmail" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtCCEmail" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtBccEmail" runat="server"></asp:HiddenField>
		<asp:HiddenField ID="txtNewWindow" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtShowSplash" runat="server"></asp:HiddenField>
		<asp:HiddenField ID="txtRedirUrl" runat="server"></asp:HiddenField>	
		<asp:HiddenField ID="txtTimer" runat="server"></asp:HiddenField>
		<asp:HiddenField ID="txtSuccessMsg" runat="server"></asp:HiddenField>
		<asp:HiddenField ID="txtErrorMsg" runat="server"></asp:HiddenField>		
		<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"/>
	</div>
</form>

<script type="text/javascript" src="sessvars.js"></script>
<script type="text/javascript">


if(window.opener!=undefined){
	if(window.opener.openInNewWindowAndEmail!=undefined){
		if("<%=SendFunctionTriggered%>" != 1){
			document.getElementById('txtSMTP').value=window.opener.openInNewWindowAndEmail.SMTP;
			document.getElementById('txtSMTP_Port').value=window.opener.openInNewWindowAndEmail.SMTP_Port;
			document.getElementById('txtEmailSubject').value=window.opener.openInNewWindowAndEmail.EmailSubject;
			document.getElementById('txtHtmlBody').value=window.opener.openInNewWindowAndEmail.htmlBody;
			document.getElementById('txtFromEmail').value=window.opener.openInNewWindowAndEmail.fromEmail;
			document.getElementById('txtToEmail').value=window.opener.openInNewWindowAndEmail.toEmail;
			document.getElementById('txtCCEmail').value=window.opener.openInNewWindowAndEmail.ccEmail;
			document.getElementById('txtBccEmail').value=window.opener.openInNewWindowAndEmail.BccEmail;	
			document.getElementById('txtNewWindow').value="1";
			document.getElementById('txtShowSplash').value=window.opener.openInNewWindowAndEmail.ShowSplash;
			document.getElementById('txtTimer').value=window.opener.openInNewWindowAndEmail.CloseWindowTimer;
			document.getElementById('txtSuccessMsg').value=window.opener.openInNewWindowAndEmail.SuccessMsg;
			document.getElementById('txtErrorMsg').value=window.opener.openInNewWindowAndEmail.ErrorMsg;
		
			//if(confirm("Window.opener - send mail?")){
				document.getElementById('btnSubmit').click();
			//}
		}else if("<%=SendFunctionTriggered%>" == 1){
			if(window.opener.openInNewWindowAndEmail.ShowSplash=="1"){
				var showSplashTime = "<%=redirTimer%>" * 1000; // Milliseconds
				setTimeout("self.close()", showSplashTime);
			}else if(window.opener.openInNewWindowAndEmail.ShowSplash=="0"){
				self.close();
			}
		}
	}
}
</script>    
</body>
</html>

SourceCode for SendMail.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class Enquiry : System.Web.UI.Page
{
public string SendFunctionTriggered = string.Empty;
public string UrlStatusFlagPrefix = string.Empty;
public string EmailSendStatus = string.Empty;
public int redirTimer = 0;

protected void Page_Load(object sender, EventArgs e)
{
// Do nothing
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SendFunctionTriggered = "1";
SendMail(txtToEmail.Value, txtFromEmail.Value, txtCCEmail.Value, txtBccEmail.Value, txtEmailSubject.Value, txtHtmlBody.Value);
if (txtRedirUrl.Value.IndexOf("?") > 0)
{
UrlStatusFlagPrefix = "&";
}
else
{
UrlStatusFlagPrefix = "?";
}

if (msg == "Successful")
{
EmailSendStatus = UrlStatusFlagPrefix + "Email=Success";
}
else
{
EmailSendStatus = UrlStatusFlagPrefix + "Email=Failure";
}

if (txtNewWindow.Value == "1") // Open new window to handle send mail operation
{
if (txtShowSplash.Value == "1")
{
statusMsgDisplay();
}
}
else // Handle send mail operation in current window
{
if (txtShowSplash.Value == "1")
{
// Show status msg
statusMsgDisplay();
}
else
{
Response.Redirect(txtRedirUrl.Value + EmailSendStatus);
}
}
}

public void statusMsgDisplay()
{
redirTimer = Convert.ToInt32(txtTimer.Value);
string newString = string.Empty;
if (msg == "Successful")
{
newString = txtSuccessMsg.Value.Replace("{0}", Convert.ToString(redirTimer));
Response.Write(newString);
if (txtNewWindow.Value != "1")
{
Response.Write("<Meta http-equiv=’REFRESH’ content=’" + redirTimer + ";URL=" + txtRedirUrl.Value + EmailSendStatus + "’/>");
}
}
else
{
redirTimer = redirTimer + 3;
newString = txtErrorMsg.Value.Replace("{0}", Convert.ToString(redirTimer));
newString = newString.Replace("{1}",msg);
Response.Write(newString);
if (txtNewWindow.Value != "1")
{
Response.Write("<Meta http-equiv=’REFRESH’ content=’" + redirTimer + ";URL=" + txtRedirUrl.Value + EmailSendStatus + "’/>");
}
}
}

public string msg = string.Empty;
public string SendMail(string toList, string from, string ccList, string bccList, string subject, string body)
{
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();

try
{
MailAddress fromAddress = new MailAddress(from);
message.From = fromAddress;
message.To.Add(toList);
if(ccList != null && ccList != string.Empty)
message.CC.Add(ccList);
if(bccList != null && bccList != string.Empty)
message.Bcc.Add(bccList);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;

smtpClient.Host = txtSMTP.Value;
smtpClient.Port = Convert.ToInt32(txtSMTP_Port.Value);
smtpClient.UseDefaultCredentials = true;
smtpClient.Send(message);
msg = "Successful";
}
catch (Exception ex)
{
msg = ex.Message;
}
return msg;
}
}
[/javascript]


Simple Contact form

IMG

As always we start like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

The file “sessvars.js” is found here.

Sourcecode for the contact form:

&lt;button id=&quot;showContactForm&quot; onclick=&quot;javascript:toggleContactForm();&quot;&gt;Contact me&lt;/button&gt;
&lt;div id=&quot;contactForm&quot; style=&quot;display:none&quot;&gt;
&lt;table style=&quot;width: 500px&quot; cellpadding=&quot;4&quot; cellspacing=&quot;0&quot;&gt;
&lt;tr&gt;
&lt;td valign=&quot;top&quot; style=&quot;width:100px&quot;&gt;Your name&lt;span class=&quot;ms-formvalidation&quot;&gt; *&lt;/span&gt;&lt;/td&gt;
&lt;td valign=&quot;top&quot;&gt;&lt;input id=&quot;customInputName&quot; type=&quot;text&quot; style=&quot;width: 300px&quot; /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign=&quot;top&quot; style=&quot;width:100px&quot;&gt;Your email&lt;span class=&quot;ms-formvalidation&quot;&gt; *&lt;/span&gt;&lt;/td&gt;
&lt;td valign=&quot;top&quot;&gt;&lt;input id=&quot;customInputEmail&quot; type=&quot;text&quot; style=&quot;width: 300px&quot; /&gt;&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td valign=&quot;top&quot; style=&quot;width:100px&quot;&gt;Message&lt;span class=&quot;ms-formvalidation&quot;&gt; *&lt;/span&gt;&lt;/td&gt;
&lt;td valign=&quot;top&quot;&gt;&lt;textarea id=&quot;customInputMessage&quot; rows=&quot;10&quot; style=&quot;width: 100%&quot;&gt;&lt;/textarea&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td colspan=&quot;2&quot; align=&quot;right&quot;&gt;
&lt;button onclick=&quot;javascript:emailBySessvars()&quot;&gt;Sessvars Send Email&lt;/button&gt;&amp;nbsp;
&lt;button onclick=&quot;javascript:openInNewAndEmail()&quot;&gt;New Window Send Email&lt;/button&gt;&amp;nbsp;
&lt;button onclick=&quot;javascript:toggleContactForm();&quot;&gt;Cancel&lt;/button&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/test/English/Javascript/sessvars.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
function toggleContactForm(){
$('#contactForm').find(&quot;:input:not(button)&quot;).each(function(){
	$(this).val('');
});
$('#showContactForm').toggle();
$('#contactForm').toggle();
}

function preSendCheck(){
var arrTovalidate = ['customInputName','customInputEmail','customInputMessage'];
$(&quot;div.ms-formvalidation&quot;).remove();
var preCheckOK = true;
$.each(arrTovalidate,function(){
	var field = $(&quot;#&quot; + this);
	if(field.val()==''){
		preCheckOK = false;
		field.parent().append(&quot;&lt;div class='ms-formvalidation'&gt;You must specify a value for this required field.&lt;/div&gt;&quot;)
	}
});
return preCheckOK ;
}

function emailBySessvars(){ // Current window redirect
var sendOK = preSendCheck();
if(sendOK ){
	var name = $(&quot;#customInputName&quot;).val();
	var email = $(&quot;#customInputEmail&quot;).val();
	var message = $(&quot;#customInputMessage&quot;).val();
		sessvars.emailBySessvars = {
		&quot;SMTP&quot;:&quot;insert your SMTP here&quot;,
		&quot;SMTP_Port&quot;:&quot;25&quot;,
		&quot;fromEmail&quot;:email,
		&quot;toEmail&quot;:&quot;insert the address to send the mail to here&quot;,
		&quot;ccEmail&quot;:&quot;&quot;,
		&quot;BccEmail&quot;:&quot;&quot;,
		&quot;EmailSubject&quot;:&quot;Contact form by Sessvars&quot;,
		&quot;htmlBody&quot;:&quot;Name: &lt;br&gt;&quot; + name + &quot;&lt;br&gt;Message:&lt;br&gt;&quot; + message,
		&quot;ShowSplash&quot;:&quot;1&quot;,
		&quot;RedirUrl&quot;:&quot;/test/English/Javascript/SendMailWithJavascript.aspx&quot;,
		&quot;RedirTimer&quot;:&quot;1&quot;,
		&quot;SuccessMsg&quot;:&quot;&lt;div class='mailStatusMsg'&gt;E-mail successfully sendt&lt;div style='font-size:small'&gt;Redirecting in {0} seconds&lt;/div&gt;&lt;/div&gt;&quot;,
		&quot;ErrorMsg&quot;:&quot;&lt;div class='mailStatusMsg'&gt;Error sending message&lt;div style='font-size:small'&gt;{1}&lt;br&gt;Redirecting in {0} seconds&lt;/div&gt;&lt;/div&gt;&quot;
		};
			window.location.href='/_layouts/SendMailWithJavascript/SendMailBySessvars.aspx';
	}
}

function openInNewAndEmail(){ // New window
var sendOK = preSendCheck();
if(sendOK){
	var name = $(&quot;#customInputName&quot;).val();
	var email = $(&quot;#customInputEmail&quot;).val();
	var message = $(&quot;#customInputMessage&quot;).val();
		openInNewWindowAndEmail = {
		&quot;SMTP&quot;:&quot;insert your SMTP here&quot;,
		&quot;SMTP_Port&quot;:&quot;25&quot;,
		&quot;fromEmail&quot;:email,
		&quot;toEmail&quot;:&quot;insert the address to send the mail to here&quot;,
		&quot;ccEmail&quot;:&quot;&quot;,
		&quot;BccEmail&quot;:&quot;&quot;,
		&quot;EmailSubject&quot;:&quot;Contact form by Window.opener&quot;,
		&quot;htmlBody&quot;:&quot;Name: &lt;br&gt;&quot; + name + &quot;&lt;br&gt;Message:&lt;br&gt;&quot; + message,
		&quot;ShowSplash&quot;:&quot;1&quot;,
		&quot;CloseWindowTimer&quot;:&quot;1&quot;,
		&quot;SuccessMsg&quot;:&quot;&lt;div class='mailStatusMsg'&gt;E-mail successfully sendt&lt;div style='font-size:small'&gt;Closing this window in {0} seconds&lt;/div&gt;&lt;/div&gt;&quot;,
		&quot;ErrorMsg&quot;:&quot;&lt;div class='mailStatusMsg'&gt;Error sending message&lt;div style='font-size:small'&gt;{1}&lt;br&gt;Closing in {0} seconds&lt;/div&gt;&lt;/div&gt;&quot;
		};
		newwindow=window.open('/_layouts/SendMailWithJavascript/SendMailNewWindow.aspx',
		'SendMail','location=no,menubar=no,resizable=no,scrollbars=no,titlebar=no,toolbar=no,width=300,height=125');
		toggleContactForm();
	}
}
&lt;/script&gt;

In the code for the contact form you have to insert your SMTP-server and the “toEmail”. This example form provides buttons for both methods of sending mail.

When sending the email you are presented with a “splash-screen” like this when using “sessvars.js” and redirect in the same page:
IMG

When using the sessvars.js redirect, you also get a “receipt” in the URL:
IMG

And like this when opening in a new window:
IMG

These “receipts” are based on the “SuccessMsg” and “ErrorMsg” specified in the contact form. The “placeholder” {0} and {1} in the message text are replaced with the time to close/redirect, and for “ErrorMsg” also the actual error from the “sendmail-code”.
IMG
In case of an error – the splash screen is displayed for 3 seconds longer than specified.

I will follow up this one with an example on how to send the contents of a DispForm as a HTML-bodied email, but all that is to it is to loose the “contact-form-message-field” and define the “htmlBody” in the “contact-form-code” to hold the HTML-content you want to send.

I am open for questions – and as i noted above: this one is outside my comfort zone and i appreciate feedback on the selected method and tips on how to make it better.

Regards
Alexander

3 Comments on “Send E-mail with JavaScript

  1. Hi Alexander,

    Thank you for the nice article and tip.

    Well, in my sharepoint web site I’ve created a workspace. This workspace contains a list of “Persons”. And also, there is another list named “Session”.
    I want to implement sending email on the “Persons” list. That is, I want to be able to send emails containg information about Session items to all or a group of selected persons.

    Is it possible to do this? Please, can you help me to implement it?
    Best regards,
    Sofiane.

  2. Is there a way to get these scripts to work on Google Chrome, Firefox, etc. other browsers….. I know SharePoint is MS and so is IE and know some features in SharePoint do not work in other browser but curious how to get this script to work…..

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.