无法编码特殊字符的电子邮件以正确的格式,gmail api&ae.net.mail

问题描述:

我正在研究一个应用程序,它可以发送带有附件的电子邮件,它可以工作,直到我尝试特殊字符æ,ø,å。无法编码特殊字符的电子邮件以正确的格式,gmail api&ae.net.mail

enter image description here

我打得有点左右测试不同的编码,它看起来像的主题是ISO-8859-1进行编码,而邮件的休息UTF-8编码。

这里是我的方法产生一个谷歌Gmail API消息

 public Message CreateMessage(string to, string from, string body, string subject, GmailService service, string[] files = null, string bcc = null) 
    { 
     AE.Net.Mail.MailMessage message = new AE.Net.Mail.MailMessage() 
     { 
      Subject = subject, 
      Body = body, 
      From = new MailAddress(from), 
     }; 

     message.To.Add(new MailAddress(to)); 
     message.ReplyTo.Add(message.From); 

     message.Headers.Add("Content-Type", "text/plain; charset=utf-8"); 

     if (bcc != null) 
      message.Bcc.Add(new MailAddress(bcc)); 

     if (files != null) 
     { 
      foreach(string file in files) 
      { 
       using (var opennedFile = File.Open(file, FileMode.Open, FileAccess.Read)) 
       using (MemoryStream stream = new MemoryStream()) 
       { 
        string[] FileName = file.Split('\\'); 
        opennedFile.CopyTo(stream); 
        message.Attachments.Add(new AE.Net.Mail.Attachment(stream.ToArray(), MediaTypeNames.Application.Octet, FileName[FileName.Length - 1], true)); 
       } 
      } 
     } 

     var msgStr = new StringWriter(); 
     message.Save(msgStr); 

     return new Message() { 
      Raw = Base64UrlEncode(msgStr.ToString()), 
     }; 
    } 

    private static string Base64UrlEncode(string message) 
    { 
     var inputBytes = Encoding.GetEncoding("utf-8").GetBytes(message); 
     return Convert.ToBase64String(inputBytes).Replace('+', '-').Replace('/', '_').Replace("=", ""); 
    } 

message.ContentType =“text/plain的;字符集= UTF-8”不解决这个问题,使附加的文件显示在body Base64

+0

其中是从截屏? – DaImTo

您可以使用the following technique在主题头中使用UTF-8。

=?charset?encoding?encoded-text?= 

你可以然后使用charset=utf-8encoding=B(B = BASE64),和编码的受试者encoded-text

Subject: =?utf-8?B?aGVsbG8=?= // 'aGVsbG8=' is 'hello' in base64 format. 
+1

我不知道有什么区别,因为我已经测试过,但不知何故,你的例子为我工作 – dark2222