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

Correct Syntax for Generating HTML Email using AlternateView(使用 AlternateView 生成 HTML 电子邮件的正确语法)
本文介绍了使用 AlternateView 生成 HTML 电子邮件的正确语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use the AlternateView to cater for both HTML and Text clients. I would prefer to use HTML and only fall back to text where necessary. I started re-coding an old console app to do this but I still have carriage returns and newlines as "/r/n" in my code and my problem is trying to figure out how and where to use Environment.Newline instead of these?

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

Right now, the console application is being called from a Web form. I'm experiencing some difficulties debugging and the eventual plan is to create a WCF service for this.

我认为我遇到的困难是确定 AlternateView 实际为我做了什么,而不是我必须在文本和 HTML 版本中分别明确编码多少电子邮件正文.具体来说,我在以下代码的最后一个 else 块中仍然有旧的回车符和换行符,我正在尝试找出一种更优雅的方法来做到这一点.

I think the difficulty I'm having is determining what AlternateView actually does for me as opposed to how much of the email body I have to explicitly code separately, in text and HTML versions. Specifically, I still have old carriage returns and newlines in the final else block of the following code and I'm trying to figure out a more elegant way of doing this.

    // 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 += 
                           "

If you no longer wish to receive notifications, you can "
                               + "unsubscribe and your details will be removed from our system:
" 
                               + "http://example.com/apps/vendorreg/unsubscribe.aspx?unsub=" 
                               + hash + "

";

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

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

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

推荐答案

UPDATE - 09-30-2019:Microsoft 更新了文档为此.

UPDATE - 09-30-2019: Microsoft updated the documentation for this.

正如我所料,我必须明确提供消息正文的纯文本和 HTML 版本.MSDN 文档不是很有帮助.这是我为使其工作而创建的代码片段:

As I guessed, I had to explicitly provide a plain text and HTML version of the message body. The MSDN documentation was not very helpful. Here's a snippet of the code I created to get this working:

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

textMessage += "

If you no longer wish to receive notifications, you can "
    + "unsubscribe and your details will be removed from our system:
"
    + "http://example.com/apps/vendorreg/unsubscribe.aspx?unsub=" + hash + "

"
    + "Example Website Policies:
"
    + "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

这篇关于使用 AlternateView 生成 HTML 电子邮件的正确语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
How to use REG_OPTION_OPEN_LINK in C# Registry class(如何在C#注册表类中使用REG_OPTION_OPEN_LINK)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)