C#中的IMAP - 下载邮件和附件

3

我曾尝试过使用名为“Koolwired.Imap”的开源项目在C#上执行此操作。

在下载邮件时,效果还不错,但对于附件,它仅列出了附件的文件名。是否有人尝试过这个?

如果没有,是否有其他更好的免费库可以做到同样的事情(我需要一个免费/开源的解决方案,因为我正在为校园项目做这个)

ImapConnect connection = new ImapConnect("imap.gmail.com", 993, true);
ImapCommand command = new ImapCommand(connection);
ImapAuthenticate auth = new ImapAuthenticate(connection, "<username>@gmail.com", "<password>");
connection.Open();
auth.Login();

string htmlbody = "";
ImapMailbox mailbox = command.Select("INBOX");
mailbox = command.Fetch(mailbox);
int mailCount = mailbox.Messages.Count;

for (int i = 0; i < mailCount ; i++)
{
 ImapMailboxMessage msg = mailbox.Messages[mailCount - 1];
 msg = command.FetchBodyStructure(msg);

 msg.BodyParts[0].ContentEncoding = BodyPartEncoding.NONE;
 msg = command.FetchBodyPart(msg, msg.HTML);

 foreach (ImapMessageBodyPart a in msg.BodyParts)
 {
     if (a.Data != null)
     {
         string fileName = "";

         if (a.Attachment) fileName = ParseFileName(a.Disposition);
             string mimeType = a.ContentType.MediaType.ToLower();

         a.ContentEncoding = BodyPartEncoding.UTF7;
         htmlbody = a.Data;
    }
 }
}

auth.Logout();
connection.Close();

2
请勿与他人共享您的登录详细信息 :) - Serkan Hekimoglu
这是一个测试账户,没有问题。谢谢您的提醒。 - Buddhi Dananjaya
如何运行这段代码?它仅适用于从 Gmail 账户下载电子邮件吗?在下载后是否有可能转换已下载的文件? - Nicholas
4个回答

1

我的选择是 CodePlex 上的 interimap 项目。它能完美地处理附件。


1

0

你写代码的地方

ImapMailboxMessage msg = mailbox.Messages[mailCount - 1];

当你在选定的文件夹中有多个电子邮件时,可以使用ImapMailboxMessage msg = mailbox.Messages[i];

以便更好地工作。

[mailCount - 1]从不读取最后一条消息。


-1

如果您想短期使用,请使用 Chilkat IMAP API。 您可以将整个电子邮件保存为 eml 文件,并有足够的示例来让任何人运行。 它在一个月内完全免费,之后需要付费。

同时,如果您想单独下载附件并使用 coolwired,请使用以下方法

ImapMailboxMessage mbStructure = new ImapMailboxMessage();
mbStructure = command.FetchBodyStructure(a);
for (int j = 0; j < a.BodyParts.Count; j++)
{
 //create dir if doesnot exist
 if (!Directory.Exists(path))
 {
    DirectoryInfo di = Directory.CreateDirectory(path);
 }
 if (mbStructure.BodyParts[j].Attachment)
 {
    //Attachment
    command.FetchBodyPart(mbStructure, mbStructure.BodyParts.IndexOf(mbStructure.BodyParts[j]));
    //Write Binary File
    FileStream fs = new FileStream(path +  mbStructure.BodyParts[j].FileName, FileMode.Create);
    fs.Write(mbStructure.BodyParts[j].DataBinary, 0, (int)mbStructure.BodyParts[j].DataBinary.Length);
    fs.Flush();
    fs.Close();
 }
}                                  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接