我正在尝试使用电子邮件类 MailMessage 和 SMTPClient 在 ASP.NET 中发送电子邮件。该代码工作正常,但当收件人地址包含丹麦字符时,例如Niels.Østergaard@company.dk,Send() 方法抛出一个异常,提示地址的格式。如何解决这个问题?这段代码如下:
MailMessage mail = new MailMessage();
//set the addresses
MailAddress fromAddress = new MailAddress(from);
foreach (string s in to)
{
mail.To.Add(new MailAddress(s));
}
mail.From = fromAddress;
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = false;
// Include attachments if any
if (files != null)
{
foreach (string file in files)
{
mail.Attachments.Add(new Attachment(string.Format("{0}\\{1}",
HttpContext.Current.Server.MapPath("~/Temp"), file)));
}
}
// These settings should be retrieved from web.config
SmtpClient smtp = new SmtpClient();
smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
smtp.PickupDirectoryLocation = @"C:\Temp\Mail";
smtp.Send(mail);
请您参考如下方法:
我使用 http://msdn.microsoft.com/en-us/library/system.globalization.idnmapping.aspx 取得了一些成功来解决这个问题。
像这样:
var m = new IdnMapping();
var parts = "Niels.Østergaard@company.dk".Split('@');
var adr = new MailAddress(string.Concat(
m.GetAscii(parts[0]),
"@",
m.GetAscii(parts[1])));
