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

时间:2017-06-25 17:31:24

标签: c# utf-8 gmail-api google-api-dotnet-client iso-8859-1

我正在开发一个可以发送带有附件的电子邮件的应用程序,它可以工作,直到我尝试使用特殊字符æ,ø,å。

enter image description here

我玩了一些测试不同的编码,看起来这个主题是用ISO-8859-1编码的,而其余的邮件是用UTF-8编码的。

以下是我生成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”无法修复此问题,并使附加文件在正文中显示为Base64

1 个答案:

答案 0 :(得分:0)

您可以使用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.