Formatting a plain text e-mail in C#

2020-05-05 04:15发布

问题:

I am trying to print a table inside an e-mail using plain text. I have the following code:

string body = string.Format("{0,-30}{1,-30}{2,-50}{3,-40}",
                                   "Col1", "Col2", "Col2", “Col4”);

body += string.Format("{0,-30}{1,-30}{2,-50}{3,-40}",
                                value1, value2, value3, value4);

Microsoft.Office.Interop.Outlook.ApplicationClass myOutlookApplication = null;
myOutlookApplication = new Microsoft.Office.Interop.Outlook.ApplicationClass();
Microsoft.Office.Interop.Outlook.MailItem myNewMail = 
    (Microsoft.Office.Interop.Outlook.MailItem)myOutlookApplication.CreateItem( 
      Microsoft.Office.Interop.Outlook.OlItemType.olMailItem );            

myNewMail.To = recipient;
myNewMail.Subject = subject;
myNewMail.Body = body;
myNewMail.BodyFormat = OlBodyFormat.olFormatPlain;            

myNewMail.Send();

The problem I have is that the text for the body does not line up. It also seems to wrap the text inside the mail. Can anyone tell me what I may be doing wrong here?

回答1:

Creating (or actually imitating the behaviour of) a table in plain text only works well when:

  1. The values in your tables are exactly the same width as the widht of the column. This is something you (the programmer) should take care of by trailing the text with spaces when the text is too short or cutting of the text if is too long.

  2. The user that is receiving the text is using a monospace font (http://en.wikipedia.org/wiki/Monospaced_font) to view the table. And that is unfortunately beyond your control if you send the table in an e-mail message...



回答2:

That's due to fonts. If you want it to line up, you need to use a fixed width font like your code editor hopefully does.

Else you can attempt something using TAB's. But that can be tricky.