Ever needed to convert html image link on your site to cid to embed on email
public ArrayList arr_image_path = new ArrayList();//image array (for embedding images)
public string _html, _plain;
public string RootDirectory = HttpRuntime.AppDomainAppPath.ToString();
public void covert_image_to_embedded_cid()
{
int cid = 0;
string Pattern = @"url\(['|\""]+.*['|\""]\)|src=[""|'][^""']+[""|']";
MatchCollection match_vars = Regex.Matches(_html, Pattern,
RegexOptions.IgnoreCase);
string img_path;
foreach (Match match in match_vars)
{
_html = _html.Replace(match.Value, "src=\"cid:EmbedRes_" + cid + "\"");
//get path;
img_path = Regex.Replace(match.Value, @"url\(['|\""]", "");
img_path = Regex.Replace(img_path, @"src=['|\""]", "");
img_path = Regex.Replace(img_path, @"['|\""]\)", "").Replace("\"", "");
arr_image_path.Add(img_path);
cid++;
}
}
public bool sendmail(string strTo, string strSubject)
{
bool success = false;
StringBuilder sb_plain = new StringBuilder();
StringBuilder sb_html = new StringBuilder();
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress(Mail_From);
mail.To.Add(strTo);
//set the content
mail.Subject = strSubject;
//Plain Text
AlternateView plainView = AlternateView.CreateAlternateViewFromString(_plain, null, "text/plain");
//Html part
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(_html, null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
//add images
if (arr_image_path.Count > 0)
{
for(int i=0; i<arr_image_path.Count; i++)
{
string img = arr_image_path[i].ToString();
if (!img.ToLower().StartsWith("http"))
{
img = RootDirectory + img;
}
LinkedResource logo = new LinkedResource(img);
logo.ContentId = "EmbedRes_"+i;
htmlView.LinkedResources.Add(logo);
}
}
//send the message
SmtpClient smtp = new SmtpClient(MailServer); //specify the mail server address
//check if server creditial required
if (credentialsRequired)
{
smtp.Credentials = new NetworkCredential(Mail_Username, Mail_Password);
}
//try
{
smtp.Send(mail);
}
//catch
{
}
return success;
}