2011-12-22 137 views
1

如何浏览电子邮件并下载所有附件?从电子邮件下载附件

public string Connect_Email() 
{ 
    string Res = ""; 

    try 
    { 
     mailclient = new TcpClient("pop.orange.fr", Convert.ToInt16("110")); 
    } 
    catch (SocketException ExTrhown) 
    { 
     Res = "Unable to connect to server 1"; 
     throw new Exception(ExTrhown.Message + "Unable to connect to server 1"); 
    } 

    ns = mailclient.GetStream(); 
    sr = new StreamReader(ns); 
    sw = new StreamWriter(ns); 

    response = sr.ReadLine(); //Get opening POP3 banner 

    sw.WriteLine("USER " + "[email protected]"); //Send username 
    sw.Flush(); 

    response = sr.ReadLine(); 

    if (response.Substring(0, 4) == "-ERR") 
    { 
     Res = "Unable to log into server 2"; 
    } 

    sw.WriteLine("PASS " + "xxxxx"); //Send password 
    sw.Flush(); 

    response = sr.ReadLine(); 

    if (response.Substring(0, 3) == "-ER") 
    { 
     Res = "Unable to log into server 3"; 
    } 

    return Res; 
} 

public void Get_Attacht() 
{ 
    string ClientName = ""; 

    #region Chercher Attachment 
    sw.WriteLine("STAT"); //Send stat command to get number of messages 
    sw.Flush(); 

    response = sr.ReadLine(); 

    //find number of message 
    string[] nummess = response.Split(' '); 
    totmessages = Convert.ToInt16(nummess[1]); 

    //read emails 
    for (int i = 1; i <= totmessages; i++) 
    { 
     msg = null; 

     sw.WriteLine("top " + i + " 0"); //read header of each message 
     sw.Flush(); 
     response = sr.ReadLine(); 

     while (true) 
     { 
      response = sr.ReadLine(); 
      if (response == ".") 
       break; 
      msg = msg + response + "\r\n"; 
     } 

     //read attachment 
     attachment = null; 
     if (Regex.Match(msg, "multipart/mixed").Success) 
     { 
      msg = null; 
      sw.WriteLine("retr " + i.ToString()); //Retrieve entire message 
      sw.Flush(); 
      response = sr.ReadLine(); 

      while (true) 
      { 
       response = sr.ReadLine(); 
       if (response == ".") 
        break; 
       msg = msg + response + "\r\n"; 
      } 

      int End = msg.IndexOf(".csv"); 
      string LeFile = msg.Substring(End - 9, 9); 

      if (Regex.Match(msg, LeFile + ".csv").Success) 
      { 
       data = msg.Split('\r'); 

       startindex = 0; 
       index = 0; 
       lastindex = 0; 
       x = null; 
       ms = null; 
       fs = null; 

       while (true) 
       { 
        attachment = null; 
        while (!Regex.Match(data[index].Trim(), "filename").Success) 
        { 
         index++; 
        } 
        if (index == data.Length - 1) break; 
        FileName_Email = data[index].Trim().Substring(42).Replace("\"", ""); 

        //find start of attachment data 
        index++; 
        while (data[index].Length != 1) 
        { 
         index++; 
        } 

        if (index == data.Length - 1) break; 
        startindex = index + 1; 

        //find end of data 
        index = startindex + 1; 
        while ((!Regex.Match(data[index].Trim(), "--0").Success) && (data[index].Length != 1) && (index < data.Length - 1)) 
        { 
         index++; 
        } 
        if (index == data.Length) break; 
        lastindex = index - 2; 

        for (int j = startindex; j <= lastindex; j++) 
        { 
         attachment = attachment + data[j]; 
        } 
        attachment = attachment + "\r\n"; 

        if (Regex.Match(FileName_Email.ToLower(), "csv").Success) 
        { 
         byte[] filebytes = Convert.FromBase64String(attachment); 
         FileStream LeFS = new FileStream(filePath + "\\testDEC.csv", FileMode.Create, FileAccess.Write, FileShare.None); 
         LeFS.Write(filebytes, 0, filebytes.Length); 
         LeFS.Close(); 
         break; 
        } 

       } 
      } 
     } 
    } 

    sw.WriteLine("quit"); //quit 
    sw.Flush(); 
    #endregion 
} 

