Monday, August 8, 2011

Sending mail using Outlook in C#


Follow following Steps:
1) Add references from COM tab: Microsoft Outlook 9.0 Objecr library
2) Add following line at the top of the file
using Outlook = Microsoft.Office.Interop.Outlook;
3)  Add this method:
 private void SendMail()
{
       Outlook.Application oApp = new Outlook.Application();

      Outlook.MailItem email = (Outlook.MailItem)(oApp.CreateItem(Outlook.OlItemType.olMailItem));
       email.Recipients.Add("info@gmail.com");
       email.Subject = "hi";
       email.Body = "bye";

       OpenFileDialog attachment = new OpenFileDialog();
       attachment.Title = "Select a file to send";
       attachment.ShowDialog();
      email.Attachments.Add(attachment.FileName,Outlook.OlAttachmentType.olByValue,1,attachment.FileName);
                     
        email.DeleteAfterSubmit=true;//email removed from the outbox after send
        email.Send();

 }

Note: Outlook should be configured (tools -> Email accounts) with valid SMTP details like
          a) Server Information
                  Incoming Mail Server(POP3): mail.microsoft.com
                  Outgoing Mail Server(SMTP): mail.microsoft.com
          b) Email Address: info@microsoft.com
          c) Logon Information
                  UserName: info@microsoft.com
                  Password: *******
          d) Commonly Incoming Server Port: 110 and Outgoing Server port: 25
          e) My Outgoing server require authentication checkbox may be checked.
          f) Connection: Connect via Modem checkbox may be checked.

No comments:

Post a Comment