简体   繁体   English

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

[英]unable to encode special characters email in right format, gmail api & ae.net.mail

I'm working on an application that can send emails out with attachments and it works, until I try special characters æ, ø, å. 我正在开发一个可以发送带有附件的电子邮件并且可以正常工作的应用程序,直到我尝试使用特殊字符æ,ø,å。

在此处输入图片说明

I played a bit around testing different encodings and it looks like the subject is being encoded in ISO-8859-1 while the rest of the mail is encoded in UTF-8. 我对测试不同的编码进行了一些测试,看起来主题是在ISO-8859-1中编码的,而其余邮件则是在UTF-8中编码的。

Here is my method that generates a Google Gmail API message 这是我生成Google 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; charset=utf-8" does not fix this issue and makes the attached files show in the body as Base64 message.ContentType =“ text / plain; charset = utf-8”无法解决此问题,并使附件在正文中显示为Base64

You could use the following technique to use UTF-8 in the subject header. 您可以使用以下技术在主题标头中使用UTF-8。

=?charset?encoding?encoded-text?=

You could then use charset=utf-8 , encoding=B (B = base64), and encoded subject as encoded-text . 然后,您可以使用charset=utf-8encoding=B (B = base64),并将编码后的主题用作encoding=B encoded-text

Example

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM