2009-07-09 2 views
5

... <MailDefinition> và <%%> placeholders


BodyFileName thuộc tính tài liệu tham khảo tập tin trên đĩa có chứa văn bản cơ thể mail. Nếu chúng tôi đặt giữ chỗ <% UserName %><% Password %> trong tệp văn bản nội dung (RegistrationMail.txt), thì CreateUserWizard sẽ tự động thay thế các trình giữ chỗ này bằng tên người dùng và mật khẩu của người dùng được tạo.

A) Nếu tôi muốn tạo điều khiển cũng có thể thay thế trình giữ chỗ <% %> trong tệp bằng một số văn bản, tôi sẽ làm như thế nào?

B) Tôi cũng có thể viết vào các trình giữ chỗ này từ mã phía sau tệp không? Có nghĩa là, có một số phương pháp mà khi được gọi, viết văn bản cụ thể vào giữ chỗ chứa bên trong một số tập tin txt?


thanx

Trả lời

9

Một string.Replace đơn giản() được gọi trong trường hợp SendingMail hiện các trick.

protected void CreateUserWizard1_SendingMail(object sender, MailMessageEventArgs e) 
{ 
    // Replace <%foo%> placeholder with foo value 
    e.Message.Body = e.Message.Body.Replace("<%foo%>", foo); 
} 

Tạo cơ chế gửi email của riêng bạn cũng không khó.

using(MailMessage message = new MailMessage()) 
{ 
    message.To.Add("[email protected]"); 
    message.Subject = "Here's your new password"; 
    message.IsBodyHtml = true; 
    message.Body = GetEmailTemplate(); 

    // Replace placeholders in template. 
    message.Body = message.Body.Replace("<%Password%>", newPassword); 
    message.Body = message.Body.Replace("<%LoginUrl%>", HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + FormsAuthentication.LoginUrl); // Get the login url without hardcoding it. 

    new SmtpClient().Send(message); 
} 

private string GetEmailTemplate() 
{ 
    string templatePath = Server.MapPath(@"C:\template.rtf"); 

    using(StreamReader sr = new StreamReader(templatePath)) 
     return sr.ReadToEnd(); 
}