Sunday, September 25, 2011

Sending email with embeded image

I have written some articles on sending email from .net application. In this article I will show you a tricky way of sending embeded image to your mail.

The trick to embed image is to create an alternative view and to add a linked resource to the alternative view. Alternative views enable you to create different versions of the email message -- typically one in plain text and the other formatted with HTML. These then substitute for the basic msg.Body property.

To do the actual embedding, you need to do a number of things:
  • Create an HTML-formatted message.
  • Use an <img> tag in the message body.
  • For the src attribute of the <img>, point to a content ID (cid). This points to the portion of the message containing the image stream.
  • Create an alternative view.
  • Create a linkedResource that slurps up the image you want to embed.
  • Assign a content ID to the linked resource -- this should match the cid you used in the <img> tag.
  • Assign the image's file name to the linked resource.

Here is example code sample:

protected void btnSend_Click(object sender, EventArgs e)
    {
        MailMessage mail = BuildMail();
        SendEMail(mail);
    }

private MailMessage BuildMail()
    {
        string from, to, bcc, cc, subject, body;
        from = "uniquesaiful@gmail.com";   //Email Address of Sender
        to = "tips.asp.net@gmail.com,saifulondotnet@gmail.com,uniquesaiful@gmail.com";   //Email Address of Receiver
        bcc = "";
        cc = "";
        subject = "This is a test email. I am just checking whether email client is working properly.";
 
        string imagePath = Server.MapPath("~") + "\\";
        string fileName = imagePath + "Logo.JPG";
 
        StringBuilder sb = new StringBuilder();
        sb.Append("Hi Scott,<br/>");
        sb.Append("This is a test email. We are testing out email client. Please don't mind.<br/>");
        sb.Append("We are sorry for this unexpected mail to your mail box.<br/>");
        sb.Append("<br/>");
        sb.Append("Thanking you<br/>");
        sb.Append("Tips.Asp.Net");
 
        body = sb.ToString();
 
        AlternateView av = AlternateView.CreateAlternateViewFromString(body, nullMediaTypeNames.Text.Html);
        LinkedResource linkedRes = new LinkedResource(fileName);
        linkedRes.ContentId = "image1";
        linkedRes.ContentType.Name = fileName;
        av.LinkedResources.Add(linkedRes);
 
 
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(from);
        if (to.Contains(","))
        {
            string[] tos = to.Split(',');
            for (int i = 0; i < tos.Length; i++)
            {
                mail.To.Add(new MailAddress(tos[i]));
            }
        }
        else
        {
            mail.To.Add(new MailAddress(to));
        }
 
        if (!string.IsNullOrEmpty(bcc))
        {
            mail.Bcc.Add(new MailAddress(bcc));
        }
        if (!string.IsNullOrEmpty(cc))
        {
            mail.CC.Add(new MailAddress(cc));
        }
 
        mail.Subject = subject;
        mail.Body = body;
        mail.AlternateViews.Add(av);
        mail.IsBodyHtml = true;
 
        return mail;
    }
 
    private void SendEMail(MailMessage mail)
    {
        SmtpClient client = new SmtpClient();
        client.Host = "smtp.gmail.com";
        client.Port = 587;
        client.EnableSsl = true;
        client.Credentials = new System.Net.NetworkCredential("uniquesaiful"ami@janina.com);
        try
        {
            client.Send(mail);
        }
        catch (Exception ex)
        {
            throw ex;
        }
 
    }



4 comments:

  1. there is something is wrong
    it works as attachment with yahoo mails !!

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

    ReplyDelete
  3. Do you think it is possible to place a header/banner on the confirmation e-mail? how?

    ReplyDelete
  4. It is not working correctly. The image is not getting in the mail even though we changed the setting 'show images' in the received mail. It works only if the mail is opened in the same system where the image is physically located..

    ReplyDelete