22 May 2007

Sending mails in .NET & C#

My ideal method to send standard html mails through an application is by reading an html file and replacing its content with final data and send it.

I was very much familiar and proficient in ASP and PHP, now i tried the same with ASP.NET C# and the details of the same are given below:


string path = Request.MapPath("leave_mail_tpl.html");
//Session["eid"]
//opening a file
//FileStream file = new FileStream("leave_mail_tpl.html");
//reading a file
StreamReader sr = new StreamReader(path);
string mailbody = sr.ReadToEnd().ToString();
sr.Close();


mailbody = mailbody.Replace("empname", empname);
and so on for all the replacable elements.


MailMessage msg = new MailMessage();
//System.Text.StringBuilder str = new System.Text.StringBuilder();
msg.To=toemail;
msg.Cc = ccemail;
msg.From =fromemail;
msg.Subject = "A Leave Request from " + empname;
msg.BodyFormat = MailFormat.Html;
msg.Body = mailbody.ToString();
try
{
SmtpMail.SmtpServer= "ip adress";
SmtpMail.Send(msg);
}
catch(Exception ex)
{
// show success message
}

No comments: