0

I'm using C# and MimeKit (AE.Net.Mail) to send email through Gmail. Everything works perfectly, until I have an accented name in the body.

I have been unable to figure out how to send the accented characters properly. This is where I am with the code right now. I've tried many dozens of iterations, and so far, nothing works. I've tried encoding in various formats, none of it worked, so I removed all of that for this example. I want to reiterate. The email works perfectly, it's just the accented characters that cause an issue. I know it's related to encoding, but I just can't find the secret sauce to get it to work. (Note, the answer does need to work in all major mail clients)

var msg = new AE.Net.Mail.MailMessage
{
     Subject = "Hello Tést",
     From = new MailAddress("support@domain.com"),
     Sender = new MailAddress("support@domain.com"),
     Body = "Dear Tést, Thanks",
     ContentType = "text/html",
     Importance = AE.Net.Mail.MailPriority.Normal,
};
msg.ReplyTo.Add("support@domain.com");
var mimeMessage = MimeMessage.CreateFromMailMessage(msg);
var result = new GmailService(new BaseClientService.Initializer()
{
       HttpClientInitializer = GetCredentials("support@domain.com"),
       ApplicationName = "DomainApp",
})
.Users.Messages.Send(new Message
{
       Raw = urlSafeToBase64(mimeMessage.ToString())
},
"me");
var t = result.ExecuteAsync().GetAwaiter().GetResult();


private string urlSafeToBase64(string input)
{
    return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(input))
    .Replace('+', '-')
    .Replace('/', '_')
    .Replace("=", "");
}
Brian Kitt
  • 665
  • 1
  • 6
  • 20
  • [Possible duplicate of this](https://stackoverflow.com/questions/44748843/unable-to-encode-special-characters-email-in-right-format-gmail-api-ae-net-ma) – ProgrammingLlama Dec 22 '21 at 02:52
  • That is for the subject line. My subject line is working correctly. I just need to get UTF-8 working in the body, and nothing I am doing is working. – Brian Kitt Dec 23 '21 at 00:27

1 Answers1

1

This is the cause of the problem:

Raw = urlSafeToBase64(mimeMessage.ToString())

The ToString() method is not meant for doing stuff like this, it's only meant for debugging purposes. See the docs: http://www.mimekit.net/docs/html/M_MimeKit_MimeMessage_ToString.htm

You will need to write the message to a Stream and then modify your urlSafeToBase64() method to either take a stream or a byte[]

jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • OMG!!! That was it!! The example that I started from, used the .ToString, and I never thought to question it. THANK YOU SO MUCH!!! That fixed it with no other code changes!!!! That explains why every example I tried, failed. All of the changes I was making were in the message object, not the 'raw' part of the send object. THANKS!! – Brian Kitt Dec 24 '21 at 21:46