bashbin
bashbin

Reputation: 414

Sending HTML Email - How to attach the .html file to the email?

I have the following method for sending a simple email:

private void WelcomeMail(string recipient)
{
    MailMessage mailMessage = new MailMessage("MyEmail", recipient);
    StringBuilder sbEmailBody = new StringBuilder();

    sbEmailBody.Append("How can I attach .html file here instead of writing the whole code");

    mailMessage.IsBodyHtml = true;
    mailMessage.Body = sbEmailBody.ToString();
    mailMessage.Subject = "Welcome to domain.com";
    SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
    smtpClient.Credentials = new System.Net.NetworkCredential()
    {
        UserName = "MyEmail",
        Password = "MyPassword"
    };
    smtpClient.EnableSsl = true;
    smtpClient.Send(mailMessage);
}  

What should I remove/change/add to send an HTML formatted email?

The HTML file is called responsivemail.html and contains more than 100+ lines of html code (that's the problem).

Upvotes: 0

Views: 2747

Answers (1)

mason
mason

Reputation: 32738

If you have the HTML file in your site root in a file called emailtemplate.html, you can simply read the HTML into memory and assign it to the body of the email.

mailMessage.Body = File.ReadAllText(Server.MapPath("~/emailtemplate.html"));

I don't recommend this, but you could also embed the HTML into your code directly. Since the HTML spans multiple lines, we'll need to use a string literal (@"this is a string literal"). The HTML likely has double quotes in it. You'd need to escape them by doubling your double quotes.

mailMessage.Body = @"
  <h1>This is HTML in an email!</h1>
  <a href=""http://google.com\"">This is a test link.</a>
";

Long term, if you're going to be sending emails with HTML and you need to inject values into them, I suggest you look into Postal or other libraries. Postal can even make it easy to embed images.

Upvotes: 1

Related Questions