private void PreencheEmails(Usuario_Imap usuario_imap, string pasta, ref List <Email> emails) { Imap imap = usuario_imap.Imap; using (ImapConnect connection = new ImapConnect(imap.Host, imap.Porta, imap.SSL)) { ImapCommand command = new ImapCommand(connection); ImapAuthenticate authentication = new ImapAuthenticate(connection, usuario_imap.Email, usuario_imap.Password); ImapMailbox mailbox; connection.Open(); authentication.Login(); mailbox = command.Select(pasta); mailbox = command.Fetch(mailbox); foreach (ImapMailboxMessage m in mailbox.Messages.Reverse <ImapMailboxMessage>()) { string destinatarios = string.Empty; Email email = new Email(); m.To.ToList().ForEach(a => destinatarios += a.Address + "; "); email.Remetente = m.From.Address; email.Destinatario = destinatarios.Trim(); email.Assunto = m.Subject; email.Data_Envio = m.Sent.ToString("dd/MM/yyyy"); email.Usuario_Imap = usuario_imap; ImapMailboxMessage msg = command.FetchBodyStructure(m); if (m.HasText) { msg = command.FetchBodyPart(m, m.Text); email.Mensagem = msg.BodyParts[m.Text].Data; } if (m.HasHTML) { msg = command.FetchBodyPart(m, m.HTML); string html = msg.BodyParts[m.HTML].Data; Encoding encoding = msg.BodyParts[m.HTML].Encoding; if (msg.BodyParts[m.HTML].ContentEncoding == BodyPartEncoding.BASE64) { email.Mensagem = html.DecodeBase64(encoding); } else { email.Mensagem = html.ToUTF8(encoding); } } emails.Add(email); } authentication.Logout(); connection.Close(); } }
static void Main(string[] args) { using (ImapConnect connection = new ImapConnect("imap.gmail.com", 993, true)) { ImapCommand command = new ImapCommand(connection); ImapAuthenticate authentication = new ImapAuthenticate(connection, "user", "password"); ImapMailbox mailbox; connection.Open(); authentication.Login(); mailbox = command.Select("INBOX"); mailbox = command.Fetch(mailbox, mailbox.Exist - 20, mailbox.Exist); foreach (ImapMailboxMessage m in mailbox.Messages.Reverse <ImapMailboxMessage>()) { ImapMailboxMessage msg = command.FetchBodyStructure(m); if (m.HasText) { msg = command.FetchBodyPart(m, m.Text); String textBody = msg.BodyParts[m.Text].Data; } if (m.HasHTML) { msg = command.FetchBodyPart(m, m.HTML); String htmlText = msg.BodyParts[m.HTML].Data; } Console.WriteLine("---------------------------------------"); Console.WriteLine(string.Format("Remetente: {0}", m.From)); Console.WriteLine(string.Format("Assunto: {0}", m.Subject)); Console.WriteLine("---------------------------------------"); } authentication.Logout(); connection.Close(); } Console.Read(); }