特殊字符@ /防止电子邮件中的换行

本文关键字:换行 电子邮件 特殊字符 | 更新日期: 2023-09-27 18:04:26

我有一个ASP。. NET MVC应用程序,我使用System.Net.Mail类发送电子邮件。

SmtpClient client = new SmtpClient(AppConstants.SmptHostName);
client.Credentials = new NetworkCredential(AppConstants.SmptUsername, AppConstants.SmptPassword);
MailAddress from = new MailAddress(emailSettings.AdminEmailAddress, emailSettings.EmailSender);
MailAddress to = new MailAddress(emailSettings.ApplicationEmailAddress);
MailMessage message = new MailMessage(from, to);
message.Body = GetApplicationEmail();
message.Subject = "New Application";
client.Send(message);

我正在构建由不同应用程序导入的电子邮件,格式为:

String.Format("{0}:{1}{2}", "FieldName", "FieldValue", Environment.NewLine);
private string GetApplicationEmail()
    {
            string messageContents = "";
            var fieldList = _fieldList;
            foreach (var field in fieldList)
            {
                messageContents += String.Format("{0}:{1}{2}", field.Name, field.Value, Environment.NewLine);
            }
            return messageContents;
     }

电子邮件看起来像这样:

Field1:Value1
Field2:Value2
Field3:Value3

我的问题出现在特殊字符,特别是如正斜杠/或@符号在值中。每个字段值组合不是在单独的行上,而是在一行上。如:

Field1:Value1
Field2:Value2
Field3:Different/Value Field4:Extra / LongValue Field5:PeanutsAreGood
Field6:Another Value

电子邮件以"纯文本"形式发送。我不能对特殊字符进行编码,也不能转义诸如正斜杠之类的字符。

我目前唯一的解决方案是用空格替换字符,但是这会破坏功能。还有别的解决办法吗?

特殊字符@ /防止电子邮件中的换行

一种解决方案是使用message.IsBodyHtml = true

发送HTML格式的电子邮件。

你能这样做吗?

 class Program
  {
    static void Main(string[] args)
    {
      SmtpClient client = new SmtpClient("smtp.gmail.com");
      client.EnableSsl = true;
      client.Port = 587;
      client.Credentials = new NetworkCredential("someEmail", "somePass");
      MailAddress from = new MailAddress("from", "Name");
      MailAddress to = new MailAddress("toEmail");
      MailMessage message = new MailMessage(from, to);
      string fieldName = @"$%^^TheField";
      string fieldValue = @"the test value)(/%";
      string string1 = String.Format("{0}:{1}{2}", fieldName, fieldValue, Environment.NewLine);
      string fieldName2 = @"anotheremail@mail.com/'";
      string fieldValue2 = @"'#the test value2";
      string string2 = String.Format("{0}:{1}{2}", fieldName2, fieldValue2, Environment.NewLine);
      List<string> messageBody = new List<string>();
      messageBody.Add(string1);
      messageBody.Add(string2);
      foreach (string str in messageBody)
      {
        message.Body += str;
      }
      message.Subject = "New Application";
      client.Send(message);
      //NonStaticClass cls = new NonStaticClass();
      //cls.GetVariable();
    }