<MailDefinition>和<%%>占位符

5

BodyFileName属性引用包含电子邮件正文文本的磁盘文件。如果我们在正文文本文件(RegistrationMail.txt)中放置占位符<% UserName %><% Password %>,那么CreateUserWizard将自动用创建的用户的用户名和密码替换这些占位符。

A)如果我想创建一个控件,也能够用一些文本替换文件中的占位符<% %>,我该怎么做?

B)我能否从代码后台文件中写入这些占位符?也就是说,是否有一种方法,当调用时,将特定的文本写入包含在某个txt文件中的占位符?


谢谢

1个回答

9
在发送邮件事件中调用简单的string.Replace()函数即可解决问题。
protected void CreateUserWizard1_SendingMail( object sender, MailMessageEventArgs e )
{
    // Replace <%foo%> placeholder with foo value
    e.Message.Body = e.Message.Body.Replace( "<%foo%>", foo );
}

自己创建电子邮件机制并不太困难。

using( MailMessage message = new MailMessage() )
{
    message.To.Add( "none@none.com" );
    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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接