我可以使用MailKit通过电子邮件发送文件吗?

问题描述 投票:21回答:1

作为标题,MailKit是否支持发送文件? 如果是,我该怎么办?

c# email-attachments mailkit mimekit
1个回答
49
投票

是。这在文档以及FAQ中有解释。

来自FAQ:

How do I create a message with attachments?

要构建带附件的消息,首先需要创建一个multipart/mixed容器,然后您需要先将消息体添加到容器中。添加完正文后,您可以添加包含您要附加​​的文件内容的MIME部分,并确保将Content-Disposition标头值设置为附件。您可能还想在filename标头上设置Content-Disposition参数以及在name标头上设置Content-Type参数。最方便的方法是简单地使用MimePart.FileName属性,它将为您设置两个参数,并将Content-Disposition标头值设置为attachment(如果尚未设置为其他值)。

var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "[email protected]"));
message.To.Add (new MailboxAddress ("Alice", "[email protected]"));
message.Subject = "How you doin?";

// create our message text, just like before (except don't set it as the message.Body)
var body = new TextPart ("plain") {
    Text = @"Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.

Will you be my +1?

-- Joey
"
};

// create an image attachment for the file located at path
var attachment = new MimePart ("image", "gif") {
    Content = new MimeContent (File.OpenRead (path)),
    ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
    ContentTransferEncoding = ContentEncoding.Base64,
    FileName = Path.GetFileName (path)
};

// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new Multipart ("mixed");
multipart.Add (body);
multipart.Add (attachment);

// now set the multipart/mixed as the message body
message.Body = multipart;

使用附件构造消息的一种更简单的方法是利用BodyBuilder类。

var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "[email protected]"));
message.To.Add (new MailboxAddress ("Alice", "[email protected]"));
message.Subject = "How you doin?";

var builder = new BodyBuilder ();

// Set the plain-text version of the message text
builder.TextBody = @"Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.

Will you be my +1?

-- Joey
";

// We may also want to attach a calendar event for Monica's party...
builder.Attachments.Add (@"C:\Users\Joey\Documents\party.ics");

// Now we just need to set the message body and we're done
message.Body = builder.ToMessageBody ();

有关更多信息,请参阅Creating Messages

© www.soinside.com 2019 - 2024. All rights reserved.