daw*_*ode 4 c# asp.net asp.net-mvc mailkit asp.net-core
如何使用 MailKit 从内存流发送带有附件的电子邮件?目前,我正在使用常规 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));
Run Code Online (Sandbox Code Playgroud)
这是我的 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
Run Code Online (Sandbox Code Playgroud)
如果您想坚持使用 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 ();
Run Code Online (Sandbox Code Playgroud)
它是这样完成的:您需要TextPart为字符串内容创建 a ,MimePart为附件创建 a ,并将两者添加到 a中Multipart,这是BodyMimeMessage
我假设您想要发送一个 HTML 字符串textContent和一个名称为 的 PDF 文件filename,该文件已使用任何名为 的流读取stream。
var multipart = new Multipart("mixed");
var textPart = new TextPart(TextFormat.Html)
{
Text = textContent,
ContentTransferEncoding = ContentEncoding.Base64,
};
multipart.Add(textPart);
stream.Position = 0; // you MUST reset stream position
var attachmentPart = new MimePart(MediaTypeNames.Application.Pdf)
{
Content = new MimeContent(stream),
ContentId = filename,
ContentTransferEncoding = ContentEncoding.Base64,
FileName = filename
};
multipart.Add(attachmentPart);
mimeMessage.Body = multipart;
Run Code Online (Sandbox Code Playgroud)
请注意,对于contentType我使用的MediaTypeNames.Application.PdfDLLSystem.Net.Mail和命名空间System.Net.Mime,它等于字符串"application/pdf"。您可以使用您喜欢的任何其他库,或者编写自己的库。
| 归档时间: |
|
| 查看次数: |
12426 次 |
| 最近记录: |