2012-02-07 68 views
1

我有一个项目要求,我们需要将HTML格式的日志表附加到发送给用户的电子邮件。 我不希望日志表成为正文的一部分。我宁愿不使用HTMLTextWriter或StringBuilder,因为日志表非常复杂。在运行时生成HTML文件并作为电子邮件附件发送

是否有另一种方法,我没有提及或使这更容易的工具?

注意:我已经使用MailDefinition类并创建了一个模板,但是我还没有找到一种方法将此附件设置为可能。

回答

3

既然您使用的是WebForms,我会推荐rendering your log sheet in a Control as a string,然后attaching that to a MailMessage

渲染部分看起来有点像这样:

public static string GetRenderedHtml(this Control control) 
{ 
    StringBuilder sbHtml = new StringBuilder(); 
    using (StringWriter stringWriter = new StringWriter(sbHtml)) 
    using (HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter)) 
    { 
     control.RenderControl(textWriter); 
    } 
    return sbHtml.ToString(); 
} 

如果您有可编辑控件(TextBoxDropDownList,等等),你需要调用GetRenderedHtml()之前,标签或常量来替换它们。完整的示例请参阅this blog post

这里的MSDN example for attachments

// Specify the file to be attached and sent. 
// This example assumes that a file named Data.xls exists in the 
// current working directory. 
string file = "data.xls"; 
// Create a message and set up the recipients. 
MailMessage message = new MailMessage(
    "[email protected]", 
    "[email protected]", 
    "Quarterly data report.", 
    "See the attached spreadsheet."); 

// Create the file attachment for this e-mail message. 
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet); 
// Add time stamp information for the file. 
ContentDisposition disposition = data.ContentDisposition; 
disposition.CreationDate = System.IO.File.GetCreationTime(file); 
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); 
disposition.ReadDate = System.IO.File.GetLastAccessTime(file); 
// Add the file attachment to this e-mail message. 
message.Attachments.Add(data); 
2
+0

我不是目前使用MVC,所以我不相信这是一个选项,做的工作。 – Matt 2012-02-07 13:34:45

+0

@Matt剃刀模板也适用于网页表单。 – adt 2012-02-07 13:38:11

+2

好吧,这是很好的知道,但不幸的是,我仍然运行asp.net 3.5,看起来RazorEngine需要4.0 – Matt 2012-02-07 13:55:55

相关问题