How to pull content of an e-mail page/template into a MailMessage Body in .NET
-
18-09-2019 - |
Question
I have an e-mail template which is just a plain, static HTML page.
I need to get that page into the Body of a MailMessage
.
Normally what I would do is just create a StringBuilder
and append the lines over and over. But it's kind of a long page, and I don't want to go through replacing the quotes with single quotes etc..
So is there a way to just pull in the contents of an html page into a string? Such as:
emailMessage.IsBodyHtml = true;
emailMessage.Subject = "Test Subject";
emailMessage.Body = GetContentsFrom("emailtemplate.html");
Thanks!
Solution
Could you replace GetContentsFrom with File.ReadAllText?
OTHER TIPS
I think this routine would do the trick:
private static string GetTemplate(string templateFullPath)
{
string template;
if (!File.Exists(templateFullPath))
throw new ArgumentException("Template file does not exist: " + templateFullPath);
using (StreamReader reader = new StreamReader(templateFullPath))
{
template = reader.ReadToEnd();
reader.Close();
}
return template;
}
Is the page being hosted somewhere? You could do this:
private string HtmlPageInToString()
{
WebRequest myRequest;
myRequest = WebRequest.Create(@"http://yoururlhere/");
myRequest.UseDefaultCredentials = true;
WebResponse myResponse = myRequest.GetResponse();
Stream ReceiveStream = myResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(ReceiveStream, encode);
return readStream.ReadToEnd();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow