2012-02-07 73 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

相關問題