Embedding images in an Email sent by ASP.Net Server

If you want to embed your images in an email sent using ASP.Net server instead than using URLs you can use an AlternateView and use the mime standard to embed them:

    using System.Net.Mail;

    protected void SendBTN_Click(object sender, EventArgs e) {

        // Send email using ASP.Net:
        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

        message.From = new System.Net.Mail.MailAddress(Email_From);
        message.To.Add(Email_To);
        message.Bcc.Add(Email_BCC);
        message.Subject = Email_Subject;
        message.IsBodyHtml = true;
        message.AlternateViews.Add(getS4HRegisteredUsersWithoutAnOrderBody_ForEmail(Customer.Name));

        SmtpClient smtp = new SmtpClient("subdom.myserver.com");
        smtp.Send(message);

        // Show some "Email Sent" msg and all that stuff or return ok.
    }


private AlternateView getS4HRegisteredUsersWithoutAnOrderBody_ForEmail(String CustName) {
        StringBuilder body = new StringBuilder();
        body = SkyGuard.MIS.Email.getTemplate("S4HRegisteredUserWithoutOrder.htm");
        body.Replace("[SUBJECT]", Email_Subject);
        body.Replace("[CUSTNAME]", CustName);
        //These keys are set into the image src attribute
        body.Replace("[LOGO_IMGSRC]", "cid:logo"); //Notice that we are adding a cid:id as the image source
        body.Replace("[SUPPORT_PHOTO_IMGSRC]", "cid:avatar");
        body.Replace("[SIGNATURE_IMGSRC]", "cid:signature");

        AlternateView view = AlternateView.CreateAlternateViewFromString(body.ToString(), null, System.Net.Mime.MediaTypeNames.Text.Html);
        
        //Company Logo
        LinkedResource logo = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/imgs/Emails/Company_logo.png"), System.Net.Mime.MediaTypeNames.Image.Jpeg);
        logo.ContentId = "logo";
        LinkedResource avatar = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/imgs/Emails/Support_Avatar.png"), System.Net.Mime.MediaTypeNames.Image.Jpeg);
        avatar.ContentId = "avatar";
        LinkedResource signature = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/imgs/Emails/Support_Signature.png"), System.Net.Mime.MediaTypeNames.Image.Jpeg);
        signature.ContentId = "signature";

        view.LinkedResources.Add(logo);
        view.LinkedResources.Add(avatar);
        view.LinkedResources.Add(signature);

        return view;
    }

One thought on “Embedding images in an Email sent by ASP.Net Server

Leave a Reply

Close Bitnami banner
Bitnami