2012-02-03 52 views
1

我有一個純文本文件,需要使用C#讀取,稍微操作一下,然後我需要給它發郵件。這是很容易的,但它也有留在相同的格式,因爲它的原始狀態:在不影響原文的情況下讀取純文本文本文件和電子郵件

這是一個示例文件「mySample.txt」的摘錄:

*****************************NB!!!!********************************** 
    *Please view http://www.sdfsdf.comsdfsdfsdf .      * 
    ********************************************************************* 


     *** DO NOT DELETE or ALTER ANY OF THE FOLLOWING TEXT *** 

          Company X PTY. 
        Lorem Ipsum Office 
        Last Change - 01 February 2008 

      APPLICATION TO ESTABLISH A COMMUNITY WITHIN 
       THE RESTIN DISTRICT OF THE IPSUM. 

    =================================================================== 

    1. COMMUNITY and ACTION 

    Give the name of the community. This is the name that will be 
    used in tables and lists associating the community with the name 
    district and community forum. The community names that are 
    delegated by Lorem are at the district level 
    The Action field specifies whether this is a 'N'ew application, an 
    'U'pdate or a 'R' removal. 

    1a. Complete community name:**{0}** 
    1b. Action - [N]ew, [U]pdate, or [R]emoval :**{1}** 

正如你可以看到我我已經在要由自動過程替換的文件中獲得了佔位符{0}和{1}。

在我的C#中,我使用流讀取器將整個文件讀入到StringBuilder對象中,然後使用StringBuilder.AppendFormat方法替換佔位符。

問題是,當我將文本添加到電子郵件正文併發送格式結果看起來不同。它看起來像一堆空格或製表符在流程中被刪除。

private void Submit_Click(object sender, EventArgs e) 
    { 
     //create mail client 
     System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); 
     System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); 
     message.To.Add(ConfigurationManager.AppSettings["SubmitToEmail"]); 
     message.Bcc.Add("[email protected]"); 
     message.Subject = "Test Subject"; 

     message.BodyEncoding = Encoding.ASCII; 
     message.IsBodyHtml = false; 
     message.Body = _PopulateForm(_GatherInput());//calls method to read the file and replace values 
     client.Send(message); 

     //cleanup 
     client = null; 
     message.Dispose(); 
     message = null; 

    } 

任何人有任何想法如何保持格式的機智?

感謝, 雅克

+1

純文本電子郵件不支持選項卡。如果您的原始文件包含選項卡,請將其展開爲空格。有一個命令可以在Visual Studio編輯器中執行此操作。 – arx 2012-02-03 14:56:38

+0

你能比我說「看起來不一樣」嗎?如果你在十六進制編輯器中打開它,確切地說缺少哪些字節? – 2012-02-03 14:58:01

+0

@arx命令是編輯 - >高級 - >解除選定的行。它必須在原始文本文件上完成。 – Alexandre 2012-02-03 14:59:11

回答

0

答案似乎與.net和郵件消息對象。不必將內容添加到Body屬性,您必須創建一個alternateView對象並將其添加到該對象。這解決了我的問題。

Regards, Jacques

0

你得到的問題是,您要發送純文本HTML。佈局變得很自然,因爲HTML的顯示方式與文本不同。純文本有新行(\n),製表符(\t)等,而HTML有換行符(<BR>)和不同的佈局方法。

如果我是你,我會第一個開始了用<BR>更換新線(應該有一個替換功能x.Replace("\n", "<BR>");

至於那些爲中心的文本項目,包起來<p style="text-align:center" }></p>

+0

嗨mj,我的文本文件是純文本,我正在閱讀到一個stringbuilder對象。消息正文設置爲Ascii,IsBodyHtml設置爲false。沒有涉及HTML? – Jacques 2012-02-03 15:22:40

+0

你用什麼瀏覽器/電子郵件客戶端查看郵件?如果是Outlook或類似的東西,可以選擇以純文本顯示。 – 2012-02-03 15:42:27

+0

這是前景,但絕對只是純文本。 – Jacques 2012-02-03 16:00:41

相關問題