Using SmtpClient
, MailMessage
and MailAddress
classes, I cannot send to email addresses such as åbc.def@domain.se. I get the error/exc
To be able to to send UTF-8 characters according to RFC6531 both client and server need to support it.
If you use the .NET implementation of SmtpClient
you'll need to target framework version 4.5 because that implementation supports the SMTPUTF8 extension.
If you set the DeliveryFormat property you have done what is needed for your client to support UTF8 characters:
using (var smtp = new SmtpClient())
{
smtp.DeliveryFormat = SmtpDeliveryFormat.International;
var message = new MailMessage(
"my.email@gmail.com",
"ëçïƒÖ@example.com",
"UTF8",
"Is UTF8 supported?");
smtp.Send(message);
}
If we reverse-engineer the Send
method we can easily follow the stack-trace from your question. You'll find this implementation:
if (!allowUnicode && !MimeBasePart.IsAscii(this.userName, true))
{
throw new SmtpException(SR.GetString("SmtpNonAsciiUserNotSupported", new object[]
{
this.Address
}));
}
That allowUnicode
boolean is being supplied from the Send
method:
if (this.DeliveryMethod == SmtpDeliveryMethod.Network)
{
return this.ServerSupportsEai && this.DeliveryFormat == SmtpDeliveryFormat.International;
}
Now here comes the server in the picture. When does the private boolean ServerSupportsEai
becomes true? It turns out that on sending the EHLO
command the SmptConnection
calls ParseExtensions
:
if (string.Compare(text, 0, "SMTPUTF8", 0, 8, StringComparison.OrdinalIgnoreCase) == 0)
{
((SmtpPooledStream)this.pooledStream).serverSupportsEai = true;
}
If you want to know upfront if your mail server is supporting that extension you can simply connect with a telnet client (I use putty) to your smtp server and send the EHLO somename
command and inspect the results.
Connecting to smtp.gmail.com
on port 587 gives me this output:
220 smtp.gmail.com ESMTP hx10sm19521922wjb.25 - gsmtp
EHLO fubar
250-smtp.gmail.com at your service, [2001:FFF:8bef:1:34d6:a247:FFFF:4620]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
Notice the last line: it holds our required SMTPUTF8
tl;dr
To be able to use international characters in the emailaddres make sure to set the DeliveryFormat
to SmtpDeliveryFormat.International
and use an smtp server that supports the SMTPUTF8 extension and advertises it in its EHLO
command.