c# - 如何使用 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
,我导航到父文件夹,因为文件位于父文件夹上,并且在变量上存在的路径内,抱歉代码可能看起来是法语,我不是法语,但我工作的地方是一家法国国际公司,如果您想了解更多信息,请随时问我,谢谢
解决方案
问题是您错误地设置了消息正文。
替换以下行:
email.Body = Format == false ? new TextPart(TextFormat.Text) { Text = builder.TextBody } : new TextPart(TextFormat.Html){ Text= builder.HtmlBody };
有了这个:
email.Body = builder.ToMessageBody();
我不明白Format
应该做什么,但看起来如果Format
是false
,那么你只想要纯文本吗?
如果是这样,您需要将代码更改为以下内容:
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)。
推荐阅读
- java - 如何在 Firebase Firestore 中创建唯一输入?
- vbscript - 如何在不创建新进程的情况下从另一个 VBScript 中运行 VBScript?
- perl - 如何管理自己的 SIGINT 和 SIGTERM 信号?
- select - 如何将基值添加到python中的不同组?
- c++ - ld:版本 3 无效(最大 0) - 添加符号时出错:值错误
- java - 创建一个类的实例并将其添加到地图中。爪哇
- flutter - 为什么我不能在初始化状态后刷新构建
- r - 如何在为其他变量分组时按一个变量对R中的数据框进行排序
- sql - 如何根据特定列项目名称汇总列
- python - 如何像 c++ 中的 cpp/h 一样在 Cython 中导入 pyx/pxd?