C#发送HTML和文本电子邮件 - 最优雅? [英] C# Send both HTML and Text email - most elegant?

查看:874
本文介绍了C#发送HTML和文本电子邮件 - 最优雅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时的最佳做法是同时发送HTML和文本电子邮件?

如果我只发送HTML的危害有哪些?

我想是这样的,从下方

<一个href=\"http://johnny$c$cr.com/blog/2009/04/15/net-mailmessage-linkedresources-alternateviews-and-exceptions/\">http://johnny$c$cr.com/blog/2009/04/15/net-mailmessage-linkedresources-alternateviews-and-exceptions/

 尝试
{
    //分配发件人,收件人,如有新邮件
    MailAddress发件人=
        新的MailAddress(sender@johnny$c$cr.com,发件人);    MailAddress收件人=
        新的MailAddress(recipient@johnny$c$cr.com,收件人);    MAILMESSAGE M = MAILMESSAGE新(发件人,收件人);
    m.Subject =测试信息;    //定义纯文本不同的观点,并加入到消息
    串plainTextBody =
        你必须使用支持HTML邮件的电子邮件客户端    AlternateView plainTextView =
        AlternateView.CreateAlternateViewFromString(
            plainTextBody,空,MediaTypeNames.Text.Plain);    m.AlternateViews.Add(plainTextView);    //定义嵌入图片的HTML不同的观点和
    //添加到消息。要引用附件图片为链接
    从你的HTML邮件正文//资源,用CID:内容识别
    //在&lt; IMG&GT;标签...
    串htmlBody =
        &LT; HTML和GT;&LT;身体GT;&LT; H1&GT;图片和LT; / H1&GT;&LT; BR&gt;中+
        &LT; IMG SRC = \\CID:SampleImage \\&GT;&LT; /身体GT;&LT; / HTML&gt;中;    AlternateView htmlView =
        AlternateView.CreateAlternateViewFromString(
            htmlBody,空,MediaTypeNames.Text.Html);    // ...然后定义实际LinkedResource匹配
    //为图像标记发现内容识别属性。在这种情况下,
    // HTML邮件包括标签
    //&LT; IMG SRC = \\CID:SampleImage \\&GT;和下面的
    // LinkedResource.ContentId设为SampleImage
    LinkedResource sampleImage =
        新LinkedResource(sample.jpg
            MediaTypeNames.Image.Jpeg);
    sampleImage.ContentId =SampleImage;    htmlView.LinkedResources.Add(sampleImage);    m.AlternateViews.Add(htmlView);    //最后,配置SMTP或交替使用
    // system.net mailSettings
    SmtpClient SMTP =新SmtpClient
          {
              主机=smtp.example.com
              UseDefaultCredentials =假,
              证书=
                  新的NetworkCredential(用户名,密码)
          };    //<system.net>
    //&LT; mailSettings&GT;
    //&LT; SMTP deliveryMethod =网络&GT;
    //&lt;网络主机=smtp.example.com
    //端口=25的DefaultCredentials =真/&GT;
    //&LT; / SMTP&GT;
    //&LT; / mailSettings&GT;
    //</system.net>    smtp.Send(米);
}
赶上(ArgumentException的)
{
    抛出新
        ArgumentException的(未定义发件人和/或收件人。);
}
赶上(FormatException)
{
    抛出新
        FormatException(无效的发件人和/或收件人。);
}
赶上(InvalidOperationException异常)
{
    抛出新
        InvalidOperationException异常(未定义SMTP服务器。);
}
赶上(SmtpFailedRecipientException)
{
    抛出新SmtpFailedRecipientException(
        邮件服务器说有收件人没有邮箱);
}
赶上(SmtpException前)
{
    //主机名无效导致引发WebException的InnerException是
    //提供了一个更具描述性的错误,所以得到的基异常
    例外内= ex.GetBaseException();
    抛出新SmtpException(无法发送消息:+ inner.Message);
}


解决方案

我要说的是,在当今世界,最佳实践的做法是,以确保您发送邮件作为两个纯文本和HTML(如果你真的想发送HTML电子邮件)。

呵呵,并确保你实际上是在纯文本视图发送的内容的,而不是单一的一句话说:你必须使用支持HTML邮件的电子邮件客户端。谷歌邮件采用这种方法,它似乎很好地工作,允许在完全成熟的PC客户端富的观点,同时也让更多的受限设备(即移动/手机)最小的观点。

