How to read POP3 emails from C #?

2

What I want to do, is read a type of attachment, for example those that are .pdf, of those emails that have not been read. To begin, I was trying with a simple example to read, but it tells me the following message:

Server did not accept user credentials

And I'm sure the username and password are correct.

The simple example with which I was testing would be this (It's a class I did):

class ConnectPop3
{             
    private string username = "[email protected]";

    private string password = "miclave";

    private int port = 995;

    private string hostname = "pop.gmail.com";

    private bool useSsl = true;

    public List<Message> getMensajes()
    {
        try
        {

            // El cliente se desconecta al terminar el using
            using (Pop3Client client = new Pop3Client())
            {
                // conectamos al servidor
                client.Connect(hostname, port, useSsl);

                // Autentificación
                client.Authenticate(username, password, OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword);

                // Obtenemos los Uids mensajes
                List<string> uids = client.GetMessageUids();

                // creamos instancia de mensajes
                List<Message> lstMessages = new List<Message>();

                // Recorremos para comparar
                for (int i = 0; i < uids.Count; i++)
                {
                    //obtenemos el uid actual, es él id del mensaje
                    string currentUidOnServer = uids[i];

                    //por medio del uid obtenemos el mensaje con el siguiente metodo
                    Message oMessage = client.GetMessage(i + 1);

                    //agregamos el mensaje a la lista que regresa el metodo
                    lstMessages.Add(oMessage);

                }

                // regresamos la lista
                return lstMessages;
            }
        }

        catch (Exception ex)
        {
            //si ocurre una excepción regresamos null, es importante que cachen las excepciones, yo
            //lo hice general por modo de ejemplo
            return null;
        }
    }
}

And the index I call it like this:

protected void LeerCorreo_Click(object sender, EventArgs e)
    {

       ConnectPop3 oCP3 = new ConnectPop3();

        //invocamos el metodo para obtener mensajes
        List<OpenPop.Mime.Message> lstMensajes = oCP3.getMensajes();

        //recorremos y mostramos el asunto
        foreach (OpenPop.Mime.Message oMensaje in lstMensajes)
        {
            //Console.WriteLine(oMensaje.Headers.Subject);
            MessageBox.Show(oMensaje.Headers.Subject);
        }
   }

I would like to know how to solve the message Server did not accept user credentials. Then I would like to be able to read the emails that have not been read in the inbox, but from those emails, only the attachments with a specific format.

Then I tried this way: I'm currently testing it like this:

       ImapClient ic = new ImapClient("imap.gmail.com", "[email protected]", "miclave",
        AE.Net.Mail.AuthMethods.Login, 993, true);                
        // Select a mailbox. Case-insensitive
        ic.SelectMailbox("INBOX");
        Console.WriteLine(ic.GetMessageCount());             
        System.Windows.Forms.MessageBox.Show(ic.GetMessageCount().ToString());

        MailMessage[] mm = ic.GetMessages(0, 10);
        foreach (MailMessage m in mm)
        {
            Console.WriteLine(m.Subject);
            System.Windows.Forms.MessageBox.Show(m.Subject);
        }
        // Probably wiser to use a using statement
        ic.Dispose();

but I need to read the ones that have not been read from the inbox, but in this case I read them all.

    
asked by Danilo 01.11.2016 в 19:09
source

1 answer

2

To read Gmail emails using Imap, I would use the AE.Net.Mail library (you have it available in NuGet) and the code would be something like this:

AE.Net.Mail.ImapClient ic = new AE.Net.Mail.ImapClient("imap.gmail.com", "[email protected]", "pass",
AE.Net.Mail.AuthMethods.Login, 993, true);
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());

Keep in mind that to work, you should have port 993 open.

Edit The following code gets the id's of the unread emails and then obtains the file names of the attachments:

List<string> ids = new List<string>();
List<AE.Net.Mail.MailMessage> mails = new List<AE.Net.Mail.MailMessage>();

using (var imap = new AE.Net.Mail.ImapClient("imap.gmail.com", username, password, AE.Net.Mail.ImapClient.AuthMethods.Login, 993, true)) 
{
    var msgs = imap.SearchMessages(SearchCondition.Unseen());
    for (int i = 0; i < msgs.Length; i++) {
        string msgId = msgs[i].Uid;
        ids.Add(msgId);            
    }

    foreach (string id in ids)
    {
        mails.Add(imap.GetMessage(id, headersonly: false));
    }
}

foreach(var msg in mails)
{
    foreach (var att in msg.Attachments) 
    {
        string fName;
        fName = att.Filename;
    }
}

I hope this example helps you.

    
answered by 02.11.2016 / 17:36
source