将内嵌和页脚添加到电子邮件中,作为内联C#

时间:2015-10-03 15:31:04

标签: c# html email mailmessage

我的网站有两个图片页眉和页脚。

我正在向客户发送电子邮件。

我想将我网站的页眉和页脚添加到电子邮件中作为内联。

在页眉和页脚之间,我想添加一些信息。

如何将解决方案资源管理器中的图像添加为电子邮件正文中的内嵌。

 var mailMessage = new MailMessage(from, userName, subject, emailBody) { IsBodyHtml = true };

            var emailClient = new SmtpClient
            {
                EnableSsl = useSsl.ToLower().Contains("true"),
                Credentials = new NetworkCredential(emailLoginUser, emailLoginPassword),
                Host = smtpServerUrl,
                Port = int.Parse(smtpServerPort)
            };
            emailClient.Send(mailMessage);

1 个答案:

答案 0 :(得分:0)

您可以使用MailMessageAlternateView中嵌入资源。代码是可以理解的。我假设fromuserName是字符串,创建了MailAddress的实例:

public static void SendMail(string from, string userName, string subject, string emailBody)
{
    string htmlBody = string.Format("<html><body><img src=\"cid:Header\" /><br />{0}<br /><img src=\"cid:Footer\" /></body></html>", emailBody);
    AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, Encoding.Default, MediaTypeNames.Text.Html);

    // Create a LinkedResource object for each embedded image
    LinkedResource header = new LinkedResource("Header.jpg", MediaTypeNames.Image.Jpeg);
    header.ContentId = "Header";

    LinkedResource footer = new LinkedResource("Footer.jpg", MediaTypeNames.Image.Jpeg);
    header.ContentId = "Footer";

    avHtml.LinkedResources.Add(header);
    avHtml.LinkedResources.Add(footer);


    // Add the alternate views instead of using MailMessage.Body
    var mailMessage = new MailMessage();
    mailMessage.From = new MailAddress(from);
    mailMessage.To.Add(new MailAddress(userName));
    mailMessage.Subject = subject;
    mailMessage.AlternateViews.Add(avHtml);

    // Address and send the message
    var emailClient = new SmtpClient
    {
        EnableSsl = useSsl.ToLower().Contains("true"),
        Credentials = new NetworkCredential(emailLoginUser, emailLoginPassword),
        Host = smtpServerUrl,
        Port = int.Parse(smtpServerPort)
    };
    emailClient.Send(mailMessage);
}