Email address encoding issues
.net, asp.net, c#
Solution
Please look at this example below using System.Uri class methods, hope it helps you
string email = "Confirmación@test.com";
string escaped =
System.Uri.EscapeDataString(email); // Confirmaci%C3%B3n%40test.com
string unescaped =
System.Uri.UnescapeDataString(email); //Confirmación@test.com
Problem
I have the following string I need to use for a confirmation email 'from' address. This is the spanish translation which is causing a problem when viewing within a web client. Shown below. ``` model.FromAddresses = new EmailAddress { Address = fromAddressComponents[0], DisplayName = fromAddressComponents[1] }; ``` Value taken from a resource string, shown below ``` <data name="BookingConfirmation_FromAddress" xml:space="preserve"> <value>Confirmación@test.com</value> </data> ``` Within the email client the value becomes (should be Confirmación@test.com) ``` =?utf-8?Q?Confirmaci=C3=B3n ``` Can you see how to avoid this? I know it's because of the ó but I'm not sure how to avoid this problem! Thanks, James UPDATE Full code below: ``` public void Send(MailAddress to, MailAddress from, string subject, string body) { var message = new MailMessage { BodyEncoding = new System.Text.UTF8Encoding(true), From = from, Subject = subject, Body = body, IsBodyHtml = true }; message.To.Add(to.Address); var smtp = new SmtpClient() { Timeout = 100000 }; try { smtp.Send(message); } finally { if (smtp.DeliveryMethod == SmtpDeliveryMethod.Network) smtp.Dispose(); } } // New Version // -------------------------- public override void Handle(SendEmailEmailCommand emailCommand) { if(!_config.SendEmail) { return; } var to = new MailAddress(emailCommand.To.Address, emailCommand.To.DisplayName); var from = new MailAddress(emailCommand.From.Address, Uri.UnescapeDataString(emailCommand.From.DisplayName)); try { var msgBody = _compressor.Decompress(emailCommand.Body); _emailClient.Send(to, from, emailCommand.Subject, msgBody); } catch (Exception ex) { _logger.Error("An error occurred when trying to send an email", ex); throw; } } public void Send(MailAddress to, MailAddress from, string subject, string body) { var message = new MailMessage { BodyEncoding = new System.Text.UTF8Encoding(true), From = from, Subject = subject, Body = body, IsBodyHtml = true }; message.To.Add(to.Address); if (!string.IsNullOrWhiteSpace(_config.BccEmailRecipents)) { message.Bcc.Add(_config.BccEmailRecipents); } SendEmail(message); if (_config.BackupEmailsEnabled) { SendBackupEmail(message); } } private void SendEmail(MailMessage message) { var smtp = new SmtpClient() { Timeout = 100000 }; try { smtp.Send(message); } finally { if (smtp.DeliveryMethod == SmtpDeliveryMethod.Network) smtp.Dispose(); } } ```