假设,我们有一个电子邮件收件箱子文件夹,文件夹中的每封电子邮件都有数百封带有许多图像附件的电子邮件。我们希望在本地下载所有附件。
我们该怎么做?
我们将使用MailKit包。将此nuget添加到您的项目依赖项中。
所以,让我们连接一下:
using CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
const int imapPortNumber = 993;
client.Connect(configuration.ImapServerAddress, imapPortNumber, true, cancellationTokenSource.Token);
并验证:
client.Authenticate(configuration.FullEmailAddress, configuration.ApplicationPassword, cancellationTokenSource.Token);
有些服务器需要单独的应用程序密码以提高安全性,请在此处提供。否则,请提供您的电子邮件帐户的密码。
现在获取并打开收件箱子文件夹(对于本例,其名称存储在configuration.InboxSubfolderName
中(
// getting inbox folder
IMailFolder inboxFolder = client.Inbox;
// getting subfolder for Inbox
IMailFolder inboxSubfolderWithPictures = inboxFolder.GetSubfolder(configuration.InboxSubfolderName);
inboxSubfolderWithPictures.Open(FolderAccess.ReadOnly, cancellationTokenSource.Token);
让我们处理文件夹中的每一条消息:
for (int i = 0; i < inboxSubfolderWithPictures.Count; i++)
{
using MimeMessage message = inboxSubfolderWithPictures.GetMessage(i, cancellationTokenSource.Token);
string messageFolderName = ... // build message folder name as you want
string messageFolderPath = Path.Combine(configuration.DownloadDestinationFolder, messageFolderName);
// creating directory for a message to store its attachments
Directory.CreateDirectory(messageFolderPath);
foreach (MimeEntity? emailAttachment in message.Attachments)
{
if (emailAttachment.IsAttachment)
{
using MimePart fileAttachment = (MimePart)emailAttachment;
string fileName = fileAttachment.FileName;
string fullPathToFile = Path.Combine(messageFolderPath, fileName);
using FileStream fileStream = File.Create(fullPathToFile);
fileAttachment.Content.DecodeTo(fileStream);
}
}
}
不要忘记断开与服务器的连接:
client.Disconnect(true, cancellationTokenSource.Token);