C# MailMessage with attachment breaks subject encoding

485 Views Asked by At

I'm sending e-mails with System.Net.Mail.SmtpClient. The problem is that when I add an attachment to the MailMessage the received e-mails subject and the attached filenames decoding goes wrong.

When the subject or attachment name string contains only one special character like 'ü' the decoding fails, but if it contains more like 'ÍŰÁÉÚŐÓÜÖíűáéúőóüö' the decoding is ok.

Code to reproduce the problem:

var message = new MailMessage();
message.From = new MailAddress("[email protected]", "test");
message.To.Add(new MailAddress("[email protected]", "test"));
message.Subject = "Teszt üzenet";
message.Body = "Teszt üzenet";

// if i remove the line below en/decoding is ok
message.Attachments.Add(new Attachment(@"document.pdf") { Name = "fájl.pdf" });

using (var smtp = new SmtpClient() {
  DeliveryFormat = SmtpDeliveryFormat.International,
  DeliveryMethod = SmtpDeliveryMethod.Network,
  EnableSsl = Settings.UseSsl,
  Host = Settings.Host,
  Port = Settings.Port,
  UseDefaultCredentials = false,
  Credentials = new NetworkCredential(Settings.Username, Settings.Password)
}) {
  smtp.Send(message);
}

Setting message.SubjectEcoding and others doesn't seem to matter. The default is UTF-8 which i would use anyway.

I'm using gmail smtp for testing and this is part of a webapi 2 project.

1

There are 1 best solutions below

0
On BEST ANSWER

The reason for the encoding/decoding failures was the gmail smtp.