Microsoft, have you ever stepped on ?, Microsoft click

Source: Internet
Author: User
Tags mailmessage smtpclient

Microsoft, have you ever stepped on ?, Microsoft click

Recently, I am working on a simple little tool. The requirement is probably like this. I am working on a scheduled task system to regularly collect related business data from the server and generate relevant reports, then, it is sent to relevant personnel in Excel format. The task is very simple, the scheduled task is OK, the report generation is OK, And the Excel export is OK. The exported Excel file is placed in the temp directory of drive C, and the sending time is set. Everything is done properly, the results are also very good. After 10 seconds (this is also a test, the time is set to be short), the email is received properly, and the excel table in the attachment can be opened properly, the report is OK. Oh, yeah, so, easy.... If the result is so good, package and release it.

If 100 words are omitted here, the deployment is complete.

Tick .. Didi da... 10 seconds, 20 seconds, 30 seconds ,... I did not make a mistake. I set it to run once every 10 seconds in the official environment to report it first? This 10 seconds is too long, right? It took about 1 minute. Well, it should have been a problem. I was still wondering if there was a problem with deployment. Shouldn't it be? Is that a simple tool?

200 words are omitted here. Check that the deployment is normal. Okay, check the log.

Sure enough, an error is reported, and the error is still very arrogant:

System. FormatException: An invalid character was found in the mail header: 'Week '.
At System. Net. Mime. MailBnfHelper. GetTokenOrQuotedString (String data, StringBuilder builder)
At System. Net. Mime. ContentDisposition. ToString ()
At System. Net. Mime. ContentDisposition. PersistIfNeeded (HeaderCollection headers, Boolean forcePersist)
At System. Net. Mime. MimePart. Send (BaseWriter writer)
At System. Net. Mime. MimeMultiPart. Send (BaseWriter writer)
At System. Net. Mail. SmtpClient. Send (MailMessage message)
--- End of inner exception stack trace ---
At System. Net. Mail. SmtpClient. Send (MailMessage message)

No error. An invalid character was found in the mail header "Week "? This should be a garbled message, right? On the page, I used SmtpClient to send emails directly. I didn't set the header at all?

1000 words are omitted here, various Niang, various google, various anti-spoofing mail headers, MIME knowledge, and various settings of the attachment ContentType. The results are the same. The only difference is garbled characters, from "Week" to "Week".

2000 words are omitted here. I suddenly heard from my colleagues that it may be related to CurrentCulture. It was so bright that I had to google it. As a result, I had the answer.

. Net 4.0 has a Bug: Culture Bug in ContentDisposition, that is, you only need to set the ContentDisposition time, any time, such as CreationDate, or ModificationDate ,. net internally, the time will be passed to SmtpDateTime by calling the toString method of DateTime, the problem occurs, these time formats are related to the local language environment, toString is likely to have problems. (The official statement is to fix this problem in vs2013) Well, it's easy to find the problem. It's related to the Culture, and I don't want to upgrade it. net Framework, so it has nothing to do with CurrentCulture.

 1  var currentCulture = Thread.CurrentThread.CurrentCulture; 2             var attachment = new Attachment(attachmentFile, displayName); 3             try 4             { 5                 ... 6                 Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;               7                 attachment.ContentDisposition.CreationDate = File.GetCreationTime(attachmentFilePath); 8                 attachment.ContentDisposition.ModificationDate = File.GetLastWriteTime(attachmentFilePath); 9                 attachment.ContentDisposition.ReadDate = File.GetLastAccessTime(attachmentFilePath);10                 ...11             }12             finally13             {14                 Thread.CurrentThread.CurrentCulture = currentCulture;15             }

Sure enough, the "Week" that the other person hated disappeared. The email arrived in 10 seconds. Haha, you can finally close the job. And so on... why is there no file name after I have a good Excel attachment? (actually, it's just garbled and not displayed? Oh, are you kidding me? My local development environment is good !!

3000 words are omitted here, various attempts, various ways of using netizens, various irrational attempts, and various .. The final result is fruitless.

I was about to give up the time. I suddenly remembered that I had a problem with stackoverflow.com. Okay, I am confused. Who told me that I should have been off work two hours ago, and now I have no clue about the problem. Indeed, this problem was discovered n years ago and is still a pitfall of our lovely Microsoft:

  

(Machine Translation, you will be watching it ).

Okay, I lost. I love you too deeply and never doubt you.

But I still don't want to upgrade the Framework or production environment.

Try to use ZYD to split the file name encoding first. The problem can be solved:

  

1 .. 2 Attachment attachment = null; 3 // Add Attachment 4 if (! String. isNullOrEmpty (attachmentFilePath) & File. exists (attachmentFilePath) 5 {6 attachment = CreateAttachment (WriteFileToMemory (attachmentFilePath), attachmentFileName, contentType, attachmentFilePath); 7 message. attachments. add (attachment); 8 9} 10... 11 12 public static Attachment CreateAttachment (Stream attachmentFile, string displayName, string contentType, string attachmentFilePath) 13 {14 var CurrentCulture = Thread. currentThread. currentCulture ;//. net4.0 bug, 15 var attachment = new Attachment (attachmentFile, displayName); 16 try17 {18 Thread. currentThread. currentCulture = CultureInfo. invariantCulture; 19 attachment. contentType = new ContentType (contentType); 20 attachment. contentDisposition. creationDate = File. getCreationTime (attachmentFilePath); 21 attachment. contentDisposition. modificat IonDate = File. getLastWriteTime (attachmentFilePath); 22 attachment. contentDisposition. readDate = File. getLastAccessTime (attachmentFilePath); 23 attachment. transferEncoding = TransferEncoding. base64; 24 attachment. nameEncoding = Encoding. UTF8; 25 string encodedAttachmentName = Convert. toBase64String (Encoding. UTF8.GetBytes (displayName); 26 encodedAttachmentName = SplitEncodedAttachmentName (encodedAttach MentName); 27 attachment. name = encodedAttachmentName; 28} 29 finally30 {31 Thread. currentThread. currentCulture = currentCulture; 32} 33 return attachment; 34} 35 36 private static Stream WriteFileToMemory (string filePath) 37 {38 var fileStream = new FileStream (filePath, FileMode. open, FileAccess. read); 39 return fileStream; 40} 41 42 private static string SplitEncodedAttachmentName (string encoded) 43 {4 4 const string encodingtoken = "=? UTF-8? B? "; 45 const string softbreak = "? = "; 46 const int maxChunkLength = 30; 47 int splitLength = maxChunkLength-encodingtoken. length-(softbreak. length * 2); 48 IEnumerable <string> parts = SplitByLength (encoded, splitLength); 49 string encodedAttachmentName = encodingtoken; 50 foreach (var part in parts) 51 {52 encodedAttachmentName + = part + softbreak + encodingtoken; 53} 54 encodedAttachmentName = encodedAttachmentName. remove (encodedAttachmentName. length-encodingtoken. length, encodingtoken. length); 55 return encodedAttachmentName; 56} 57 58 private static IEnumerable <string> SplitByLength (string stringToSplit, int length) 59 {60 while (stringToSplit. length> length) 61 {62 yield return stringToSplit. substring (0, length); 63 stringToSplit = stringToSplit. substring (length); 64} 65 if (stringToSplit. length> 0) 66 {67 yield return stringToSplit; 68} 69}View Code

The process is bumpy and the ending is wonderful!

I love you too deeply and never doubt you. I can't help but use it for conclusion!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.