使用AlternateView生成HTML电子邮件的正确语法

时间:2014-12-09 23:53:50

标签: html asp.net email webforms system.net.mail

我正在尝试使用AlternateView来满足HTML和Text客户端的需求。我更喜欢使用HTML,只在必要时回退到文本。我开始重新编写一个旧的控制台应用程序来执行此操作,但我的代码中仍然有回车和换行符为“/ r / n”,我的问题是试图弄清楚如何以及在何处使用Environment.Newline而不是这些?

现在,正在从Web表单调用控制台应用程序。我在调试方面遇到了一些困难,最终的计划是为此创建一个WCF服务。

我认为我遇到的困难是确定AlternateView实际上为我做了什么,而不是我需要在文本和HTML版本中单独显式编码的电子邮件主体的数量。具体来说,我仍然在以下代码的最后一个块中有旧的回车和换行符,我正在试图找出一种更优雅的方法。

    // args[0] - Subject
    // args[1] - Message (uses all Environment.Newlines)
    // args[2] - RfpID

    static void Main(string[] args)
    {
        string subject = args[0];
        string message  = args[1];

        // Get programatic access to the email information stored in the web.config file
        string emailHost = WebConfigurationManager.AppSettings["EmailHost"];
        string fromAddress = WebConfigurationManager.AppSettings["FromEmailAddress"];

        SmtpClient client = new SmtpClient(emailHost);

        int count = 0;
        using (SqlDataReader dr = MailerDALC.GetAddressesByRFP(Convert.ToInt32(args[2])))
        {
            string hash;
            while (dr.Read())
            {
                MailMessage mailMessage = new MailMessage();

                mailMessage.IsBodyHtml = true;
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;

                using (AlternateView textPart = 
                    AlternateView.CreateAlternateViewFromString(mailMessage.Body,
                        System.Text.Encoding.UTF8, "text/plain"))
                {
                    textPart.TransferEncoding = 
                        System.Net.Mime.TransferEncoding.QuotedPrintable;
                    mailMessage.AlternateViews.Add(textPart);
                }

                using (AlternateView htmlPart = 
                    AlternateView.CreateAlternateViewFromString(mailMessage.Body,
                        System.Text.Encoding.UTF8, "text/html"))
               {
                   htmlPart.TransferEncoding = 
                       System.Net.Mime.TransferEncoding.QuotedPrintable;
                   mailMessage.AlternateViews.Add(htmlPart);
               }

               mailMessage.Priority = MailPriority.High;

               mailMessage.From = new MailAddress(fromAddress);
               mailMessage.Subject = subject;

               mailMessage.To.Add(new MailAddress(dr["EmailAddress"].ToString()));

               if ((bool)dr["SecondaryNotify"])
                   mailMessage.Bcc.Add(new MailAddress(dr["SecondaryEmail"].ToString()));

                   // Send email in batches of 100 with a 30 second pause between each batch 
                   if ((count >= 100) && (count % 100 == 0))
                       Thread.Sleep(30000);

                   // Check well-formedness of each email adddress
                   if (!IsWellformedEmailAddr(mailMessage.To.ToString()))       
                   {
                       LogError(dr[1].ToString() 
                        + " is a malformed email address. 
                            Message was not sent to this subscriber "
                                + dr[1].ToString() + ".", "");
                       continue;
                   }
                   else
                   {
                       mailMessage.Body = message; 

                       hash = dr["Hash"].ToString();
                       mailMessage.Body += 
                           "\n\nIf you no longer wish to receive notifications, you can "
                               + "unsubscribe and your details will be removed from our system:\n" 
                               + "http://example.com/apps/vendorreg/unsubscribe.aspx?unsub=" 
                               + hash + "\n\n";

                       mailMessage.Body += "My Website Policies:\n"
                           + "http://example.com/doc/help/policies/help_website_policies";

                        client.Send(mailMessage.From.Address, mailMessage.To[0].ToString(),
                            mailMessage.Subject, mailMessage.Body);

                        count++;
                   }
                   hash = "";
               } 
           } 
    }

1 个答案:

答案 0 :(得分:3)

正如我猜测的那样,我必须明确提供邮件正文的纯文本和HTML版本。 MSDN文档不是很有帮助。以下是我为使其工作而创建的代码片段:

// args[0] - Subject
// args[1] - Plain text body content
// args[2] - HTML body content
// args[3] - RfpID

textMessage += "\n\nIf you no longer wish to receive notifications, you can "
    + "unsubscribe and your details will be removed from our system:\n"
    + "http://example.com/apps/vendorreg/unsubscribe.aspx?unsub=" + hash + "\n\n"
    + "Example Website Policies:\n"
    + "http://example.com/doc/help/policies/help_website_policies";

// Important: Mime standard dictates that text version must come first 
using (AlternateView textPart = 
    AlternateView.CreateAlternateViewFromString(textMessage, null, "text/plain"))
{
    textPart.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
    mailMessage.AlternateViews.Add(textPart);
    mailMessage.IsBodyHtml = false;
    mailMessage.Body = textMessage;
}

htmlMessage += Environment.NewLine + Environment.NewLine
    + "If you no longer wish to receive notifications, you can "
    + "unsubscribe and your details will be removed from our system:"
    + Environment.NewLine 
    + "http://example.com/apps/vendorreg/unsubscribe.aspx?unsub=" + hash
    + Environment.NewLine + Environment.NewLine
    + "Example.com Website Policies:" 
    + Environment.NewLine
    + "http://example.com/doc/help/policies/help_website_policies";

using (AlternateView htmlPart = 
    AlternateView.CreateAlternateViewFromString(htmlMessage,
    System.Text.Encoding.UTF8, "text/html"))
{
    htmlPart.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
    mailMessage.AlternateViews.Add(htmlPart);
    mailMessage.IsBodyHtml = true;
    mailMessage.Body = htmlMessage;
}

// Send email