HaresH Chaudhari

Freelance Web Developer

How to embad Images in mail body in asp.net

When we send email with images, we must have to provide phisical path of the host where our images are located.  But here is the one solution that we can embad images in email body.

Here we don’t need to provide the path. We just have to create Linked resource and Alternative view  from the mail message object. Now we just have to provide the Resource Id to Alternative view object and bind that linked resource to alternative view’s object. That’s all.  See the following code with example…

//Holds message information.
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
//Add basic information.
mailMessage.From = new System.Net.Mail.MailAddress(txtFrom.Text.Trim());
mailMessage.To.Add(txtTo.Text.Trim());
mailMessage.Subject = txtSubject.Text.Trim();

//Add image to HTML version
string path = Server.MapPath(@”Your Image Name.extention”); // my logo is placed in images folder

System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(path, “image/gif”);
imageResource.ContentId = “HDIImage”;
//Create two views, one text, one HTML.
System.Net.Mail.AlternateView htmlView = AlternateView.CreateAlternateViewFromString(“
” + txtBody, null, MediaTypeNames.Text.Html);
htmlView.LinkedResources.Add(imageResource);

mailMessage.AlternateViews.Add(htmlView);
mailMessage.IsBodyHtml = true;
//Send message
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(“Your Mail Server Name”);
//SmtpClient client = new SmtpClient(strSMTPserver);
smtpClient.Credentials = new NetworkCredential(“Username”, “Password”);
smtpClient.Send(mailMessage);

Thanks you and hope this article will help you lot’s

Advertisement

Filed under: 1,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.