Search in Help for developer site.

Monday 25 July 2016

How to send HTML email in outlook programmatically using c#.

In outlook we can send HTML emails, when we add some HTML code outlook can convert that HTML to design. For that we need to change the mail format to HTML in outlook setting.

For eg. if you use the below HTML code in your mail body
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
<p>Name</p>
<span>Add</span>
</body>
</html>

Then outlook will convert your message like below

My First Heading

My first paragraph.
Name
Add

This can be done by C#. When you have a fixed HTML format but some fields will change such as name, address etc then u can use this code to send HTML mail.
For that you need to add a reference to "Microsoft.Office.Interop.Outlook"
Use this code in your mail sending event.



            StringBuilder mailbody = new StringBuilder();
            Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();

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

            oMailItem.To = "xyz@gmail.com";
            oMailItem.Subject = "Subject";
            mailbody.Append("<html>");
            mailbody.Append("<head>");
            mailbody.Append("<title>Page Title</title>");
            mailbody.Append("</head>");
            mailbody.Append("<body>");
            mailbody.Append("<h1>My First Heading</h1>");
            mailbody.Append("<p>My first paragraph.</p>");
            mailbody.Append("<p>Name</p>");
            mailbody.Append("<span>Add</span>");
            mailbody.Append("</body>");
            mailbody.Append("</html>");
            oMailItem.HTMLBody = mailbody.ToString();
            // body, bcc etc...
            //For adding cc and bcc

            //oMailItem.Send();
            //To send mail.

            oMailItem.Display(true);//This will open outlook before sending the mail.





Please comment for more explanation.

4 comments:

  1. good to know but what if we want to add attachments

    ReplyDelete
    Replies
    1. Definitely we can do that just add,
      oMailItem.Attachments.Add(@"C:\Users\XYZ\....\Filename");
      It will add the attachment.
      Thank You

      Delete
  2. This comment has been removed by the author.

    ReplyDelete