You may have the requirement to send invitation emails to Clients with Login information in the email from your DotNet application. You’re using a WebAPI as the back-end service to serve data and e-mail functionality. You may choose to have the format of the e-mail in the in an HTML file under the Views folder with placeholders that will be replaced from the data fetched from the database like username and login details etc.
Below is the sample mail format template with placeholders in the html file under the WebAPI Views folder as mail_invitation.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
{EmailBody}
<br />
<br />
Your Login:
<br />
USERNAME: {UserEmail}
<br />
LOGIN CODE: {Password}
<br />
<br />
{EmailSignature}
<br />
<br />
</body>
</html>
The following MailService class is kept under the Business layer of the WebAPI to modify the mail template:
public class MailService
{
public void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
{
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["FromEmailID"]); //From address from AppSettings.
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"]; //SMTP Server name or IP from AppSettings.
smtp.Send(mailMessage);
}
}
public string PopulateJourneyInvitationMailBody(string emailBody, string userEmail, string loginCode, string emailSignature)
{
string body = string.Empty;
using (StreamReader reader = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath("~/Views/Mails/mail_invitation.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{EmailBody}", emailBody);
body = body.Replace("{UserEmail}", userEmail);
body = body.Replace("{Password}", loginCode);
body = body.Replace("{EmailSignature}", emailSignature);
return body;
}
}
One thought on “Send email with C# DotNet”