private void ExecuteThread() { try { using (Pop3Client client = new Pop3Client()) { Write("Connecting to " + txtAddress.Text + "...\n"); client.Connect(txtAddress.Text, (int)nPort.Value, chkSSL.Checked); Write("Login with " + txtUsername.Text + "...\n"); client.Authenticate(txtUsername.Text, txtPassword.Text, authMethod); int messageCount = client.GetMessageCount(); setProgressBarMaximum(messageCount); Write("Detected " + messageCount + " message/s to delete.\n"); if (!test && messageCount > 0) { Write("Start deleting messages, the operation may take a long time...\n"); client.DeleteAllMessages(); Write("All messages deleted!\n"); } client.Disconnect(); Write("Disconnected from " + txtAddress.Text + ".\n"); } } catch { } }
/// <summary> /// Retrieves emailed FillPerfect contact us form response emails and puts them in the database /// </summary> /// <param name="procParams"></param> /// <returns></returns> public GeneralSuccessResultViewModel Execute(FetchFpContactResponseEmailsParams procParams) { const string FORMS_EMAIL = "*****@*****.**"; const string FORMS_PASS = "******"; const string POP_HOST = "pop.gmail.com"; const int POP_PORT = 995; const bool USE_SSL = true; // Download all the new mail messages from the email using (var client = new Pop3Client()) { try { client.Connect(POP_HOST, POP_PORT, USE_SSL); client.Authenticate(FORMS_EMAIL, FORMS_PASS); int messageCount = client.GetMessageCount(); for (int x = messageCount; x > 0; x--) { var message = client.GetMessage(x); if (message.Headers.Subject == "cs fp form filled out") { string[] bodyLines = message.FindFirstPlainTextVersion() .GetBodyAsText() .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // make sure the message is as expected if (bodyLines.Length == 4) { _context.FillPerfectContactResponses.Add(new FillPerfectContactResponse { Name = bodyLines[0], Email = bodyLines[1], School = bodyLines[2], Program = bodyLines[3], ReceivedDate = message.Headers.DateSent }); } } } _context.SaveChanges(); client.DeleteAllMessages(); } catch (PopClientException) { return(new GeneralSuccessResultViewModel { WasSuccessful = false }); } } return(new GeneralSuccessResultViewModel { WasSuccessful = true }); }
public void DeleteAllMessages(string hostname, bool useSsl, int port, string username, string password) { using (var pop3Client = new Pop3Client()) { pop3Client.Connect(hostname, port, useSsl); //specify "recent:" to get messages that have already been opened pop3Client.Authenticate($"recent:{username}", password, AuthenticationMethod.UsernameAndPassword); pop3Client.DeleteAllMessages(); pop3Client.Disconnect(); } }
/// <summary> /// This method is the heavy lifter to get all email messages from a POP3 account. This is called by the GetAllEmailsFromAnEmailAccount method /// in the Core.cs /// </summary> /// <param name="hostname">Domain</param> /// <param name="port">Usually always 110 for Pop3</param> /// <param name="useSsl">SSL true or false</param> /// <param name="username">Email Account</param> /// <param name="password">Password for the account</param> /// <param name="delete">Delete all emails from the account after the account's emails are saved.</param> /// <returns></returns> public static List <Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password, bool delete = false) { using (Pop3Client client = new Pop3Client()) { client.Connect(hostname, port, useSsl); client.Authenticate(username, password); int messageCount = client.GetMessageCount(); List <Message> allMessages = new List <Message>(messageCount); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); } int number = 1; // Now return the fetched messages foreach (var emailText in allMessages) { DateTime date = DateTime.Today; var dir = $@"c:\Automation Logs\{date:MM.dd.yyyy}\Emails\"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } MessagePart plainText = emailText.FindFirstPlainTextVersion(); plainText.Save(new FileInfo(dir + $"\\Email {number}.txt")); number++; } // Delete all messages from the account if (delete == true) { try { client.DeleteAllMessages(); } catch (Exception _ex) { Console.WriteLine("Error occured trying to delete with FetchAllMessages method." + Environment.NewLine + _ex); } } return(allMessages); } }
public void LoginForm_PasswordRestoreWithValidEmail() { using (IWebDriver driver = new FirefoxDriver()) { driver.Navigate().GoToUrl(gg); //Открытие формы IWebElement formLink = driver.FindElement(By.XPath(@"//*[@id=""top_back""]/div[3]/a[1]")); formLink.Click(); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); IWebElement overlay = driver.FindElement(By.Id("cboxOverlay")); IWebElement colorbox = driver.FindElement(By.Id("colorbox")); IWebElement messageBox = driver.FindElement(By.ClassName("status-error")); IWebElement emailField = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("Email"))); IWebElement restoreLink = wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText("Я не помню пароль"))); Assert.IsTrue(colorbox.Displayed, "Форма не открылась"); emailField.SendKeys(validEmail); restoreLink.Click(); try { wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.ClassName("status-message"), "Инструкция по восстановлению отправлена")); } catch (Exception e) { Assert.Fail("Не появилось сообщение об отправке письма"); } } using (Pop3Client client = new Pop3Client()) { client.Connect(hostname, port, useSsl); client.Authenticate(validEmail, emailPass); int messageNumber = client.GetMessageCount(); int i = 0; while (messageNumber == 0 && i < 60) { client.Disconnect(); System.Threading.Thread.Sleep(5000); client.Connect(hostname, port, useSsl); client.Authenticate(validEmail, emailPass); messageNumber = client.GetMessageCount(); i = i++; } Assert.IsTrue(messageNumber > 0, "Письмо не пришло"); MessageHeader headers = client.GetMessageHeaders(messageNumber); RfcMailAddress from = headers.From; string subject = headers.Subject; client.DeleteAllMessages(); Assert.IsFalse(from.HasValidMailAddress && from.Address.Equals("*****@*****.**") && "Восстановление пароля на Gama - Gama".Equals(subject), "Письмо не пришло"); } }
private void btnRun_Click(object sender, EventArgs e) { // Create a POP3 client Pop3Client client = new Pop3Client(); client.Host = this.HostInput.Text; client.Username = this.Username.Text; client.Password = this.Password.Text; client.Port = int.Parse(this.PortInput.Text); client.EnableSsl = true; client.Connect(); // Delete all the messages client.DeleteAllMessages(); MessageBox.Show("Deleted Successfully"); }
/// <summary> /// Get all new Mails from Client Email Account /// </summary> /// <returns>A list of all new Emails</returns> private List <OpenPop.Mime.Message> ReceiveMails() { using (Pop3Client client = new Pop3Client()) { try { // Connect to the server try { client.Connect(glob.MailServerPopAddress, glob.MailServerPort, true); } catch (Exception ex) { Commands.ShowToast(ex.ToString()); } // Authenticate ourselves towards the server client.Authenticate(glob.ClientMailAddress, glob.ClientMailPass); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to download all messages List <OpenPop.Mime.Message> allMessages = new List <OpenPop.Mime.Message>(messageCount); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); } // Delete all messages client.DeleteAllMessages(); // Now return the fetched messages return(allMessages); } catch (Exception pie) { // Mmh... pie return(null); } } }
/// <summary> /// Удаляет все письма с сервера. /// </summary> /// <param name="Login">Логин</param> /// <param name="Password">Пароль</param> /// <param name="Server">POP3 сервер</param> /// <param name="Port">порт</param> /// <param name="UseSSL">использовать или нет SSL</param> public static void DeleteAllEmails(string Login, string Password, string Server, int Port, bool UseSSL) { using (Pop3Client client = new Pop3Client()) { client.Connect(Server, Port, UseSSL); client.Authenticate(Login, Password, AuthenticationMethod.UsernameAndPassword); try { client.DeleteAllMessages(); } catch (OpenPop.Pop3.Exceptions.PopServerException ex) { Log.MesQuestion("Скорее всего превышено количество запросов"); Log.MesQuestion(ex.Message); } } }
public async Task <bool> DeleteAllMessage() { using (Pop3Client client = new Pop3Client()) { if (client.Connected) { client.Disconnect(); } client.Connect(popServer, popPort, isUseSSL); client.Authenticate(accout, pass, AuthenticationMethod.UsernameAndPassword); client.DeleteAllMessages(); await Task.Delay(new Random().Next(500, 1000)); var count = client.GetMessageCount(); return(count == 0); } }
/// <summary> /// Asynchronusly executes the client. /// </summary> /// <returns> /// A task that represents the asynchronous operation. /// </returns> public override async Task ExecuteAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (var pop = new Pop3Client()) { pop.Connect(HostName, Port, EnableSsl); pop.Authenticate(UserName, Password); for (int id = pop.GetMessageCount(); id > 0; --id) { var message = pop.GetMessage(id); if (message != null) { await ParseMessageAsync(message, cancellationToken); } } pop.DeleteAllMessages(); } }
private bool isCardValid(string email, string password) { bool checkStatus = false; Pop3Client client = new Pop3Client(); client.Connect("pop.gmail.com", 995, true); client.Authenticate(email, password); //get number of newly unread messages int counter = client.GetMessageCount(); if (counter >= 1) { client.DeleteAllMessages(); checkStatus = true; client.Disconnect(); } return(checkStatus); }
/// <summary> /// Get a message from POP-mail. /// </summary> /// <param name="hostname">Hostname.</param> /// <param name="port">Port.</param> /// <param name="useSsl">Is SSL used?</param> /// <param name="username">Username of POP.</param> /// <param name="password">Password of POP.</param> /// <returns></returns> public static string getMessage(string hostname, int port, bool useSsl, string username, string password) { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(hostname, port, useSsl); // Authenticate ourselves towards the server client.Authenticate(username, password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); string result = string.Empty; if (messageCount != 0 && client.GetMessage(1).Headers.From.Address.Equals("*****@*****.**")) { result = client.GetMessage(1).FindFirstPlainTextVersion().GetBodyAsText(); } result = messageCount + " _*_" + result; client.DeleteAllMessages(); return(result); } }
private static MailMessage[] GetMailMessagesByPOP3(string contentListPath) { var messages = new List <MailMessage>(); var credentials = MailProvider.Instance.GetPOP3Credentials(contentListPath); var pop3s = Settings.GetValue <POP3Settings>(MAILPROCESSOR_SETTINGS, SETTINGS_POP3, contentListPath) ?? new POP3Settings(); using (var client = new Pop3Client()) { try { client.Connect(pop3s.Server, pop3s.Port, pop3s.SSL); client.Authenticate(credentials.Username, credentials.Password); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error: connecting to mail server " + pop3s.Server + " with the username " + credentials.Username + " failed.", ex)); return(messages.ToArray()); } int messageCount; try { messageCount = client.GetMessageCount(); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error: getting messages failed. Content list: " + contentListPath, ex)); return(messages.ToArray()); } // Messages are numbered in the interval: [1, messageCount] // Most servers give the latest message the highest number for (var i = messageCount; i > 0; i--) { try { var msg = client.GetMessage(i); var mailMessage = msg.ToMailMessage(); //maybe we should skip messages without a real sender //if (mailMessage.Sender != null) messages.Add(mailMessage); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error. Content list: " + contentListPath, ex)); } } try { client.DeleteAllMessages(); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error: deleting messages failed. Content list: " + contentListPath, ex)); } } Logger.WriteVerbose("MailPoller workflow: " + messages.Count + " messages received. Content list: " + contentListPath); return(messages.ToArray()); }
//========================================================================== POP3 implementation private MailMessage[] GetMailMessagesByPOP3(string contentListPath) { var messages = new List <MailMessage>(); var credentials = GetPOP3Credentials(contentListPath); var pop3s = Settings.GetValue <POP3Settings>( MailHelper.MAILPROCESSOR_SETTINGS, MailHelper.SETTINGS_POP3, contentListPath) ?? new POP3Settings(); using (var client = new Pop3Client()) { try { client.Connect(pop3s.Server, pop3s.Port, pop3s.SSL); client.Authenticate(credentials.Username, credentials.Password); } catch (Exception ex) { SnLog.WriteException(ex, "Mail processor workflow error: connecting to mail server " + pop3s.Server + " with the username " + credentials.Username + " failed."); return(messages.ToArray()); } int messageCount; try { messageCount = client.GetMessageCount(); } catch (Exception ex) { SnLog.WriteException(ex, "Mail processor workflow error: getting messages failed. Content list: " + contentListPath); return(messages.ToArray()); } // Messages are numbered in the interval: [1, messageCount] // Most servers give the latest message the highest number for (var i = messageCount; i > 0; i--) { try { var msg = client.GetMessage(i); var mailMessage = msg.ToMailMessage(); messages.Add(mailMessage); } catch (Exception ex) { SnLog.WriteException(ex, "Mail processor workflow error. Content list: " + contentListPath); } } try { client.DeleteAllMessages(); } catch (Exception ex) { SnLog.WriteException(ex, "Mail processor workflow error: deleting messages failed. Content list: " + contentListPath); } } SnTrace.Workflow.Write("MailPoller workflow: " + messages.Count + " messages received. Content list: " + contentListPath); return(messages.ToArray()); }
public override ActionResult Execute(ISpecialExecutionTaskTestAction testAction) { // Host auf dem der POP3 Service laeuft String host = testAction.GetParameterAsInputValue("host", false).Value; if (string.IsNullOrEmpty(host)) { throw new ArgumentException(string.Format("Es muss ein POP3 Host angegeben sein.")); } // Port fuer den POP Service String strPort = testAction.GetParameterAsInputValue("port", false).Value; if (string.IsNullOrEmpty(strPort)) { throw new ArgumentException(string.Format("Es muss ein POP3 Port angegeben sein.")); } int port = int.Parse(strPort); // User Name String user = testAction.GetParameterAsInputValue("user", false).Value; if (string.IsNullOrEmpty(user)) { throw new ArgumentException(string.Format("Es muss ein User angegeben werden.")); } // Password String password = testAction.GetParameterAsInputValue("password", false).Value; if (string.IsNullOrEmpty(password)) { throw new ArgumentException(string.Format("Es muss ein Passwort angegeben werden.")); } pop3Client = new Pop3Client(); messages = new Dictionary <int, Message>(); int before_count = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(host, port, false); pop3Client.Authenticate(user, password); before_count = pop3Client.GetMessageCount(); if (before_count > 0) { pop3Client.DeleteAllMessages(); } } catch (InvalidLoginException e) { return(new PassedActionResult("Cannot login, maybe mailbox not ready yet. Ignoring this exception: " + e.Message)); } catch (PopServerNotFoundException e) { return(new UnknownFailedActionResult("The server could not be found:" + e.Message)); } catch (PopServerLockedException e) { return(new UnknownFailedActionResult("The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere: " + e.Message)); } catch (LoginDelayException e) { return(new UnknownFailedActionResult("Login not allowed. Server enforces delay between logins. Have you connected recently: " + e.Message)); } catch (Exception e) { return(new PassedActionResult("Error occurred retrieving mail: " + e.Message)); } finally { pop3Client.Disconnect(); } return(new PassedActionResult("Messages marked for deletion: " + Convert.ToString(before_count))); }
public void TestDeleteAllMessages() { Connect(); Assert.Throws(typeof(InvalidUseException), delegate { Client.DeleteAllMessages(); }); }
//private void DepartSent_SMS() //{ // DataTable dtDepartmentSMSSent = new DataTable(); // dtDepartmentSMSSent = DataAccessManager.GetSMSSent( Convert.ToString(Session["DeptID"]), Convert.ToInt32(Session["CampusID"])); // Session["dtDepartmentSMSSent"] = dtDepartmentSMSSent; // rgvDepartmentSent.DataSource = (DataTable)Session["dtDepartmentSMSSent"]; //} //protected void rgvDepartmentSent_SortCommand(object sender, GridSortCommandEventArgs e) //{ // this.rgvDepartmentSent.MasterTableView.AllowNaturalSort = true; // this.rgvDepartmentSent.MasterTableView.Rebind(); //} //protected void rgvDepartmentSent_PageIndexChanged(object sender, GridPageChangedEventArgs e) //{ // try // { // rgvDepartmentSent.DataSource = (DataTable)Session["dtDepartmentSMSSent"]; // } // catch (Exception ex) // { // } //} #endregion public void fetchmail(string DeptID, int CampusID) { try { DataTable dtEmailConfig = DataAccessManager.GetEmailConfigDetail(DeptID, CampusID); if (dtEmailConfig.Rows.Count > 0) { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(dtEmailConfig.Rows[0]["Pop3"].ToString(), Convert.ToInt32(dtEmailConfig.Rows[0]["PortIn"]), Convert.ToBoolean(dtEmailConfig.Rows[0]["SSL"])); pop3Client.Authenticate(dtEmailConfig.Rows[0]["DeptEmail"].ToString(), dtEmailConfig.Rows[0]["Pass"].ToString(), AuthenticationMethod.UsernameAndPassword); if (pop3Client.Connected) { int count = pop3Client.GetMessageCount(); int progressstepno; if (count == 0) { } else { progressstepno = 100 - count; this.Emails = new List <Email>(); for (int i = 1; i <= count; i++) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); Email email = new Email() { MessageNumber = i, messageId = message.Headers.MessageId, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = message.Headers.From.Address }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } email.IsAttached = false; this.Emails.Add(email); //Attachment Process List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.IsAttached = true; string FolderName = string.Empty; FolderName = Convert.ToString(Session["CampusName"]); String path = Server.MapPath("~/InboxAttachment/" + FolderName); if (!Directory.Exists(path)) { // Try to create the directory. DirectoryInfo di = Directory.CreateDirectory(path); } string ext = attachment.FileName.Split('.')[1]; // FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\") + attachment.FileName.ToString()); FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\" + FolderName + "\\") + attachment.FileName.ToString()); attachment.SaveToFile(file); Attachment att = new Attachment(); att.messageId = message.Headers.MessageId; att.FileName = attachment.FileName; attItem.Add(att); } //System.Threading.Thread.Sleep(500); } //Insert into database Inbox table DataTable dtStudentNo = new DataTable(); bool IsReadAndSave = false; foreach (var ReadItem in Emails) { string from = string.Empty, subj = string.Empty, messId = string.Empty, Ebody = string.Empty; from = Convert.ToString(ReadItem.From); subj = Convert.ToString(ReadItem.Subject); messId = Convert.ToString(ReadItem.messageId); Ebody = Convert.ToString(ReadItem.Body); if (Ebody != string.Empty && Ebody != null) { Ebody = Ebody.Replace("'", " "); } DateTime date = ReadItem.DateSent; bool IsAtta = ReadItem.IsAttached; //Student Email if (Source.SOrL(Convert.ToString(Session["StudentNo"]), Convert.ToString(Session["leadID"]))) { dtStudentNo = DyDataAccessManager.GetStudentNo(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase(dtStudentNo.Rows[0]["StudentNo"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } //Leads Email if (Source.SOrL(Convert.ToString(Session["ParamStudentNo"]), Convert.ToString(Session["ParamleadID"])) == false) { dtStudentNo = DyDataAccessManager.GetLeadsID(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead(dtStudentNo.Rows[0]["LeadsID"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } // } //Insert into database Attachment table foreach (var attachItem in attItem) { bool success; string Filname = attachItem.FileName; string MssID = attachItem.messageId; success = DataAccessManager.ReadEmailAttachmentAndSaveDatabase(MssID, Filname); } Emails.Clear(); // attItem.Clear(); pop3Client.DeleteAllMessages(); //StartNotification(count); } } pop3Client.Disconnect(); } } catch (Exception ex) { } }
void DeleteAllMail() { popClient.DeleteAllMessages(); popClient.Disconnect(); checkPopClientConnected = false; }
//focusing first on gMail account using recent: in username public void FetchRecentMessages(Account emailAccount, bool isFetchLast30days) { SqlConnection connection = null; SqlCommand cmd = null; string emailUsername = null; if (isFetchLast30days) { if (emailAccount.server.Contains("gmail.com")) { emailUsername = "******" + emailAccount.username; } else { emailUsername = emailAccount.username; } CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Fetching *last 30 days* message", EventLogEntryType.Information); } else { emailUsername = emailAccount.username; CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Fetching *new* message", EventLogEntryType.Information); } if (PosLibrary.CoreFeature.getInstance().Connect(emailAccount.name, emailAccount.server, emailAccount.port, emailAccount.use_ssl, emailUsername, emailAccount.password)) { int count = PosLibrary.CoreFeature.getInstance().getPop3Client().GetMessageCount(); for (int i = 1; i <= count; i++) { //Regards to : http://hpop.sourceforge.net/exampleSpecificParts.php OpenPop.Mime.Message message = PosLibrary.CoreFeature.getInstance().getPop3Client().GetMessage(i); MessagePart messagePart = message.FindFirstPlainTextVersion(); if (messagePart == null) { messagePart = message.FindFirstHtmlVersion(); } string messageBody = null; if (messagePart != null) { messageBody = messagePart.GetBodyAsText(); } messageBody = Regex.Replace(messageBody, "<.*?>", string.Empty); //save to appropriate inbox connection = CoreFeature.getInstance().getDataConnection(); string sql = "insert into inbox(account_name,sender,subject,body,date, sender_ip,[to]) values (@account_name,@sender,@subject,@body,@date,@sender_ip,@to)"; cmd = new SqlCommand(sql, connection); cmd.Parameters.Add(new SqlParameter("account_name", emailAccount.name.ToString())); cmd.Parameters.Add(new SqlParameter("sender", message.Headers.From.ToString())); cmd.Parameters.Add(new SqlParameter("subject", message.Headers.Subject.ToString())); cmd.Parameters.Add(new SqlParameter("body", messageBody.ToString())); cmd.Parameters.Add(new SqlParameter("date", message.Headers.Date.ToString())); cmd.Parameters.Add(new SqlParameter("sender_ip", message.Headers.Received[message.Headers.Received.Count - 1].Raw.ToString())); cmd.Parameters.Add(new SqlParameter("to", message.Headers.To[message.Headers.To.Count - 1].ToString())); try { int rowAffected = cmd.ExecuteNonQuery(); CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Inserting email inbox from " + message.Headers.From + ", subject=" + message.Headers.Subject + ", body=" + messageBody, EventLogEntryType.Information); } catch (Exception ex) { CoreFeature.getInstance().LogActivity(LogLevel.Debug, "[Internal Application Error] FetchRecentMessages " + ex.Message, EventLogEntryType.Information); } cmd.Dispose(); connection.Close(); } // delete if there any message received from the server if (count > 0 && !emailAccount.server.Contains("gmail.com")) { pop3Client.DeleteAllMessages(); pop3Client.Disconnect(); } } else { CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Unable to login to your email", EventLogEntryType.Information); } }
public void TestDeleteAllMessagesDoesNotThrow() { Authenticate("+OK 0"); // First message count is asked for, we return 0 Assert.DoesNotThrow(delegate { Client.DeleteAllMessages(); }); }