How to send HTML-formatted email? [duplicate]
I could be able to let the web application sends automatic emails using Windows Task Scheduler. Now I want to send HTML-Formatted email using the following method that I wrote for sending emails.
My code-behind:
protected void Page_Load(object sender, EventArgs e)
{
SmtpClient sc = new SmtpClient("mail address");
MailMessage msg = null;
try
{
msg = new MailMessage("[email protected]",
"[email protected]", "Message from PSSP System",
"This email sent by the PSSP system");
sc.Send(msg);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (msg != null)
{
msg.Dispose();
}
}
}
How to do that? I just want to put some bold text with one link and maybe one image in the email.
Setting isBodyHtml
to true
allows you to use HTML tags in the message body:
msg = new MailMessage("[email protected]",
"[email protected]", "Message from PSSP System",
"This email sent by the PSSP system<br />" +
"<b>this is bold text!</b>");
msg.IsBodyHtml = true;
Best way to send html formatted Email
This code will be in "Customer.htm"
<table>
<tr>
<td>
Dealer's Company Name
</td>
<td>
:
</td>
<td>
#DealerCompanyName#
</td>
</tr>
</table>
Read HTML file Using System.IO.File.ReadAllText. get all HTML code in string variable.
string Body = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("EmailTemplates/Customer.htm"));
Replace Particular string to your custom value.
Body = Body.Replace("#DealerCompanyName#", _lstGetDealerRoleAndContactInfoByCompanyIDResult[0].CompanyName);
call SendEmail(string Body) Function and do procedure to send email.
public static void SendEmail(string Body)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(Session["Email"].Tostring());
message.To.Add(ConfigurationSettings.AppSettings["RequesEmail"].ToString());
message.Subject = "Request from " + SessionFactory.CurrentCompany.CompanyName + " to add a new supplier";
message.IsBodyHtml = true;
message.Body = Body;
SmtpClient smtpClient = new SmtpClient();
smtpClient.UseDefaultCredentials = true;
smtpClient.Host = ConfigurationSettings.AppSettings["SMTP"].ToString();
smtpClient.Port = Convert.ToInt32(ConfigurationSettings.AppSettings["PORT"].ToString());
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings["USERNAME"].ToString(), ConfigurationSettings.AppSettings["PASSWORD"].ToString());
smtpClient.Send(message);
}
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"