C# - 使用内联附件发送电子邮件没有Outlook的回形针图标?

时间:2015-12-15 18:56:18

标签: c# email outlook inline

我有一个系统可以发送包含内嵌图片的电子邮件。问题是Outlook 2013如何显示附件。我是否可以通过告诉outlook 来显示此处显示的回形针图标来更新我的代码?

Outlook 2013 preview pane

我的想法是,我只想在附上完整尺寸的图片时显示此图标。不是内联附件。

以下是生成电子邮件的代码。创建一个基本的控制台应用程序,指定To / mailserver / picture路径,然后运行。

static void Main(string[] args)
{
    Console.WriteLine("Prepping email message....");

    var subject = "Test Subject With Inline";
    var message = "<p>This is a test message.</p><br/><br/><p>[CompanyLogo]</p>";
    var to = new List<string>();

    to.Add("My.Name@company.com");

    Console.WriteLine("Sending email message....");

    if (SendMessageToFrom(subject, message, to, new List<string>()))
    {
        Console.WriteLine("Email sent! Check your inbox.");
    }
    else
    {
        Console.WriteLine("Error sending email!");
    }
}

public static bool SendMessageToFrom(String subject, String message, List<String> to, List<String> cc)
{
    try
    {
        // Construct the email
        var sendMessage = new MailMessage()
        {
            IsBodyHtml = true,
            From = new MailAddress("noreply@company.com"),
            Subject = subject,
            Body = message
        };

        if (sendMessage.Body.Contains("[CompanyLogo]"))
        {
            sendMessage.AlternateViews.Add(EmbedLogo(sendMessage.Body));
        }

        // Add the list of recipients
        foreach (var recipient in to)
        {
            sendMessage.To.Add(recipient);
        }
        foreach (var recipient in cc)
        {
            sendMessage.CC.Add(recipient);
        }

        //Specify the SMTP server
        var smtpServerName = "mailserver.company.com";

        var mailClient = new SmtpClient(smtpServerName);

        mailClient.Send(sendMessage);

        return true;
    }
    catch
    {
        throw;
    }
}

private static AlternateView EmbedLogo(string html)
{
    var inline = new LinkedResource("img\\company-logo.jpg");
    inline.ContentId = Guid.NewGuid().ToString();
    html = html.Replace("[CompanyLogo]", string.Format(@"<img src='cid:{0}'/>", inline.ContentId));
    var result = AlternateView.CreateAlternateViewFromString(html, null, System.Net.Mime.MediaTypeNames.Text.Html);
    result.LinkedResources.Add(inline);
    return result;
}

更新:这是执行诀窍的代码:

private static MailMessage EmbedLogo(MailMessage mail)
{
    var inline = new Attachment("img\\company-logo.jpg");
    inline.ContentId = Guid.NewGuid().ToString();
    inline.ContentDisposition.Inline = true;
    inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
    mail.Body = mail.Body.Replace("[CompanyLogo]", string.Format(@"<img src='cid:{0}'/>", inline.ContentId));
    mail.Attachments.Add(inline);
    return mail;
}

我还更新了主要方法:

if (sendMessage.Body.Contains("[CompanyLogo]"))
{
    sendMessage = EmbedLogo(sendMessage);
}

1 个答案:

答案 0 :(得分:3)

确保您的附件具有Content-ID MIME标头,并且消息的HTML正文使用cid属性引用它们:<img src="cid:xyz">(其中xyz是Content-ID MIME标头的值)。