Monday, February 7, 2011

Send Mail through outlook using C#

To Send Email Using Outlook you need to add refrence of Outlook to your project



using Outlook = Microsoft.Office.Interop.Outlook;

public class ODA_Genral
{
public void sendemail()
{
try
{
// Create the Outlook application.
Outlook.Application objApp = new Outlook.Application();

// Get the NameSpace and Logon information.
Outlook.NameSpace objNS = oApp.GetNamespace("mapi");

// Log on by using a dialog box to choose the profile.
objNS.Logon(System.Reflection.Missing.Value, System.Reflection.Missing.Value, true, true);

// Create a new mail item.
Outlook.MailItem objMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

// Set the subject.
objMsg.Subject = "Mail Send Using Outlook through C#.net";

// Set HTML Body for you mail.
String HtmlBoday;
HtmlBoday = "Send Mail Through Outlook using C#.Net";

objMsg.HTMLBody = HtmlBoday;

// Add a recipient.
Outlook.Recipients objRecips = (Outlook.Recipients)oMsg.Recipients;

// TODO: Change the recipient in the next line if necessary.
Outlook.Recipient objRecip = (Outlook.Recipient)oRecips.Add("Email ID");
objRecip.Resolve();

// Call Send Method to send the mail.
objMsg.Send();

// Log off from Outlook.
objNS.Logoff();

// Set All Objects to Null.
objRecip = null;
objRecips = null;
objMsg = null;
objNS = null;
objApp = null;
}

// Simple error handling.
catch (Exception ex)
{
Console.WriteLine("{0} Exception Occured. Mail Sending Failed", ex);
}
}
}

3 comments:

  1. Hi,

    Outlook coding is working fine from Visual studio. But when i publish the same in IIS it is not working. Could you please help me.

    rajmca.g@gmail.com

    ReplyDelete
    Replies
    1. Hi Raj,
      how to solve the problem.
      in local system working file but when i have publish then not working. Error-Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).

      Please help me. how to resolved.

      Delete