Embed Image in E-Mail is Easy in C#

Embed Image in mail

How to add logo in mail? How to add an image object in mail with out having any static URL?
(for example <img src=”http://shareourideas.com/wp-content/uploads/2010/03/twitter_logo_header.png” />)
Here best solution for this…!

C# Code :-

Import this Net.Mail and Net.Mime

using System.Net.Mail;
using System.Net.Mime;

//Then use this code in button click or your own function
{
string strMailContent = “Here is your mail content….”;
string fromAddress = “your-email@[yourdomain.com]”;
string toAddress = “to-email@[todomain.com]”;

// Set Image path here in windows applications. Environment.CurrentDirectory, to get .exe file location.
string path = Environment.CurrentDirectory + @”logo.png”;
//Tip:- when your working Asp.net use Server.MapPath(@”logo.png”)

MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
mailMessage.Subject = “Subject goes here”;

//Set linked resource
LinkedResource logo = new LinkedResource(path);
//Set Id for linked resource
logo.ContentId = “logo”;
logo.ContentType.MediaType = “image/png”;

//Here HTML formatting for display logo
AlternateView av = AlternateView.CreateAlternateViewFromString(“<html><body><img src=”cid:logo” /><br></body></html>” + strMailContent, null, MediaTypeNames.Text.Html);

av.LinkedResources.Add(logo);

mailMessage.AlternateViews.Add(av);
mailMessage.IsBodyHtml = true;
/* use this if you are in the development server. Else set smtp settings in web.config in asp.net, in windows apps add in app.config and use that settings. */

SmtpClient mailSender = new SmtpClient(“localhost“);
//Use if you need remote access of your mail server
mailSender.Credentials = new System.Net.NetworkCredential(“your-email@[your-domain.com]”, “[password]”);

//Now ready to send mail.
mailSender.Send(mailMessage);

}
}
}

Check your email inbox. Yes, you will get image (logo)  in mail.

Thanks,

Naga harish Movva.

  • Pingback: Embed Image in E-Mail is Easy in C# « Share Our Ideas by Naga Harish | Source code bank()

  • IGORRd

    Thanks

  • Hi

    “AlternateView av ” needs to be “AlternateView av1”
    and
    “mailMessage.AlternateViews.Add(av);” needs to be “mailMessage.AlternateViews.Add(av1);”

    OR

    “av1.LinkedResources.Add(logo);” needs to be “av.LinkedResources.Add(logo);”

    Variable names are off, but the article gives you the general workflow. Thanks!

    • Naga Harish Movva

      Thanks for you correction, I made change :)