如何使用 MailKit 发送嵌入的图像?

how to send embedded images with MailKit?

我按照 this guide 尝试在电子邮件中嵌入 2 张图片 这是我用 C# 为控制台应用程序编写的代码: ExecuteSendMailEx 过程:

 public void ExecuteSendMailEx(AccesBase accesBase, string From, string Subjet, bool Format, string EmailLogoHeader, string EmailLogoFooter, string ReplyTo, string ReturnPath, string BodyHtml, string BodyText, string Destinataire, string IdLangage, string CopieCachee, string PJ, string SMTP, string SMTPPORT, string SMTPLOGIN, string SMTPPWD, ref int RTN)
        {
            try
            {
                Log.Information("ENVOI_Constructor ExecuteSendMailEx has begun");
                var email = new MimeMessage();
                email.From.Add(MailboxAddress.Parse(From));
                email.To.Add(MailboxAddress.Parse(Destinataire));
                email.ReplyTo.Add(MailboxAddress.Parse(ReplyTo));
                if (!string.IsNullOrEmpty(CopieCachee))
                    email.Bcc.Add(MailboxAddress.Parse(CopieCachee));
                email.Subject = Subjet;
                email.Sender = (MailboxAddress.Parse(SMTPLOGIN));

                

                var currentDirectory = Directory.GetCurrentDirectory();
                var parentDirectory = Directory.GetParent(currentDirectory).FullName;
                var filesDirectory = parentDirectory + "\Files";

                var builder = new BodyBuilder();
                if (EmailLogoHeader != "" && EmailLogoFooter != "")
                {
                    var imageHead = builder.LinkedResources.Add(filesDirectory + "\" + EmailLogoHeader);
                    imageHead.ContentId = MimeUtils.GenerateMessageId();
                    var imageFoot = builder.LinkedResources.Add(filesDirectory + "\" + EmailLogoFooter);

                    imageFoot.ContentId = MimeUtils.GenerateMessageId();
                    builder.HtmlBody = string.Format(@"<img src='cid:{0}'><br>{1}<br><img src='cid:{2} '>", imageHead.ContentId, BodyHtml, imageFoot.ContentId);
                }
                else if (EmailLogoFooter != "" && EmailLogoHeader == "")
                {
                    var imageFoot = builder.LinkedResources.Add(filesDirectory + "\" + EmailLogoFooter);

                    imageFoot.ContentId = MimeUtils.GenerateMessageId();
                    builder.HtmlBody = string.Format(@"{0}<br><img src='cid={1}'>", BodyHtml, imageFoot.ContentId);
                }
                else if (EmailLogoHeader != "" && EmailLogoFooter == "")
                {
                    var imageHead = builder.LinkedResources.Add(filesDirectory+"\" + EmailLogoHeader);
                    imageHead.ContentId = MimeUtils.GenerateMessageId();
                    builder.HtmlBody = string.Format(@"<img src='cid:{0}'><br>{1}", imageHead.ContentId, BodyHtml);
                }
                else
                    builder.HtmlBody = BodyHtml;

        
                builder.TextBody = BodyText ;
               
                if (Format == false)
                {
                    builder.Attachments.Add(addImage(filesDirectory + EmailLogoHeader));
                    builder.Attachments.Add(addImage(filesDirectory + EmailLogoFooter));
                }
                email.Body = Format == false ? new TextPart(TextFormat.Text) { Text = builder.TextBody } : new TextPart(TextFormat.Html){ Text= builder.HtmlBody };

                // send email
                var smtp = new MailKit.Net.Smtp.SmtpClient();
                smtp.Connect(SMTP, Int32.Parse(SMTPPORT), SecureSocketOptions.StartTls);
                smtp.Authenticate(SMTPLOGIN, SMTPPWD);
                smtp.Send(email);
                smtp.Disconnect(true);

                
            }
            catch (Exception ex) { Log.Error(ex.Message + " : " + ex.InnerException + " - ENVOI_Constructor: ExecuteSendMailEx Method"); }

           
        }

显然,我的第一行代码是:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Web;
using TP;
using System.Net;
using System.Net.Mail;
using MimeKit;
using MimeKit.Text;
using MailKit.Net.Smtp;
using MailKit.Security;
using Serilog;
using System.Drawing;
using System.IO;
using MimeKit.Utils;

预期行为:我尝试了所有方法将图像嵌入到使用 MailKit 发送的电子邮件中,但它们总是显示为 所有变量都包含正确的值,例如承载 Exchange 服务器地址的 SMTP 或包含端口的 SMTPPORT,每个变量都按照其含义命名, EmailHeaderLogo 和 EmailFooterLogo 包含类似 Mail\image.jpg 的路径, 我导航到父文件夹,因为文件位于父文件夹中,并且位于变量中存在的路径中, 抱歉,代码可能看起来像法语,我不是法国人,但我工作的地方是一家法国国际公司, 如果您需要任何其他信息,请随时问我, 谢谢

问题是您设置的邮件正文不正确。

替换以下行:

email.Body = Format == false ? new TextPart(TextFormat.Text) { Text = builder.TextBody } : new TextPart(TextFormat.Html){ Text= builder.HtmlBody };

有了这个:

email.Body = builder.ToMessageBody();

我不明白 Format 应该做什么,但看起来如果 Formatfalse,那么您只需要纯文本?

如果是这样,您需要将代码更改为以下内容:

public void ExecuteSendMailEx(AccesBase accesBase, string From, string Subjet, bool Format, string EmailLogoHeader, string EmailLogoFooter, string ReplyTo, string ReturnPath, string BodyHtml, string BodyText, string Destinataire, string IdLangage, string CopieCachee, string PJ, string SMTP, string SMTPPORT, string SMTPLOGIN, string SMTPPWD, ref int RTN)
{
    try
    {
        Log.Information("ENVOI_Constructor ExecuteSendMailEx has begun");
        var email = new MimeMessage();
        email.From.Add(MailboxAddress.Parse(From));
        email.To.Add(MailboxAddress.Parse(Destinataire));
        email.ReplyTo.Add(MailboxAddress.Parse(ReplyTo));
        if (!string.IsNullOrEmpty(CopieCachee))
            email.Bcc.Add(MailboxAddress.Parse(CopieCachee));
        email.Subject = Subjet;
        email.Sender = (MailboxAddress.Parse(SMTPLOGIN));

        var currentDirectory = Directory.GetCurrentDirectory();
        var parentDirectory = Directory.GetParent(currentDirectory).FullName;
        var filesDirectory = Path.Combine(parentDirectory, "Files");

        var builder = new BodyBuilder();
        if (Format)
        {
            // If we have any headers or footers, inject those into the HTML body
            if (!string.IsNullOrEmpty(EmailLogoHeader) && !string.IsNullOrEmpty(EmailLogoFooter))
            {
                var imageHead = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoHeader));
                imageHead.ContentId = MimeUtils.GenerateMessageId();
                var imageFoot = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoFooter));

                imageFoot.ContentId = MimeUtils.GenerateMessageId();
                builder.HtmlBody = string.Format(@"<img src='cid:{0}'><br>{1}<br><img src='cid:{2} '>", imageHead.ContentId, BodyHtml, imageFoot.ContentId);
            }
            else if (!string.IsNullOrEmpty(EmailLogoFooter))
            {
                var imageFoot = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoFooter));

                imageFoot.ContentId = MimeUtils.GenerateMessageId();
                builder.HtmlBody = string.Format(@"{0}<br><img src='cid={1}'>", BodyHtml, imageFoot.ContentId);
            }
            else if (!string.IsNullOrEmpty(EmailLogoHeader))
            {
                var imageHead = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoHeader));
                imageHead.ContentId = MimeUtils.GenerateMessageId();
                builder.HtmlBody = string.Format(@"<img src='cid:{0}'><br>{1}", imageHead.ContentId, BodyHtml);
            }
            else
            {
                builder.HtmlBody = BodyHtml;
            }
        }
        else
        {
            // No HTML body is desired, so just add the header and footer images as attachments instead.
            if (!string.IsNullOrEmpty(EmailLogoHeader))
                builder.Attachments.Add(Path.Combine(filesDirectory, EmailLogoHeader));

            if (!string.IsNullOrEmpty(EmailLogoFooter))
                builder.Attachments.Add(Path.Combine(filesDirectory, EmailLogoFooter));
        }

        builder.TextBody = BodyText;

        email.Body = builder.ToMessageBody();

        // send email
        using (var smtp = new MailKit.Net.Smtp.SmtpClient())
        {
            smtp.Connect(SMTP, Int32.Parse(SMTPPORT), SecureSocketOptions.StartTls);
            smtp.Authenticate(SMTPLOGIN, SMTPPWD);
            smtp.Send(email);
            smtp.Disconnect(true);
        }
    }
    catch (Exception ex)
    {
        Log.Error(ex.Message + " : " + ex.InnerException + " - ENVOI_Constructor: ExecuteSendMailEx Method");
    }
}

注意:我冒昧地将您的代码更改为使用 string.IsNullOrEmpty() 而不是与“”进行直接比较,并修复了您的代码以使用 Path.Combine()。你真的应该养成使用 Path.Combine() 的习惯,尤其是,如果你想 运行 你的代码在 . NET Core(它可能 运行 在 Linux 或 Mac 上)。