问题
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.
Here is my method that generates a Google Gmail API message
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
回答1:
You could use the following technique to use UTF-8 in the subject header.
=?charset?encoding?encoded-text?=
You could then use charset=utf-8
, encoding=B
(B = base64), and encoded subject as encoded-text
.
Example
Subject: =?utf-8?B?aGVsbG8=?= // 'aGVsbG8=' is 'hello' in base64 format.
来源:https://stackoverflow.com/questions/44748843/unable-to-encode-special-characters-email-in-right-format-gmail-api-ae-net-ma