Saturday, May 29, 2010

How to use MS Outlook API to send mails

First You have to add Microsoft.Office.Interop.Outlook using References.To do that go to Solution Explorer->Reference->Add Reference->.NET tab->Microsoft.Office.Interop.Outlook.

After that we will create a small class called SendEmails and we will implement a method called sendGroupmail.

Here the Implementation for SendEmails Class.

public class SendEmails
{
public int sendGroupMail(string recipientsList, string subject, string body)
{
Outlook.Application objectOutLook = new Outlook.Application();

try
{
Outlook.MailItem mailItem = objectOutLook.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mailItem.Subject = subject;
mailItem.To = recipientsList;
mailItem.Body = body;
Outlook.NameSpace ns = objectOutLook.GetNamespace("mapi");
ns.Logon(Missing.Value, Missing.Value, true, true);
mailItem.Importance = Outlook.OlImportance.olImportanceLow;
((Outlook.MailItem)mailItem).Send();
ns.Logoff();
return 1;
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message);
return 0;
}

}
}


How to use this class.........

SendEmails newemail=new SendEmails();
int result = newemail.sendGroupMail("example@mail.com", "This is Subject", "This is Body")
;

No comments: