-1

I am sending emails to my users in HTML format. There is lots of editing there, like user name, user birthday and many other details.

Now, I don't want my code to be look like this:

String message = "hello " + "David\n" + "congratulation for your " + birthday + "\nPleas visit our site\n" + siteLink + " to get your bonus";

Is there any C# tools I can use to make it easy editing?

Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216

5 Answers5

2

It seems that you want to be able to specify named tokens in a single string so that the HTML is easy to read and edit, like so:

"Hello {FirstName},\nPlease visit our site:\n{SiteLink}"

Take a look at this answer for some ways to do that: Named string formatting in C#.

Community
  • 1
  • 1
Michael Liu
  • 52,147
  • 13
  • 117
  • 150
1
string customBody = "<a href=\"www.oursite.com\">www.oursite.com</a>";
string htmlBody = String.Format("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
        body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
        body += "</HEAD><BODY><DIV>{0}</DIV></BODY></HTML>", customBody);

var message = new MailMessage(from, to);
var mimeType = new System.Net.Mime.ContentType("text/html");
var alternate = AlternateView.CreateAlternateViewFromString(htmlBody, mimeType);
message.AlternateViews.Add(alternate);        
message.IsBodyHTML = true;
smtpClient.Send(message);

See MSDN:

sll
  • 61,540
  • 22
  • 104
  • 156
  • How doe's it makes it easy for editing? I got another 20 parameters to push there... – Ilya Gazman Feb 04 '12 at 15:35
  • It is not a question of HTML email format but anyway you can use `StringBuilder` or `string.Format` to conditionally build HTML body, or can create some helper methods – sll Feb 04 '12 at 15:55
  • Anyways you need to fill in only `customBody` string, `htmlBody` is a standart header/footer – sll Feb 04 '12 at 15:58
0

You can simply assign html code to message body

message.Body = "<b> This is a bold Text </b>";
message.IsBodyHTML = true;

Also, you can take advantage of MailDefinition Class. Check this link for the usage of this class.

NaveenBhat
  • 3,248
  • 4
  • 35
  • 48
0

Use isHtmlBody property, from MailMessage

Example:

MailMessage msg = new MailMessage();
msg.Body= "example of <a href='www.something.com'>Link</a>";
msg.IsBodyHtml = True;
...    
smtp.send(msg)

see :

IsBodyHtml Property

Example

Rodrigo Gauzmanf
  • 2,517
  • 1
  • 23
  • 26
0

string.Format() might be what you are after.

string.Format() replaces each format item in a specified string with the text equivalent of a corresponding object's value.

So for instance

 string.Format("Dear {0} {1}, You are {2} today.",
       person.Title, person.Lastname, person.Age);
Ian G
  • 29,468
  • 21
  • 78
  • 92