Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

c# - Download attachment from email

How can I browse the email and download all attachments ?

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 + "
";
        }

        //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 + "
";
            }

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

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

                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 + "
";

                    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
}

It does not work, have you another simple idea ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try something like this

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

// here is a reference link you can use as well Getting Email Attachments


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...