public List <EmailMessage> ReceiveEmail(int maxCount = 10) { using (var emailClient = new MailKit.Net.Pop3.Pop3Client()) { emailClient.Connect(_emailConfiguration.PopServer, _emailConfiguration.PopPort, true); emailClient.AuthenticationMechanisms.Remove("XOAUTH2"); emailClient.Authenticate(_emailConfiguration.PopUsername, _emailConfiguration.PopPassword); List <EmailMessage> emails = new List <EmailMessage>(); for (int i = 0; i < emailClient.Count && i < maxCount; i++) { var message = emailClient.GetMessage(i); var emailMessage = new EmailMessage { Content = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody, Subject = message.Subject }; emailMessage.ToAddresses.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new EmailAddress { Address = x.Address, Name = x.Name })); emailMessage.FromAddresses.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EmailAddress { Address = x.Address, Name = x.Name })); } return(emails); } }
public static void TestPop3(string username, string password) { using (MailKit.MailSpool client = new MailKit.Net.Pop3.Pop3Client()) { // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; // Non-Encrypted: 110 // SSL/TLS: 995 //client.Connect(RedmineMailService.Trash.UserData.POP, 110, false); client.Connect(RedmineMailService.Trash.UserData.POP, 995, true); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(username, password); for (int i = 0; i < client.Count; i++) { MimeKit.MimeMessage message = client.GetMessage(i); System.Console.WriteLine("Subject: {0}", message.Subject); } // Next i client.Disconnect(true); } // End Using client } // End Sub TestPop3
/** * Conectar no servidor para fazer o download dos e-mails */ public async Task <List <LogEmail> > downloadAsync(string host, int nroPorta, bool flagSSL, string usuario, string senha, List <string> emailJaBaixados) { //Criar lista para armazenar as novas mensagens. List <LogEmail> listaNovasMensagens = new List <LogEmail>(); Task <List <LogEmail> > OTask = new Task <List <LogEmail> >(() => { using (MailKit.Net.Pop3.Pop3Client client = new MailKit.Net.Pop3.Pop3Client()) { client.Connect(host, nroPorta, flagSSL); client.Authenticate(usuario, senha); client.AuthenticationMechanisms.Remove("XOAUTH2"); int limit = client.Count; int lastcount; for (int i = 0; i < limit; i++) { lastcount = (limit - 1) - i; var NovaMensagem = client.GetMessage(lastcount); LogEmail NovoEmail = this.mapper(NovaMensagem, lastcount); bool flagSucesso = this.salvarEmail(NovoEmail); if (flagSucesso) { client.DeleteMessage(lastcount); } } client.Disconnect(true); } return(listaNovasMensagens); }); OTask.Start(); try { listaNovasMensagens = await OTask; } catch (Exception ex) { UtilLog.saveError(ex.GetBaseException(), String.Concat(ex.Message, "\n", ex.StackTrace)); } return(listaNovasMensagens); }
private bool PrintMails(bool login_only = false) { try { this.mailclient.Connect(this.mail_server_name, this.mail_server_port_number, this.mail_server_ssl); this.mailclient.Authenticate(this.mail_server_username, this.mail_server_password); if (!login_only) { /* * imapclient.Inbox.Open(MailKit.FolderAccess.ReadOnly); * var uids = imapclient.Inbox.Search(MailKit.Search.SearchQuery.All); * foreach(var uid in uids) * { * //var message = imapclient.Inbox.GetMessage(uid); * //Console.Write(message.Body); * } */ if (this.mailclient is MailKit.Net.Pop3.Pop3Client) { MailKit.Net.Pop3.Pop3Client popclient = (MailKit.Net.Pop3.Pop3Client) this.mailclient; for (int i = 0; i < popclient.Count; i++) { var message = popclient.GetMessage(i); if (this.mail_from_condition != null && this.mail_from_condition != "") { bool contains_addr = false; foreach (var addr in message.From) { if (addr is MimeKit.MailboxAddress) { var mailbox_addr = (MimeKit.MailboxAddress)addr; if (mailbox_addr.Address == this.mail_from_condition) { contains_addr = true; break; } } } if (!contains_addr) { continue; } } if (this.mail_subject_condition != null && this.mail_subject_condition != "") { if (!message.Subject.Contains(this.mail_subject_condition)) { continue; } } if (this.mail_body_condition != null && this.mail_body_condition != "") { if (!message.TextBody.Contains(this.mail_body_condition)) { continue; } } if (SendStringToStarPRNT(message.TextBody)) { popclient.DeleteMessage(i); } } } else if (this.mailclient is MailKit.Net.Imap.ImapClient) { MailKit.Net.Imap.ImapClient imapclient = (MailKit.Net.Imap.ImapClient) this.mailclient; MailKit.Search.TextSearchQuery from_query = null, subject_query = null, body_query = null; if (this.mail_from_condition != null && this.mail_from_condition != "") { from_query = MailKit.Search.SearchQuery.FromContains(this.mail_from_condition); } if (this.mail_subject_condition != null && this.mail_subject_condition != "") { subject_query = MailKit.Search.SearchQuery.SubjectContains(this.mail_subject_condition); } if (this.mail_body_condition != null && this.mail_body_condition != "") { body_query = MailKit.Search.SearchQuery.BodyContains(this.mail_body_condition); } MailKit.Search.SearchQuery query = MailKit.Search.SearchQuery.All; if (from_query != null) { Trace.WriteLine(from_query.Term + " " + from_query.Text); query = query.And(from_query); } if (subject_query != null) { Trace.WriteLine(subject_query.Term + " " + subject_query.Text); query = query.And(subject_query); } if (body_query != null) { Trace.WriteLine(body_query.Term + " " + body_query.Text); query = query.And(body_query); } imapclient.Inbox.Open(MailKit.FolderAccess.ReadWrite); var uids = imapclient.Inbox.Search(query); var deleted_uids = new List <MailKit.UniqueId>(); foreach (MailKit.UniqueId uid in uids) { var message = imapclient.Inbox.GetMessage(uid); if (SendStringToStarPRNT(message.TextBody)) { imapclient.Inbox.AddFlags(uid, MailKit.MessageFlags.Deleted, true); deleted_uids.Add(uid); } } if (deleted_uids.Count > 0) { imapclient.Inbox.Expunge(deleted_uids); } } } } catch (Exception e) when(e is System.IO.IOException || e is System.Net.Sockets.SocketException) { Trace.TraceError("メールサーバーとの通信に失敗しました。\n" + e.ToString()); if (this.print_on_error) { SendStringToStarPRNT("【エラー】" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + "メールサーバーとの通信に失敗しました。自動印刷ができない状態です。ネットワークかメールサーバーに異常が発生している可能性があります。このエラーが出続ける場合は管理者にお問い合わせ下さい。\n" + e.GetType().ToString() + ": " + e.Message + "\n\n\n\n\n\n\n\n\n\n"); } } catch (MailKit.Security.AuthenticationException e) { Trace.TraceError("メールサーバーへのログインに失敗しました。ユーザー名かパスワードが間違っているか、サーバー側でアカウントロックされた可能性があります。\n" + e.ToString()); if (this.print_on_error) { SendStringToStarPRNT("【エラー】" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + "メールサーバーへのログインに失敗しました。自動印刷ができない状態です。管理者にお問い合わせ下さい。" + e.Message + "\n\n\n\n\n\n\n\n\n\n"); } } catch (Exception e) { Trace.TraceError("メール処理でエラーが発生しました。\n" + e.ToString()); if (this.print_on_error) { SendStringToStarPRNT("【エラー】" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + "自動印刷ができない状態です。管理者にお問い合わせ下さい。\n" + e.GetType().ToString() + ": " + e.Message + "\n\n\n\n\n\n\n\n\n\n"); } } finally { if (this.mailclient.IsConnected) { this.mailclient.Disconnect(true); } } return(true); }