How to send an email using Microsoft Office Outlook in ASP.NET
Author: Richard Wand
Download Source Code : 1435_SendEmailUsingOutLook.zip
This article will explain that how simply we can send an email with attachment in ASP.NET using Microsoft Office Outlook.
Sending email from web application is a requirement for developers. ASP.NET provides different ways to send email from your web page. Some people prefer to use Simple Mail Transfer Protocol (SMTP) to send emails in ASP.NET but some people may need Microsoft Office Outlook to send their emails in their web pages. It is developer's choice or requirement to choose one of the options. I have also written an article earlier on Simple Mail Transfer Protocol (SMTP). You can read this article if you are interested. I will give you an example in following code snippet to send email in your ASP.NET web applications via Microsoft Office Outlook. We need to add a reference of object library for Outlook to send an email.
- Create a new website in Visual Studio 2012
- Go to Solution Explorer and right click on project and click on Add Reference
- Go to COM tab and select Microsoft office 12.0 Object Librar
- Don't forget to use namespace in your code
- Now write below code in page load event or where you want to use it.
// Create a Outlook Application and connect to outlook
Application OutlookApplication = new Application();
// create the MailItem which we want to send
MailItem email = (MailItem)OutlookApplication.CreateItem(OlItemType.olMailItem);
// Add a recipient for the email
// add subject and body of the email
email.Subject = "Test";
email.Body = "This is a test email to check outlook email sending code";
// add display name, position and attach type for the attachment
string DisplayName = "MyAttachment";
int iPosition = email.Body.Length + 1;
int AttachType = (int)OlAttachmentType.olByValue;
//now attached the file
Attachment Attach = email.Attachments.Add("C:\\test.txt", AttachType, iPosition, DisplayName);
' Create a Outlook Application and connect to outlook
Dim OutlookApplication As New Application()
' create the MailItem which we want to send
Dim email As MailItem = DirectCast(OutlookApplication.CreateItem(OlItemType.olMailItem), MailItem)
' Add a recipient for the email
' add subject and body of the email
email.Subject = "Test"
email.Body = "This is a test email to check outlook email sending code"
' add display name, position and attach type for the attachment
Dim DisplayName As String = "MyAttachment"
Dim iPosition As Integer = email.Body.Length + 1
Dim AttachType As Integer = DirectCast(OlAttachmentType.olByValue, Integer)
'now attached the file
Dim Attach As Attachment = email.Attachments.Add("C:\\test.txt", AttachType, iPosition, DisplayName)
- debug the code and send email. You can download complete code from link at the top