如果你想利用一个纯粹的观点,你就不会被发送所有HTML格式的电子邮件,也不会你曾经二进制文件附加到电子邮件。原始电子邮件标准的两个腐败,这是只有永远的原来的用于纯文本。
(见一些人的这种意见这里和的这里

然而,在务实的现代现实世界中,HTML电子邮件很真实,也很可以接受的。主要缺点发送HTML电子邮件的收件人是否会看到电子邮件中,你打算让他们看到它的方式。这是大致相同的问题,网页设计师已经有多年作战;让他们的网站看恰到好处,在所有可能的浏览器(虽然它今天显著容易很多年前比它)。

要确保网站正常运行的无需类似的Javascript中,通过发送您的电子邮件既是HTML和纯文本,你会确保你的电子邮件的优雅降级等等人们阅读的电子邮件(例如)小型移动设备(东西是越来越prevalent这些天 - 而这可能是也可能不是能够呈现一个完整的HTML邮件),仍然可以读取没有问题,您的电子邮件内容

Is is best practice to send both HTML and Text email?

If I only send HTML what are the dangers?

I'm thinking something like this below from

http://johnnycoder.com/blog/2009/04/15/net-mailmessage-linkedresources-alternateviews-and-exceptions/

try
{
    // Assign a sender, recipient and subject to new mail message
    MailAddress sender =
        new MailAddress("sender@johnnycoder.com", "Sender");

    MailAddress recipient =
        new MailAddress("recipient@johnnycoder.com", "Recipient");

    MailMessage m = new MailMessage(sender, recipient);
    m.Subject = "Test Message";

    // Define the plain text alternate view and add to message
    string plainTextBody =
        "You must use an email client that supports HTML messages";

    AlternateView plainTextView =
        AlternateView.CreateAlternateViewFromString(
            plainTextBody, null, MediaTypeNames.Text.Plain);

    m.AlternateViews.Add(plainTextView);

    // Define the html alternate view with embedded image and
    // add to message. To reference images attached as linked
    // resources from your HTML message body, use "cid:contentID"
    // in the <img> tag...
    string htmlBody =
        "<html><body><h1>Picture</h1><br>" +
        "<img src=\"cid:SampleImage\"></body></html>";

    AlternateView htmlView =
        AlternateView.CreateAlternateViewFromString(
            htmlBody, null, MediaTypeNames.Text.Html);

    // ...and then define the actual LinkedResource matching the
    // ContentID property as found in the image tag. In this case,
    // the HTML message includes the tag
    // <img src=\"cid:SampleImage\"> and the following
    // LinkedResource.ContentId is set to "SampleImage"
    LinkedResource sampleImage =
        new LinkedResource("sample.jpg",
            MediaTypeNames.Image.Jpeg);
    sampleImage.ContentId = "SampleImage";

    htmlView.LinkedResources.Add(sampleImage);

    m.AlternateViews.Add(htmlView);

    // Finally, configure smtp or alternatively use the
    // system.net mailSettings
    SmtpClient smtp = new SmtpClient
          {
              Host = "smtp.example.com",
              UseDefaultCredentials = false,
              Credentials =
                  new NetworkCredential("username", "password")
          };

    //<system.net>
    //    <mailSettings>
    //        <smtp deliveryMethod="Network">
    //            <network host="smtp.example.com"
    //              port="25" defaultCredentials="true"/>
    //        </smtp>
    //    </mailSettings>
    //</system.net>

    smtp.Send(m);
}
catch (ArgumentException)
{
    throw new
        ArgumentException("Undefined sender and/or recipient.");
}
catch (FormatException)
{
    throw new
        FormatException("Invalid sender and/or recipient.");
}
catch (InvalidOperationException)
{
    throw new
        InvalidOperationException("Undefined SMTP server.");
}
catch (SmtpFailedRecipientException)
{
    throw new SmtpFailedRecipientException(
        "The mail server says that there is no mailbox for recipient");
}
catch (SmtpException ex)
{
    // Invalid hostnames result in a WebException InnerException that
    // provides a more descriptive error, so get the base exception
    Exception inner = ex.GetBaseException();
    throw new SmtpException("Could not send message: " + inner.Message);
}

解决方案

I would say that, in today's world, the "best-practice" approach would be to ensure that you send your message as both plain text and HTML (if you really want to send HTML email messages).

Oh, and make sure you do actually send the content in the plain text view, rather than a single sentence saying "You must use an email client that supports HTML messages". Google Mail takes this approach, and it seems to work perfectly, allowing "rich" views on full-fledged PC clients, whilst also allowing "minimal" views on more restricted devices (i.e. Mobile/Cell phones).

If you want to take a purist's view, you wouldn't be sending HTML emails at all, nor would you ever "attach" a binary file to an email. Both corruptions of the original email standard, which was only ever originally intended for plain text. (See some people's opinions of this here and here)

However, in the pragmatic modern-day real world, HTML email is very real, and very acceptable. The primary downside to sending HTML email is whether the recipient will see the email in the way that you intended them to see it. This is much the same problem that web designers have battled with for years; getting their websites to look "just right" in all possible browsers (although it's significantly easier today than it was many years ago).

Similar to ensuring that a website functions correctly without requiring Javascript, by sending your emails as both HTML and Plain Text, you'll ensure that your emails degrade gracefully so that people reading their emails on (for example) small mobile devices (something that's becoming more and more prevalent these days - and which may or may not be capable of rendering a complete HTML email) can still read your email content without issue.

这篇关于C#发送HTML和文本电子邮件 - 最优雅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