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

时间:2009-10-07 10:20:27

标签: c# imap attachment

我在C#上使用sourceforge上名为“Koolwired.Imap”的开源项目尝试了这个。

下载邮件时没关系,但对于附件,它只列出附件的文件名。是否有人试过这个?

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

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();

5 个答案:

答案 0 :(得分:1)

我的选择是关于codeplex的interimap项目。它完美地处理附件。

答案 1 :(得分:1)

答案 2 :(得分:0)

ImapX是最好的图书馆。与GMail完美配合。死了简单易用。

http://hellowebapps.com/products/imapx/

答案 3 :(得分:0)

你写的地方

ImapMailboxMessage msg = mailbox.Messages[i];

您可以使用[mailCount -1]

如果您在所选文件夹中有多个电子邮件,则效果更佳。

{{1}}永远不会读取最后一条消息。

答案 4 :(得分:-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();
 }
}