Friday, October 30, 2009

Sending email through Outlook using c#.net

In this example i am going to explain how to send email through MS Outlook using C#.Net

For sending email through outlook we have add referance 'Microsoft Outlook 12.0 Object Library'.

Click on the Add referance, select COM tab and select 'Microsoft Outlook 12.0 Object Library'

This is the code for sending mail:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace OutlookMail
{
    public partial class Form1 : Form
    {
        private static Microsoft.Office.Interop.Outlook.Application oApp;
        private static Microsoft.Office.Interop.Outlook._NameSpace oNameSpace;
        private static Microsoft.Office.Interop.Outlook.MAPIFolder oOutboxFolder;

        public Form1()
        {
            InitializeComponent();
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            oApp = new Microsoft.Office.Interop.Outlook.Application();
            oNameSpace = oApp.GetNamespace("MAPI");

            oNameSpace.Logon("Outlook", null, true, true);
            oOutboxFolder = oNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox);

            Microsoft.Office.Interop.Outlook._MailItem oMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

            oMailItem.To = txt_to.Text;
            oMailItem.Subject = txt_body.Text;
            oMailItem.Body = txt_body.Text;
            //oMailItem.DeleteAfterSubmit = true;
            oMailItem.Send();

            MessageBox.Show("Mail send sucessfully");
        }
    }
}