将富文本发送到电子邮件

Sending rich text to email

我在将文本作为 html 标记发送到邮件时遇到问题。首先,我将 rtf 转换为 html

string GetHtmlContent(string someRTFtext)
{
    RichEditDocumentServer server = new RichEditDocumentServer();
    server.RtfText = someRTFtext;
    server.Options.Export.Html.CssPropertiesExportType = DevExpress.XtraRichEdit.Export.Html.CssPropertiesExportType.Inline;
    server.Options.Export.Html.DefaultCharacterPropertiesExportToCss = true;
    server.Options.Export.Html.EmbedImages = true;
    server.Options.Export.Html.ExportRootTag = DevExpress.XtraRichEdit.Export.Html.ExportRootTag.Body;

    return server.HtmlText;
}

这个方法return我

<body>
<style type="text/css">
    .cs2E86D3A6{text-align:center;text-indent:0pt;margin:0pt 0pt 0pt 0pt}
    .cs88F66593{color:#800080;background-color:transparent;font-family:Arial;font-size:8pt;font-weight:bold;font-style:normal;}
</style>
<p class="cs2E86D3A6"><span class="cs88F66593">Форматированый текст</span></p></body>

但是 post 是简单的文本,没有任何选择、字体等。 下面是发送方法

try
{
    string login = ConfigurationManager.AppSettings["EmailLogin"];
    string password = ConfigurationManager.AppSettings["EmailPassword"];

    MailMessage mail = new MailMessage();
    mail.From = new MailAddress(login);

    if (lbStudents.Items.Count == 0)
        MessageBox.Show("Error.", "Sending massage", MessageBoxButtons.OK, MessageBoxIcon.Information);

    foreach (SmallStudent student in lbStudents.Items)
    {
        mail.To.Add(new MailAddress(student.Email));
    }

    if (txtSubject.Text.Trim() == String.Empty)
    {
        MessageBox.Show("Error.", "Sending massage",
        MessageBoxButtons.OK, MessageBoxIcon.Information);
        return;
    }

    mail.Subject = txtSubject.Text.Trim();
    mail.Body = GetHtmlContent(rtfEditor.DocumentRtf);
    mail.IsBodyHtml = true;
    mail.BodyEncoding = Encoding.UTF8;

    SmtpClient client = new SmtpClient();
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.EnableSsl = true;
    client.Credentials = new NetworkCredential(login.Split('@')[0], password);
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.Send(mail);
    mail.Dispose();
}
catch (Exception exception)
{
    MessageBox.Show("Exception: " + exception.Message, 
                    "Sending massage", 
                    MessageBoxButtons.OK, 
                    MessageBoxIcon.Information);
}

一些电子邮件客户端,包括 Gmail 网络邮件,不支持 <style> 元素;参见 CSS Support Guide for Email Clients

通过 style="..." 属性内联样式,您将获得更好的兼容性:

<body>
<p style="text-align:center;text-indent:0pt;margin:0pt 0pt 0pt 0pt">
    <span style="color:#800080;background-color:transparent;font-family:Arial;font-size:8pt;font-weight:bold;font-style:normal;">Форматированый текст</span>
</p>
</body>

这可能会导致大量重复,因此如果您有很多样式化元素,请考虑使用自动化过程来内联样式。