Wednesday, July 21, 2010

Embedded Images into HTML format mail in .Net

Hi,

To send the HTML format mail in .Net Environment with images and more stuff like hyper links. For that purpose create a Html page with your all requirements but in place of image tag just place like this.



and suppose you have a requirement like add values to variables dynamically, on that time you need write custom code to achevive that requiremets. In our project we did like this.

IP Address : $IpAddress

Username : $Email

Password : $Password



what are the values are comming dynamically for that variables you mention as $ before that.(see the above).

In our C# code you need to create dictionary object, and assigne values to those variables.

Dictionary templateFields = new Dictionary();
templateFields.Add("$Email", login.Email); // Login.Email is our own variable.
templateFields.Add("$Password", paas your desired value);
templateFields.Add("$IpAddress", paas your desired value);

Now you need to open the html and read the contents and write into StreamReader.

StringBuilder bodyMessage = new StringBuilder();
string filePath = Server.MapPath("~/Content/email.htm");
StreamReader ContentReader = File.OpenText(filePath);
bodyMessage.Append(ContentReader.ReadToEnd());
Match mailSubject = Regex.Match(bodyMessage.ToString(), @"(?<=)([\s\S]*)(?=)");
sendData.Subject = mailSubject.ToString();
ContentReader.Close();
}
foreach (KeyValuePair indexPair in templateFields)
{
bodyMessage = bodyMessage.Replace(indexPair.Key, indexPair.Value);
}


Now get the Images paths from server.
string serverImagePath = Server.MapPath("~/Content/Images/fsboForPhoto.jpg");

basing on that image path create you create a AlternateView and add to your Mail message.

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

// Use Linked Resource class for storing image in the form binary code.
LinkedResource imagelink = new LinkedResource(serverImagePath, "image/jpeg");
imagelink.ContentId = "imageId";
imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64; //It is so Importent

htmlView.LinkedResources.Add(imagelink);

That's it.

My code for the above eample.


Html Page:













IP Address : $IpAddress

Username : $Email

Password : $Password











Click here to login

Copyright © 2009 FSBO.in. All Rights Reserved.





C#.Net Function:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ForgotPassword(LoginViewModel login)
{

Title("FSBO Homes For Sale By Owner Real Estate Listings For Sale By Owner at FSBO.in");

if (Session["Captcha"].ToString() == Request.Form["captchaText"])
{

BS.UserBS user = new BusinessServices.UserBS();
Users users = user.ForgotPassword(login.Email);
if (users != null)
{
if (users.Password != null)
{
// Get the IP address of the system where request is comming
string address = string.Empty;
address = ControllerContext.HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
// check if the request doesnt have forward remote address
if (address == null (address != null && address.Length < address =" HttpContext.Request.ServerVariables["> templateFields = new Dictionary();
templateFields.Add("$Email", login.Email);
templateFields.Add("$Password", users.Password);
templateFields.Add("$IpAddress", address);

MailMessage mail = new MailMessage();
MailAddress mailaddress = new MailAddress(login.Email);
mail.To.Add(mailaddress);
BS.MailBS mailBs = new BusinessServices.MailBS();
// Get the physical path of the HTML file.
string mailFilePath = Server.MapPath("~/Content/email.htm");
// Get the physical path of the Image file.
string serverImagePath = Server.MapPath("~/Content/Images/fsboForPhoto.jpg");

string Body = mailBs.ComposeMessageTemplate(mail, templateFields, mailFilePath);
// Create a Alternative view using body of the mail for Image purpose
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

// Use Linked Resource class for storing image in the form binary code.
LinkedResource imagelink = new LinkedResource(serverImagePath, "image/jpeg");
imagelink.ContentId = "imageId";
imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;

htmlView.LinkedResources.Add(imagelink);
mail.AlternateViews.Add(htmlView);
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);

ViewData["MailMsg"] = "Your Password sent to your mail";
}
else
{
ViewData["MailMsg"] = "Invalid email Id";
}
}
else {
ViewData["MailMsg"] = "Invalid email Id";
}
}
else
{

ViewData["CaptchaMsg"] = "Invalid Captcha answer";
}



return View("ForgotPassword");

}


ComposeMessageTemplate Function:

public string ComposeMessageTemplate(T sendData, Dictionary templateFields, string templatePath)
{
StringBuilder bodyMessage = new StringBuilder();

try
{

//if (!loadedTemplates.ContainsKey(sendData.TemplateName))
{
string filePath = templatePath;
StreamReader ContentReader = File.OpenText(filePath);
bodyMessage.Append(ContentReader.ReadToEnd());
Match mailSubject = Regex.Match(bodyMessage.ToString(), @"(?<=)([\s\S]*)(?=)");
sendData.Subject = mailSubject.ToString();
ContentReader.Close();



}


foreach (KeyValuePair indexPair in templateFields)
{
bodyMessage = bodyMessage.Replace(indexPair.Key, indexPair.Value);
}




//sendData.Body = bodyMessage.ToString();


//sendData.MailSubject =
}
catch (Exception ex)
{
//Survey.Common.ExceptionHelper.ProcessUnhandledException(ex);
throw ex;
}

return bodyMessage.ToString();
}

Main things you need to concentarte are
Server.MapPath("~/Content/email.htm"); // to get the file or image from the Server using our URL.
AlternateView class used add MailMessage for separe view.

LinkedResource imagelink = new LinkedResource(serverImagePath, "image/jpeg");
imagelink.ContentId = "imageId";
imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;//Convert JPEG into binary fromat
LinkedResource class is used to embbed into mail by converting JPEG into binary.


No comments:

Post a Comment