c# - 如何使用 SendGrid for C# 发送以 UTF-8 编码的文本/html 的电子邮件?

标签 c# email smtp sendgrid

我正在尝试发送包含 á、é、ó、í、ú 等特殊字符的电子邮件。我的代码如下所示:

try
{
   Mail message = Mail.GetInstance();
   foreach (Users u in users)
   {
       message.AddBcc(u.Email);
   }
   message.From = new MailAddress(Microsoft.WindowsAzure.CloudConfigurationManager
       .GetSetting("emailFrom"), Microsoft.WindowsAzure.CloudConfigurationManager
       .GetSetting("emailFromName"));
   message.Subject = Microsoft.WindowsAzure.CloudConfigurationManager
       .GetSetting("emailSubject");

   message.Html = "<meta charset=\"UTF-8\"/>" + 
       Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailText1") + 
       " " + address+ ".<br/>" + 
       Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailText2");

   var transport = SMTP.GetInstance(new NetworkCredential(
       Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailLogin"), 
       Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailPass")));
   transport.Deliver(message);
   isEmailSent = true;
}
catch (Exception ex)
{
    Debug.WriteLine(ex.Message + " \n " + ex.InnerException + " \n " + ex.StackTrace);
    isEmailSent = false;
}

我试图在我发送的 Html 中指定字符集,但它不起作用,而不是发送这个 San Jerónimo Amanal,这就是正在发送的 San Jerónimo Amanal

如何以正确的编码发送它?任何帮助将不胜感激。

编辑

我尝试了这两种方法:

   message.Html = "<meta charset=\"UTF-8\"/>" + 
       Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailText1") + 
       " " + address+ ".<br/>" + 
       Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailText2");

还有这个:

   message.Html = Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting
       ("emailText1") + " " + address+ ".<br/>" + 
       Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailText2");

但电子邮件仍在以错误的编码发送。

编辑 2

我试过这个问题的答案Converting Unicode strings to escaped ascii string ,更具体地说,我尝试了 EncodeNonAsciiCharacters 方法,但我在电子邮件 San Jer\u00c3\u00b3nimo Amanal 中收到了这个。我在这方面采取了错误的方法吗?

最佳答案

好吧,这花了一些时间,但至少我找到了一种发送没有特殊字符的电子邮件的方法,我不得不 normalize我通过规范化形式兼容性分解得到的字符串,这是通过 String 类完成的'Normalize method像这样:

string normalizedString = InString.Normalize(NormalizationForm.FormKD);

引用自维基百科:

characters are decomposed by compatibility, and multiple combining characters are arranged in a specific order.

意思是如果还有一个字符的兼容性由两个字符表示,那么它将被所述字符替换。对于像 é 这样的字符,它将被替换为 e。

关于c# - 如何使用 SendGrid for C# 发送以 UTF-8 编码的文本/html 的电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17554238/

相关文章:

c# - 内联 if 语句以确定 i++ 或 i-- 在 for 循环中递增

c# - 如何在 Orchard 的特殊区域中为特殊小部件创建 View 替代?

python - GAE Python - 如何对邮件正文中的特殊字符进行编码?

asp.net - 电子邮件上的 CSS

java - 如何强制JavaMailSenderImpl使用TLS1.2?

c# - 如何将数组的字符串复制到列表<string>?

c# - 与数据库绑定(bind)后在下拉列表中添加默认值

java - 从字符串中提取电子邮件

django - 如何使用 google smtp 服务器从 django 发送电子邮件?

python - logging.handlers.SMTPHandler 引发 smtplib.SMTPAuthenticationError