它不起作用,你有没有另一个简单的想法?

+0

您正在使用哪封电子邮件..您使用的是您所在的OutLook/Exchaange服务器..? – MethodMan 2011-12-22 17:27:49

+0

任何具有服务器,登录名和密码的在线电子邮件服务器。但不是Outlook或Exchange – user609511 2011-12-22 17:33:54

回答

2

尝试这样的事情

using(Pop3 pop3 = new Pop3()) 
{ 
    pop3.Connect("server"); 
    pop3.UseBestLogin("user", "password"); 
    foreach (string uid in pop3.GetAll()) 
    { 
     IMail email = new MailBuilder() 
     .CreateFromEml(pop3.GetMessageByUID(uid)); 
     Console.WriteLine(email.Subject); 
     // save all attachments to disk 
     email.Attachments.ForEach(mime => mime.Save(mime.SafeFileName)); 
    } 
    pop3.Close(); 
} 

//这里是你可以使用,以及 Getting Email Attachments

+1

谢谢你...但它不是免费的或开源的。 – user609511 2011-12-22 18:13:14

+0

此文件有源代码在这里尝试此链接,而不是你必须做你自己的谷歌搜索http://www.codeproject.com/KB/IP/despop3client.aspx – MethodMan 2011-12-22 18:20:30

3

如果您正尝试通过POP3阅读电子邮件,我建议您使用OpenPOP.NET library而不是滚动自己的邮件。这很容易使用。

+0

谢谢..但它是窗口应用程序,我使用Web应用程序。我可以使用OpenPop.dll吗? – user609511 2011-12-22 18:12:50

+2

@ user609511:OpenPop.NET不是应用程序;它是一个库,你可以从你的C#代码中调用。它将取代你上面写的大部分内容。您应该可以在Web应用程序中使用它。 – 2011-12-22 18:34:22

2

感谢大家的贡献参考链接。最后我用POP3:

public string Connect_Email() 
{ 
    string Res = ""; 
    try 
    { 
     Pop3Client email = new Pop3Client("login", "password", "server"); 
     email.OpenInbox(); 

     while (email.NextEmail()) 
     { 
      if (email.IsMultipart) 
      { 
       IEnumerator enumerator = email.MultipartEnumerator; 
       while (enumerator.MoveNext()) 
       { 
        Pop3Component multipart = (Pop3Component) 
        enumerator.Current; 
        if (multipart.IsBody) 
        { 
         //Console.WriteLine("Multipart body:" + multipart.Name); 
        } 
        else 
        { 
         //Console.WriteLine("Attachment name=" + multipart.Name); // ... etc 
         byte[] filebytes = Convert.FromBase64String(multipart.Data); 

         //Search FileName 
         int Begin = multipart.ContentType.IndexOf("name="); 
         string leFileNale = multipart.ContentType.Substring(Begin + 5, 12); 

         FileStream LeFS = new FileStream(filePath + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None); 
         LeFS.Write(filebytes, 0, filebytes.Length); 
         LeFS.Close(); 
        } 
       } 
      } 
     } 
     email.CloseConnection(); 
    } 
    catch (Pop3LoginException) 
    { 
     Res = "Vous semblez avoir un problème de connexion!"; 
    } 
    return Res; 
} 

它工作的很好,但我仍然需要找到并下载我自己的附件。

byte[] filebytes = Convert.FromBase64String(multipart.Data); 

//Search FileName 
int Begin = multipart.ContentType.IndexOf("name="); 
string leFileNale = multipart.ContentType.Substring(Begin + 5, 12); 

FileStream LeFS = new FileStream(filePath + "\\" + leFileNale, FileMode.Create, FileAccess.Write, FileShare.None); 
LeFS.Write(filebytes, 0, filebytes.Length); 
LeFS.Close();