首页 > 解决方案 > 如何使用 MailKit 发送嵌入的图像?

问题描述

我按照本指南尝试在电子邮件中嵌入 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,我导航到父文件夹,因为文件位于父文件夹上,并且在变量上存在的路径内,抱歉代码可能看起来是法语,我不是法语,但我工作的地方是一家法国国际公司,如果您想了解更多信息,请随时问我,谢谢

标签: c#consolemailkit

解决方案


问题是您错误地设置了消息正文。

替换以下行:

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 上运行),它将有助于使您的代码可移植到非 Windows 平台或 Mac)。


推荐阅读