Search code examples
c#email.net-6.0mailkitmimekit

MailKit: ParseException when parsing an email string with email-address in displayname


I am currently working on a microservice that runs on DotNet6 and is using MailKit 3.1.0. I have the following code snippet:

var from = "John Doe via noreply@company.com <noreply@company.com>";
var mailBoxAddress = MailboxAddress.Parse(from);

The second line of code leads to following Exception: MimeKit.ParseException: Invalid addr-spec token at offset 0

I did some testing and found out that the following variations of the string work:

var fromAlternative1 = "John Doe via noreplycompany.com <noreply@company.com>";  // missing @
var fromAlternative2 = "JohnDoevianoreply@company.com<noreply@company.com>";  // no empty space

This leads me to the question wether it could exist a configuration that enables parsing the from string, there could be a bug or this behaviour is by design?

As a workaround im parsing the displayname and email-address by myself.


Solution

  • You need to properly quote the name if it contains @ symbols or ..

    Those are special characters that are required to be quoted by the email specifications.

    In other words, the correct string would be:

    "John Doe via noreply@company.com" <noreply@company.com>
    

    Or, in C#:

    var from = "\"John Doe via noreply@company.com\" <noreply@company.com>";