Wednesday, May 16, 2012

Send mail using Microsoft Outlook



Already posted how to mail using SMTP; but now in this implemenation will show how to send mail using Microsoft Outlook object.
But there a basic rule of these implementation:
  1. Create the required objects.
  2. Add recepient, main subject, mail body, attachment.
  3. Send mail and validate.
  4. Release resources.
Implementation:
using Outlook = Microsoft.Office.Interop.Outlook;

public void SendTestMail()
{
    try
    {
        Outlook.Application otApp = new Outlook.Application();// create outlook object
        Outlook.NameSpace ns = otApp.Session;
        Outlook.MailItem otMsg = (Outlook.MailItem)otApp.CreateItem(Outlook.OlItemType.olMailItem); // Create mail object
        Outlook.Inspector oInspector = otMsg.GetInspector;
        Outlook.Recipient otRecip = (Outlook.Recipient)otMsg.Recipients.Add("abc@xyz.com");
        otRecip.Resolve();// validate recipient address
        otMsg.Subject = "test subject";
        otMsg.Body = "text message";
        String sSource = "C:\\Test.txt";
        String sDisplayName = "TestAttachment";
        int iPos = (int)otMsg.Body.Length + 1;
        int iAttType = (int)Outlook.OlAttachmentType.olByValue;  
        Outlook.Attachment oAttach = otMsg.Attachments.Add(sSource,iAttType,iPos,sDisplayName); // add attachment
        otMsg.Save();
        otMsg.Send(); // Send Mail
        otRecip = null;
        otAttach = null;
        otMsg = null;
        otApp = null;
    }
    catch (Exception e)
    {
        Console.WriteLine("{0} Exception caught: ", e);
    }
    return 0;
}

4 comments:

  1. Hi Kuntal Saha,
    Same coding is working fine in my system. But when i published in IIS it is not working :(. Could you please help me in this.

    rajmca.g@gmail.com

    ReplyDelete
    Replies
    1. Hi Raj,
      I would rather suggest you creating a service seperately to handle mail communication. Consume the service whenever you wanna send mail.

      Jack

      Delete
  2. just tried this code, doesnt do anything for me :(

    ReplyDelete