2012-02-04 133 views
-1

我正在以HTML格式向我的用戶發送電子郵件。有很多的編輯,如用戶名,用戶生日和其他許多細節。現在將HTML頁面轉換爲字符串

,我不希望我的代碼是這樣的:

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

是否有任何C#工具可以使用,以方便編輯?

+0

請顯示一些源代碼...你有什麼試過?什麼不工作? – Yahia 2012-02-04 15:13:38

回答

2

看來你希望能夠在一個單一的字符串來指定命名令牌,使這個HTML很容易閱讀和編輯,像這樣:

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

看看這個答案的一些方法來做到這一點:Named string formatting in C#

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); 

請參閱MSDN:

+0

請再次檢查我的問題,只需編輯它。 – 2012-02-04 15:28:24

+0

查看更新回答 – sll 2012-02-04 15:32:11

+0

如何doe它使得它易於編輯?我得到另外20個參數來推送... – 2012-02-04 15:35:43

0

您可以HTML代碼簡單地分配給message body

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

另外,您可以利用MailDefinition Class。請查看this link瞭解該課程的用法。

+0

請再次檢查我的問題,只需編輯它。 – 2012-02-04 15:29:05

0

使用isHtmlBody財產,MAILMESSAGE從

例子:

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

見:

IsBodyHtml Property

Example

+0

請再次檢查我的問題,只需編輯它。 – 2012-02-04 15:29:35

0

string.Format()可能是你所追求的。

string.Format()將指定字符串中的每個格式項替換爲相應對象值的文本。

因此,例如

string.Format("Dear {0} {1}, You are {2} today.", 
     person.Title, person.Lastname, person.Age);