Friday, September 30, 2011

Send mail using asp.net c# code


Send mail using asp.net c# code
This code describe how to send mail where mail id is stored in database and mail sender detail From,To,
are stored in web.config file.Mail body can be customized according to requirement as described in code.

public void MailSend()
{
try
{
string mailToAdd = String.Empty;
MailMessage message1 = new MailMessage();
string strMail;
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["SqlConnString"]);
SqlDataReader dr;
conn.Open();
SqlCommand cmd = new SqlCommand("usp_MediaRegistration", conn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
strMail = (string)dr["emailID"];
message1.IsBodyHtml = true;
string MailFrom = ConfigurationManager.AppSettings["from"].ToString();
message1.From = new MailAddress(MailFrom);
message1.To.Add(new MailAddress(strMail).ToString());
message1.Subject = "Headline of the press release";
if (Request.QueryString["strmail"] == "0")
{
message1.Body = "<html><body><table><tr><td>Dear Users,</td></tr><br/>" +
"<tr><td><t/>This is to inform you that ...your message. <br/>" +
"<tr><td><t/>Please click on the link to see details....: <br/>" +
"<tr><td><a href='" + "http://xyz.com/mediapage.aspx?year=" + drlMyyyy.SelectedItem.Value
+ "'>" + "http://xyz.com/mediapage.aspx?year=" + drddMyyyy.SelectedItem.Value +
"</a></td></tr><br/>" +
"<tr><td>Thanks & Reagrds,</td></tr>" +
"<tr><td>santosh singh</td></tr> </table></body></html>";
}
}
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SmtpHost"]);
client.Send(message1);
}
catch (Exception ex)
{
string str1 = string.Format("Message Sending Fail Due To {0}.", ex.Message);
}
}
Thanks & Regards