Windows Forms: Send and Receive email in Microsoft Outlook using C#
By FoxLearn 6/2/2017 10:26:40 PM 12.9K
How to send and receive email in Microsoft Outlook using C#
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "OutlookMail" and then click OK
Step 2: Design your form as below
You need to install Microsoft Outlook, then add a reference to Microsoft.Office.Interop.Outlook.dll
Step 3: Add code to handle your form as below
using System; using System.Data; using System.Windows.Forms; using Outlook = Microsoft.Office.Interop.Outlook; namespace OutlookMail { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnSend_Click(object sender, EventArgs e) { try { //Using COM to send email Outlook._Application _app = new Outlook.Application(); Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem); mail.To = txtTo.Text; mail.Subject = txtSubject.Text; mail.Body = txtMessage.Text; mail.Importance = Outlook.OlImportance.olImportanceNormal; ((Outlook._MailItem)mail).Send(); MessageBox.Show("Your message has been successfully sent.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } DataTable dt; private void btnReceive_Click(object sender, EventArgs e) { try { Outlook._Application _app = new Outlook.Application(); Outlook._NameSpace _ns = _app.GetNamespace("MAPI"); Outlook.MAPIFolder inbox = _ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); _ns.SendAndReceive(true); dt = new DataTable("Inbox"); dt.Columns.Add("Subject", typeof(string)); dt.Columns.Add("Sender", typeof(string)); dt.Columns.Add("Body", typeof(string)); dt.Columns.Add("Date", typeof(string)); dataGrid.DataSource = dt; foreach (Outlook.MailItem item in inbox.Items) dt.Rows.Add(new object[] { item.Subject, item.SenderName, item.HTMLBody, item.SentOn.ToLongDateString() + " " + item.SentOn.ToLongTimeString() }); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void dataGrid_CellClick(object sender, DataGridViewCellEventArgs e) { //Display email as html if (e.RowIndex < dt.Rows.Count && e.RowIndex >= 0) webBrowser.DocumentText = dt.Rows[e.RowIndex]["Body"].ToString(); } } }
VIDEO TUTORIALS
- Windows Forms: Text to speech in C#
- Windows Forms: Print Picture Box in C#
- Windows Forms: Advanced Filter DataGridView in C#
- Windows Forms: Progress Bar in C#
- How to create a Lucky Draw games in C#
- Windows Forms: Youtube Search with Paging in C#
- Windows Forms: How to Create a Random Password Generator in C#
- Windows Forms: Tag Control in C#
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024