Send Email with inline images

Lakhangarg
Posted by Lakhangarg under C# category on | Views : 2132
function to send email and send the inline images without attachement.
suppose we have email template in HTML and want to send the same to user and that template contains some images. if we send this as it is then user needs to right click on the image to download image. to remove this issue we can send inline images using System.Net.Mail.Attachment class's property name ContentId.

public static void SendEmail(string from, string to, string cc, string subject, string body, string attachedFiles)
{
try
{
MailMessage mailMsg = new MailMessage();
SmtpClient mailObj = new SmtpClient(ConfigurationManager.AppSettings["SmtpClient"]);//"192.168.1.145"

mailMsg.From = new MailAddress(from);

string[] temp = to.Split(';');
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].ToString().Length > 1)
mailMsg.To.Add(temp[i].ToString());
}

temp = cc.Split(';');
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].ToString().Length > 1)
mailMsg.CC.Add(temp[i].ToString());
}
temp = attachedFiles.Split(';');
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].ToString().Length > 1)
mailMsg.Attachments.Add(new Attachment(temp[i].ToString()));
}

mailMsg.Subject = subject;
mailMsg.Body = body;
mailMsg.IsBodyHtml = true;
int count = 0;
string oldChar = ExtractImages(body,ref count);
Random RGen = new Random();
while (oldChar != "")
{
string imgPath = oldChar;
int startIndex = imgPath.ToLower().IndexOf("images/");
if (startIndex > 0)
{
imgPath = imgPath.Substring(startIndex);
imgPath = imgPath.Replace("/", "\\");
System.Net.Mail.Attachment A = new Attachment(HttpContext.Current.Request.PhysicalApplicationPath + "\\" + imgPath);
A.ContentId = RGen.Next(100000, 9999999).ToString();
body = body.Replace(oldChar, "cid:" + A.ContentId);
mailMsg.Attachments.Add(A);
oldChar = ExtractImages(body, ref count);
}
else
{
oldChar = ExtractImages(body, ref count);
}
}
mailMsg.Body = body;
mailObj.Send(mailMsg);
}
catch (Exception ex)
{
WriteLog(ex);
}
}

private static string ExtractImages(string body, ref int count)
{
int startIndex = body.ToLower().IndexOf(" < img src=\"",count);
int endIndex;
if (startIndex >= 0)
{
endIndex = body.IndexOf("\"", startIndex+10);
}
else
{
return "";
}
startIndex = startIndex + 10;
string imgurl = body.Substring(startIndex, (endIndex - (startIndex)));
count = startIndex;
return imgurl;
}


in this code we are considering that your image tag will be like this in Email Template HTML:
< img src="{ImageURL}" .../>

Comments or Responses

Login to post response