public bool Test() { BaseProtocolClient ingoing_client = (Account.Imap) ? (BaseProtocolClient)MailClientBuilder.Imap() : MailClientBuilder.Pop(); MailServerHelper.Test(ingoing_client, new MailServerSettings { Url = Account.Server, Port = Account.Port, AccountName = Account.Account, AccountPass = Account.Password, AuthenticationType = Account.AuthenticationTypeIn, EncryptionType = Account.IncomingEncryptionType }); MailServerHelper.TestSmtp(new MailServerSettings { Url = Account.SmtpServer, Port = Account.SmtpPort, AccountName = Account.SmtpAccount, AccountPass = Account.SmtpPassword, AuthenticationType = Account.AuthenticationTypeSmtp, EncryptionType = Account.OutcomingEncryptionType }); return(true); }
private static Pop3Client TestGetPop3Client(string pop3_server, string pop3_account, string pop3_password, int pop3_port, bool use_ssl) { var pop = MailClientBuilder.Pop(); Debug.WriteLine("Connect to Pop3:"); var watch = new Stopwatch(); watch.Start(); var result = use_ssl ? pop.ConnectSsl(pop3_server, pop3_port, pop3_account, pop3_password) : pop.Connect(pop3_server, pop3_port, pop3_account, pop3_password); watch.Stop(); Debug.WriteLine("Elapsed Connect pop: " + watch.ElapsedMilliseconds); if (!result.StartsWith("+")) { throw new Exception("Bad connection result: " + result); } return(pop); }
public static List <string> TestGetPopHeaderMD5(string pop3_server, string pop3_account, string pop3_password, int pop3_port, bool use_ssl) { var headers_md5 = new List <string>(); var pop = MailClientBuilder.Pop(); Debug.WriteLine("Pop3:"); try { pop = TestGetPop3Client(pop3_server, pop3_account, pop3_password, pop3_port, use_ssl); var watch = new Stopwatch(); watch.Start(); for (var i = 1; i <= pop.MessageCount; i++) { try { var header = pop.RetrieveHeaderObject(i); var unique_identifier = string.Format("{0}|{1}|{2}|{3}", header.From.Email, header.Subject, header.DateString, header.MessageId); var md5 = unique_identifier.GetMD5(); headers_md5.Add(md5); Debug.WriteLine("# " + i + "MD5: " + md5); Debug.WriteLine("unique_identifier: " + unique_identifier); } catch { //SKEEP RetrieveHeader ERROR if (!pop.IsConnected) { break; } } } watch.Stop(); Debug.WriteLine("Elapsed Get pop md5: " + watch.ElapsedMilliseconds); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (pop != null && pop.IsConnected) { pop.Disconnect(); } } return(headers_md5); }
public static bool TryTestPop(MailServerSettings settings, out string last_error) { try { last_error = String.Empty; return(Test(MailClientBuilder.Pop(), settings)); } catch (Exception ex) { last_error = ex.Message; return(false); } }
public static void TestGoogleSmtpLoginViaOAuth2(string account, string refresh_token) { var authorizatior = new GoogleOAuth2Authorization(); var granted_access = authorizatior.RequestAccessToken(refresh_token); if (granted_access == null) { return; } var smtp = MailClientBuilder.Smtp(); smtp.ConnectSsl("smtp.googlemail.com", 465); smtp.Authenticate(account, granted_access.AccessToken, SaslMechanism.OAuth2); //Do some work... smtp.Disconnect(); }
public static void TestGoogleImapLoginViaOAuth2(string account, string refresh_token) { var authorizatior = new GoogleOAuth2Authorization(); var granted_access = authorizatior.RequestAccessToken(refresh_token); if (granted_access == null) { return; } var imap = MailClientBuilder.Imap(); imap.ConnectSsl("imap.googlemail.com", 993); imap.LoginOAuth2(account, granted_access.AccessToken); //Do some work... imap.Disconnect(); }
public static void TestReceiveMessageImap() { var imap = MailClientBuilder.Imap(); try { const string imap_server = "imap.googlemail.com"; const int imap_port = 993; const string imap_account = "*****@*****.**"; const string imap_password = "******"; imap.ConnectSsl(imap_server, imap_port); imap.Login(imap_account, imap_password, ""); if (!imap.IsConnected) { return; } var inbox = imap.SelectMailbox("inbox"); if (inbox.MessageCount > 0) { var header = inbox.Fetch.HeaderObject(1); Console.WriteLine("Subject: {0} From :{1} ", header.Subject, header.From.Email); } else { Console.WriteLine("There is no message in the imap4 account"); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (imap.IsConnected) { imap.Disconnect(); } } }
static public bool TestSmtp(MailServerSettings settings) { var smtp = MailClientBuilder.Smtp(); string s_result = String.Empty; try { IAsyncResult async_res; if (settings.EncryptionType == EncryptionType.None || settings.EncryptionType == EncryptionType.StartTLS) { async_res = smtp.BeginConnect(settings.Url, settings.Port, null); if (!async_res.AsyncWaitHandle.WaitOne(WAIT_TIMEOUT)) { throw new SmtpConnectionException(MailQueueItem.CONNECTION_TIMEOUT_ERROR); } if (settings.AuthenticationType != SaslMechanism.None || settings.EncryptionType == EncryptionType.StartTLS) { smtp.SendEhloHelo(); } if (settings.EncryptionType == EncryptionType.StartTLS) { smtp.StartTLS(settings.Url); } if (settings.AuthenticationType != SaslMechanism.None) { s_result = smtp.Authenticate(settings.AccountName, settings.AccountPass, settings.AuthenticationType); } } else { async_res = smtp.BeginConnectSsl(settings.Url, settings.Port, null); if (!async_res.AsyncWaitHandle.WaitOne(WAIT_TIMEOUT)) { throw new SmtpConnectionException(MailQueueItem.CONNECTION_TIMEOUT_ERROR); } if (settings.AuthenticationType != SaslMechanism.None) { s_result = smtp.Authenticate(settings.AccountName, settings.AccountPass, settings.AuthenticationType); } } if (settings.AuthenticationType != SaslMechanism.None && !s_result.StartsWith("+")) { throw new SmtpConnectionException(s_result); } return(true); } finally { if (smtp.IsConnected) { smtp.Disconnect(); } } }
private bool RetrievePop(int max_messages_per_session, WaitHandle stop_event, out int processed_messages_count) { var pop = MailClientBuilder.Pop(); try { pop.Authenticated += OnAuthenticated; _log.Debug("Connecting to {0}", Account.EMail); switch (Account.IncomingEncryptionType) { case EncryptionType.StartTLS: pop.ConnectTLS(Account.Server, Account.Port); break; case EncryptionType.SSL: pop.ConnectSsl(Account.Server, Account.Port); break; case EncryptionType.None: pop.Connect(Account.Server, Account.Port); break; } if (Account.AuthenticationTypeIn == SaslMechanism.Login) { pop.Login(Account.Account, Account.Password, Account.Server); } else { pop.Authenticate(Account.Account, Account.Password, Account.AuthenticationTypeIn); } UpdateTimeCheckedIfNeeded(); _log.Debug("UpdateStats()"); pop.UpdateStats(); _log.Debug("GetCAPA()"); GetCAPA(pop); _log.Info("Account: MessagesCount={0}, TotalSize={1}, UIDL={2}, LoginDelay={3}", pop.MessageCount, pop.TotalSize, IsUidlSupported, Account.ServerLoginDelay); if (ProcessMessagesPop(pop, max_messages_per_session, stop_event, out processed_messages_count)) { // If all messages are proccessed Account.MessagesCount = pop.MessageCount; Account.Size = pop.TotalSize; _log.Info("Account '{0}' has been processed.", Account.EMail); } LastRetrieve = DateTime.UtcNow; return(true); } catch (Pop3Exception e) { if (e.Command.StartsWith("USER") || e.Command.StartsWith("PASS")) { if (OnAuthFailed != null) { OnAuthFailed(Account, e.Response); } _log.Warn("Retrieve() Pop3: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n", Account.Server, Account.Port, Account.Account, e.Message); } else { _log.Error("Retrieve() Pop3: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n", Account.Server, Account.Port, Account.Account, e.ToString()); } throw; } finally { try { if (pop.IsConnected) { pop.Disconnect(); } } catch { } } }
public void DownloadMessage(string uidl, string destination_path) { var pop = MailClientBuilder.Pop(); try { _log.Debug("Connecting to {0}", Account.EMail); switch (Account.IncomingEncryptionType) { case EncryptionType.StartTLS: pop.ConnectTLS(Account.Server, Account.Port); break; case EncryptionType.SSL: pop.ConnectSsl(Account.Server, Account.Port); break; case EncryptionType.None: pop.Connect(Account.Server, Account.Port); break; } if (Account.AuthenticationTypeIn == SaslMechanism.Login) { pop.Login(Account.Account, Account.Password, Account.Server); } else { pop.Authenticate(Account.Account, Account.Password, Account.AuthenticationTypeIn); } _log.Debug("GetCAPA()"); GetCAPA(pop); _log.Info("Account: MessagesCount={0}, TotalSize={1}, UIDL={2}, LoginDelay={3}", pop.MessageCount, pop.TotalSize, IsUidlSupported, Account.ServerLoginDelay); if (pop.UniqueIdExists(uidl)) { _log.Info("Message with this uidl exists!"); var index = pop.GetMessageIndex(uidl); _log.Info("StoreMessage(index: {0})", index); pop.StoreMessage(index, false, destination_path); if (File.Exists(destination_path)) { _log.Info("Message stored successfully!\r\n"); } else { _log.Error("Message is missing in destination path!\r\n"); } } else { _log.Info("Message with this uidl not exists!\r\n"); } } catch (Pop3Exception e) { if (e.Command.StartsWith("USER") || e.Command.StartsWith("PASS")) { if (OnAuthFailed != null) { OnAuthFailed(Account, e.Response); } _log.Warn("Retrieve() Pop3: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n", Account.Server, Account.Port, Account.Account, e.Message); } else { _log.Error("Retrieve() Pop3: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n", Account.Server, Account.Port, Account.Account, e.ToString()); } throw; } finally { try { if (pop.IsConnected) { pop.Disconnect(); } } catch { } } }
private bool RetrieveImap(int max_messages_per_session, WaitHandle stop_event, out int proccessed_messages_count) { proccessed_messages_count = max_messages_per_session; var imap = MailClientBuilder.Imap(); try { imap.Authenticated += OnAuthenticated; AuthenticateImap(imap); UpdateTimeCheckedIfNeeded(); // reverse folders and order them to download tagged incoming messages first // gmail returns tagged letters in mailboxes & duplicate them in inbox // to retrieve tags - first we need to download files from "sub" mailboxes var mailboxes = GetImapMailboxes(imap, Account.Server).Reverse().OrderBy(m => m.folder_id); foreach (var mailbox in mailboxes) { _log.Info("Select imap folder: {0}", mailbox.name); var mb_obj = imap.SelectMailbox(mailbox.name); int last_folder_uid; Account.ImapFolders.TryGetValue(mailbox.name, out last_folder_uid); max_messages_per_session = ProcessMessages(mb_obj, mailbox.folder_id, last_folder_uid, max_messages_per_session, stop_event, mailbox.tags); if (0 == max_messages_per_session) { break; } UpdateTimeCheckedIfNeeded(); } _log.Info("Account '{0}' has been processed.", Account.EMail); LastRetrieve = DateTime.UtcNow; proccessed_messages_count -= max_messages_per_session; return(true); } catch (Imap4Exception e) { if (e.Message.StartsWith("USER") || e.Message.StartsWith("PASS")) { if (OnAuthFailed != null) { OnAuthFailed(Account, ""); } _log.Warn("RetrieveImap Server: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n", Account.Server, Account.Port, Account.Account, e.Message); } else { _log.Error("RetrieveImap Server: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n", Account.Server, Account.Port, Account.Account, e.ToString()); } throw; } finally { try { if (imap.IsConnected) { imap.Disconnect(); } } catch { } } }
public static void TestIMAPReceiveMessage(string imap_server, string imap_account, string imap_password, int imap_port, bool use_ssl, string uidl) { var imap = MailClientBuilder.Imap(); try { _log.Debug("Connecting to {0}", imap_account); var match = _imapUidlRegx.Match(uidl); if (!match.Success) { _log.Error("Bad UIDL"); return; } var uid = Convert.ToInt32(match.Groups[1].Value); var folder = Convert.ToInt32(match.Groups[2].Value); var uid_validity = Convert.ToInt32(match.Groups[3].Value); if (use_ssl) { imap.ConnectSsl(imap_server, imap_port); } else { imap.Connect(imap_server, imap_port); } imap.Login(imap_account, imap_password, ""); var folders = MailQueueItem.GetImapMailboxes(imap, imap_server); var founded = (from n in folders where n.folder_id == folder select n) .FirstOrDefault(); if (string.IsNullOrEmpty(founded.name)) { _log.Error("Bad UIDL folder"); return; } var mb = imap.SelectMailbox(founded.name); if (mb.UidValidity != uid_validity) { _log.Error("Bad UID_VALIDITY"); return; } var message = mb.Fetch.UidMessageObject(uid); var mail_info = new MailMessageItem(message); // ReSharper disable UnusedVariable var sanitazed = HtmlSanitizer.Sanitize(mail_info.HtmlBody, true); // ReSharper restore UnusedVariable } catch (Pop3Exception ex) { Console.WriteLine(ex.ToString()); } finally { try { if (imap.IsConnected) { imap.Disconnect(); } } catch { } } }
public static void TestPOPReceiveMessage(string pop3_server, string pop3_account, string pop3_password, int pop3_port, bool use_ssl, string uidl) { var pop = MailClientBuilder.Pop(); try { _log.Debug("Connecting to {0}", pop3_account); var result = use_ssl ? pop.ConnectSsl(pop3_server, pop3_port, pop3_account, pop3_password) : pop.Connect(pop3_server, pop3_port, pop3_account, pop3_password); if (!result.StartsWith("+")) { return; } if (pop.UniqueIdExists(uidl)) { _log.Info("Message with this uidl exists!"); var index = pop.GetMessageIndex(uidl); _log.Info("StoreMessage(index: {0})", index); var destination_path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"strange.eml"); pop.UpdateStats(); //pop.StoreMessage(index, false, destination_path); var message = pop.RetrieveMessageObject(index); var mail_info = new MailMessageItem(message); _log.Info(mail_info.HtmlBody); if (File.Exists(destination_path)) { _log.Info("Message stored successfully!\r\n"); } else { _log.Error("Message is missing in destination path!\r\n"); } } else { _log.Info("Message with this uidl not exists!\r\n"); } } catch (Pop3Exception ex) { Console.WriteLine(ex.ToString()); } finally { try { if (pop.IsConnected) { pop.Disconnect(); } } catch { } } }
public static List <string> TestGetImapHeaderMD5(string imap_server, string imap_account, string imap_password, int imap_port, bool use_ssl) { var headers_md5 = new List <string>(); var imap = MailClientBuilder.Imap(); Debug.WriteLine("Imap:"); try { var watch = new Stopwatch(); watch.Start(); if (use_ssl) { imap.ConnectSsl(imap_server, imap_port); } else { imap.Connect(imap_server, imap_port); } watch.Stop(); Debug.WriteLine("Elapsed Connect imap: " + watch.ElapsedMilliseconds); watch.Reset(); watch.Start(); imap.LoginFast(imap_account, imap_password, ""); watch.Stop(); Debug.WriteLine("Elapsed LoginFast imap: " + watch.ElapsedMilliseconds); watch.Reset(); watch.Start(); const string folder_name = "inbox"; var mb = imap.ExamineMailbox(folder_name); watch.Stop(); Debug.WriteLine("Elapsed ExamineMailbox imap: " + watch.ElapsedMilliseconds); watch.Reset(); watch.Start(); for (var i = 1; i <= mb.MessageCount; i++) { var header = mb.Fetch.HeaderLinesPeek(i, new[] { "Date", "Subject", "Message-ID", "From" }); var unique_identifier = string.Format("{0}|{1}|{2}|{3}", header["Date"], header["Subject"], header["Message-ID"], header["From"]); var md5 = unique_identifier.GetMD5(); headers_md5.Add(md5); Debug.WriteLine("# " + i + "MD5: " + md5); Debug.WriteLine("unique_identifier: " + unique_identifier); } watch.Stop(); Debug.WriteLine("Elapsed Get imap md5: " + watch.ElapsedMilliseconds); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (imap.IsConnected) { imap.Disconnect(); } } return(headers_md5); }