c# - 从 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
解决方案
如果您想坚持使用 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 ();
推荐阅读
- python - 计算python中选项卡的出现次数
- ios - 为什么可访问性将 NSString 属性添加为静态文本?以及如何忽略它?
- elm - 如何在显示的代码片段中显示语法突出显示?
- reactjs - 使用 React 上下文将输入数据从组件 A 传递到组件 B
- amazon-web-services - Aws 实例端口拒绝连接,即使它在安全组中打开
- postgresql - 没有直接关系的 SQL 表
- intellij-idea - 在 IntelliJ 中将单行方法重新格式化为单行文本
- python - 这些列表之间有什么区别?
- regex - 如何使用但忽略 RegEx 中的字符
- ios - Xcode 11.2 - 在钥匙串中找不到指定的项目