Compose and Send E-mail from JavaScript by using Outlook Automation 2007
Recently, I came across with very specific requirement for composing e-mail thru client side code. The requirement was to compose outlook e-mail for daily status report after collecting the data from Project server and SharePoint site. So the outlook 2007 should be pre-installed on the client machine. When a user press the button, the application should pop-up outlook e-mail to let the user makes any changes before sending the mail
I have written the generic code so that it can be used in any such requirement. I hope this will help the developers with the similar requirement.
You need to change the settings of Internet explorer for this to work:
a) Go to ‘Tools’ menu in the internet explorer.
b) Go to ‘Options’.
c) Click “Custom Level” Button.
d) Select the option “Initialize and script ActiveX control not marked as safe for scripting” to Prompt or Enable.
JavaScript File: Mail.js (Included in the root of the project)
function SendMail(to,body,sub)
{
var theApp //Reference to Outlook.Application
var theMailItem //Outlook.mailItem
//Attach Files to the email, Construct the Email including
//To(address),subject,body
var subject = sub
var msg = body
//Create a object of Outlook.Application
try
{
var theApp = new ActiveXObject("Outlook.Application")
var theMailItem = theApp.CreateItem(0) // value 0 = MailItem
//Bind the variables with the email
theMailItem.to = to
theMailItem.Subject = (subject);
theMailItem.Body = (msg);
//Show the mail before sending for review purpose
//You can directly use the theMailItem.send() function
//if you do not want to show the message.
theMailItem.display()
}
catch(err)
{
alert("The following may have cause this error: \n"+
"1. The Outlook express 2007 is not installed on the machine.\n"+
"2. The msoutl.olb is not availabe at the location "+
"C:\\Program Files\\Microsoft Office\\OFFICE11\\msoutl.old on client's machine "+
"due to bad installation of the office 2007."+
"Re-Install office2007 with default settings.\n"+
"3. The Initialize and Scripts ActiveX controls not marked as safe is not set to enable.")
document.write("<a href=\""+"./testemail.asp"+"\""+">"+"Go Back"+"</a>")
}
}
Page_Load EventHandler(Note:How onclick attribute is added to button control):
protected void Page_Load(object sender, EventArgs e)
{
string to, sub, body;
to = "rkaushik@microsoft.com";
body = "Body of the mail";
sub = "Subject";
btnSendMail.Attributes.Add("onclick", "SendMail('" + to + "','" + body + "','" + sub + "')");
}
Button Control (used to invoke the Javascript):
<asp:Button ID="btnSendMail" runat="server" Text="Send Mail" />
Include Javascript between the page Header:
<script type="text/javascript" language="javascript" src="Mail.js"></script>
Comments
- Anonymous
April 28, 2008
The comment has been removed