首页 > 解决方案 > 从 memoryStream 发送带有附件的 MailKit 电子邮件

问题描述

如何使用 MailKit 从 memoryStream 发送带有附件的电子邮件?目前,我正在使用常规 SMTP 发送并使用以下代码附加文件,但找不到任何合适的示例来使用 MailKit 包发送它。我已经浏览了这两个文档,但找不到合适的解决方案。 http://www.mimekit.net/docs/html/M_MimeKit_AttachmentCollection_Add_6.htm

using System.Net.Mail;
MemoryStream memoryStream = new MemoryStream(bytes);
                    message.Attachments.Add(new Attachment(memoryStream, "Receipt.pdf", MediaTypeNames.Application.Pdf));

这是我的 MailKit 电子邮件代码:

#region MailKit
                string fromEmail = GlobalVariable.FromEmail;
                string fromEmailPwd = "";//add sender password
                var email = new MimeKit.MimeMessage();
                email.From.Add(new MimeKit.MailboxAddress("Sender", fromEmail));

                email.To.Add(new MimeKit.MailboxAddress("receiver", "receiver@gmail.com"));
                var emailBody = new MimeKit.BodyBuilder
                {
                    HtmlBody = htmlString
                };
                email.Subject = "test Booking";
                email.Body = emailBody.ToMessageBody();
                //bytes is parameter.
                //MemoryStream memoryStream = new MemoryStream(bytes);
                //message.Attachments.Add(new Attachment(memoryStream, "Receipt.pdf", MediaTypeNames.Application.Pdf));

                using (var smtp = new MailKit.Net.Smtp.SmtpClient())
                {
                    smtp.Connect("smtp.gmail.com", 465, true);
                    smtp.Authenticate(fromEmail, fromEmailPwd);
                    smtp.Send(email);
                    smtp.Disconnect(true);
                }
                #endregion

标签: c#asp.netasp.net-mvcasp.net-coremailkit

解决方案


如果您想坚持使用 MimeKit 的 BodyBuilder 来构建您的消息正文,您可以执行以下操作:

var emailBody = new MimeKit.BodyBuilder
{
    HtmlBody = htmlString
};
emailBody.Attachments.Add ("Receipt.pdf", bytes);

// If you find that MimeKit does not properly auto-detect the mime-type based on the
// filename, you can specify a mime-type like this:
//emailBody.Attachments.Add ("Receipt.pdf", bytes, ContentType.Parse (MediaTypeNames.Application.Pdf));

message.Body = emailBody.ToMessageBody ();

推荐阅读