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

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

问题描述

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



如果我只发送HTML什么是危险?



我正在从



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

  try 
{
//指定发件人,收件人并受新邮件
MailAddress sender =
new MailAddress(sender@johnnycoder.com,Sender);

MailAddress recipient =
new MailAddress(recipient@johnnycoder.com,收件人);

MailMessage m =新的MailMessage(发件人,收件人);
m.Subject =测试消息;

//定义纯文本替代视图并添加到消息
string plainTextBody =
您必须使用支持HTML消息的电子邮件客户端;

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

m.AlternateViews.Add(plainTextView);

//定义具有嵌入图像的html替代视图,
//添加到消息。要从HTML消息正文引用附加的链接
//资源的图像,请在< img>中使用cid:contentID
//标签...
string htmlBody =
< html>< body>< h1>图片< / h1>< br> +
< img src = \cid:SampleImage\>< / body>< / html>;

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

// ...然后定义与图像标签中找到的
// ContentID属性匹配的实际LinkedResource。在这种情况下,
// HTML消息包含标签
//< img src = \cid:SampleImage\>和以下
// LinkedResource.ContentId设置为SampleImage
LinkedResource sampleImage =
new LinkedResource(sample.jpg,
MediaTypeNames.Image.Jpeg);
sampleImage.ContentId =SampleImage;

htmlView.LinkedResources.Add(sampleImage);

m.AlternateViews.Add(htmlView);

//最后,配置smtp或者使用
// system.net mailSettings
SmtpClient smtp = new SmtpClient
{
Host =smtp
UseDefaultCredentials = false,
Credentials =
new NetworkCredential(username,password)
};

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

smtp.Send(m);
}
catch(ArgumentException)
{
throw new
ArgumentException(未定义的发件人和/或收件人);
}
catch(FormatException)
{
throw new
FormatException(Invalid sender and / or recipient);
}
catch(InvalidOperationException)
{
throw new
InvalidOperationException(Undefined SMTP server。);
}
catch(SmtpFailedRecipientException)
{
throw new SmtpFailedRecipientException(
邮件服务器说收件人没有邮箱);
}
catch(SmtpException ex)
{
//无效的主机名导致一个WebException InnerException,
//提供了一个更具描述性的错误,所以得到基本异常
异常inner = ex.GetBaseException();
抛出新的SmtpException(无法发送消息:+ inner.Message);
}


解决方案

我会说,今天的世界,最佳实践方法将是确保您以 纯文本和HTML(如果您真的要发送HTML电子邮件)发送您的消息。



呵呵,请确保您在纯文本视图中实际发送内容,而不是单个句子说您必须使用支持HTML消息的电子邮件客户端。 Google Mail采用这种方式,似乎工作完美,允许在完整的PC客户端上丰富的观点,同时还允许在更受限制的设备(即移动/手机)上最小化的观点。



如果您想要纯粹主义者的观点,您根本不会发送HTML电子邮件,也不会将二进制文件附加到电子邮件中。原始电子邮件标准的两个损坏,原本只有原始,用于纯文本。
(有些人对此此处 here



然而,在务实的现代现实世界中HTML电子邮件是非常真实的,非常可以接受。发送HTML电子邮件的主要缺点是收件人是否按照您希望他们看到的方式看到电子邮件。这是网页设计师多年来一直在争论的问题;让他们的网站在所有可能的浏览器中看起来都正确(尽管今天比以前更容易)许多年前。



类似于确保网站正常运行不需要 Javascript,通过将电子邮件作为HTML和纯文本发送,您将确保您的电子邮件正常降级,以便人们阅读电子邮件(例如)小移动设备(这些日子越来越普及,可能或可能无法呈现完整的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天全站免登陆