Wednesday, 10 November 2010

Embedded Images in Outlook using C#

Embedded Images in Outlook using C#
To monitor all the Host and services we are using Nagios application.
So at some point we felt that why not we should have some kind of application which will take the screen shot of this Nagios with different hosts and send all the screenshots embedded in to outlook instead of as attachment to a group of user.
There was an requirement in my project where I need to take the screen shot of the website at regular interval and embedded all the images in outlook as send that email to group of people.
To achieve above requirement I used WATiN ,C# and outlook instance.
Below is the Rough idea how I have done that:
1. Open the Nagios URL using WATiN
2. Login to the web site Uisng WATiN
3. Navigate the Host webpage
4. Take the Screen shot the web page and store at local drive
5. Move through all the host web page and take the screen shot using WATiN
6. Embedded in to Outlook instance and send that email.

Below is the code snippet which I have used to Embedded the images in outlook:

public void Sendemail(string mainUrl,string strToEmail, string[] strFileLocationForAttachamnet)



// Create the Outlook application.

Outlook.Application oApp = new Outlook.Application();

Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem


// Set HTMLBody.

string emailSubject = "**** Auto Generated Email:Nagios Screen Shot Update for

" + mainUrl + " ****";

String sDisplayName = "MyAttachment";

int iPosition = 50;// (int)oMsg.Body.Length + 1;

int iAttachType =(int)Outlook.OlAttachmentType.olByValue; \

string htmlStart ="<html><body><h5><Font

Color=Purpel>Hi,<br/>Please Find below The screen shot of Host

Status as of "+DateTime.Now +"<br/></h5>"; string body=string.Empty;

int i = 1;

foreach (string filelocation in strFileLocationForAttachamnet)


if (filelocation != null)


Outlook.Attachment oAttach = oMsg.Attachments.Add(filelocation, iAttachType, iPosition,


body += "<h4>["+i+"."+"]</h4><img

src=\"cid:" + oAttach.FileName

+"\" /><br/>";




string wholeBody = htmlStart + body + "<h5><Font

Color=Purpel>Note:if no Red color means none of the services are

in critical stage.<br/>Regards,<br/>Md.



oMsg.HTMLBody = wholeBody;
// Set the subject.

oMsg.Subject = emailSubject;

// Add a recipient.

Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;

Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(strToEmail); oRecip.Resolve();
// Send


// Clean up.

oRecip = null;

oRecips = null;

oMsg = null;

oApp = null;


catch (Exception ex) {

Md. Jawed


Anonymous said...

Very similar.

Marcin said...

Thanks Jawed. That was most helpful. I've been looking for this for a while. Having tested it, this method works a treat for Outlook users, but for non-Outlook users (eg gmail, yahoo etc) the images don't come up inline - have you faced that problem?