} // End Sub TestPop3 public static void TestImap(string username, string password) { using (MailKit.MailStore client = new MailKit.Net.Imap.ImapClient()) { // For demo-purposes, accept all SSL certificates client.ServerCertificateValidationCallback = (s, c, h, e) => true; // Non-Encrypted: 143 // SSL/TLS: 993 client.Connect(RedmineMailService.Trash.UserData.IMAP, 993, true); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(username, password); // The Inbox folder is always available on all IMAP servers... MailKit.IMailFolder inbox = client.Inbox; inbox.Open(MailKit.FolderAccess.ReadOnly); System.Console.WriteLine("Total messages: {0}", inbox.Count); System.Console.WriteLine("Recent messages: {0}", inbox.Recent); for (int i = 0; i < inbox.Count; i++) { MimeKit.MimeMessage message = inbox.GetMessage(i); System.Console.WriteLine("Subject: {0}", message.Subject); } // Next i client.Disconnect(true); } // End Using client } // End Sub TestImap
// Typically, SMTP uses port 25. However, an alternative SMTP "submission" port has been reserved on port 587. // For Exchange 2007 and 2010, installation will create a "Default" module listening on port 25 as well as a // "Client" module listening on port 587. // https://stackoverflow.com/questions/38747822/accessing-exchange-shared-folders-using-mailkit public static void ExchangeShared() { string userName = "******"; // The email address that has permissions to the shared mailbox string sharedMailboxAlias = "aliasName"; // This is the alias name as setup in Exchange string password = ""; using (MailKit.MailStore client = new MailKit.Net.Imap.ImapClient()) { client.Connect("outlook.office365.com", 993, true); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(userName + @"\" + sharedMailboxAlias, password); MailKit.IMailFolder inbox = client.Inbox; inbox.Open(MailKit.FolderAccess.ReadOnly); System.Console.WriteLine("Total messages: {0}", inbox.Count); System.Console.WriteLine("Recent messages: {0}", inbox.Recent); client.Disconnect(true); } }
static IMailFolder get_mail() { IMailFolder inbox_data = null; try { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect(Constants.mail_server, Constants.port, Constants.use_SSL); client.Authenticate(uname, password); var inbox = client.Inbox; inbox.Open(FolderAccess.ReadWrite); inbox_data = inbox; } catch (Exception e) { MessageBox.Show(e.Message); } return(inbox_data); }
public List <Email> GetArchiveEmails() { int errorLevel = 0; Log.Append(String.Format("Getting new emails from archive...")); List <Email> newEmails = new List <Email>(); int emailSyncCount = 0; using (var client = new MailKit.Net.Imap.ImapClient()) { try { //For demo-purposes, accept all SSL certificates client.ServerCertificateValidationCallback = (s, c, h, e) => true; #region Connect using receiving parameters try { client.Connect(ReceivingProtocol, Convert.ToInt32(ReceivingPort), true); } catch { Log.Append(String.Format("ERROR: Failed to connect to {0} using {1}:{2}", Email, ReceivingProtocol, ReceivingPort)); return(new List <Email>()); } #endregion // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); #region Login using credentials try { client.Authenticate(Email, Password); } catch { Log.Append(String.Format("ERROR: Failed to login using user credentials for '{0}'", Email)); return(new List <Email>()); } #endregion #region Inbox // The Inbox folder is always available on all IMAP servers... var inbox = client.Inbox; inbox.Open(FolderAccess.ReadWrite); var query = SearchQuery.DeliveredAfter(LastUpdateTime); foreach (var uid in inbox.Search(query)) { try { if (Readiness.CheckTerminationStatus(true)) { break; } string workingID = Global.GetAttachmentID(); try { MimeMessage message = inbox.GetMessage(uid); var date = message.Date.ToString(); Email email = new Email() { UID = uid.ToString(), ID = workingID, MailDate = Convert.ToDateTime(date), From = message.From.ToString(), To = Email, Subject = message.Subject, }; if (email.Subject.Trim().Length != 6 || !email.Subject.Trim().All(char.IsDigit)) { Random r = new Random(); email.CreateEmailMsgFile(message, ArchivesChecker._errorPath + DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Year + "_" + r.Next(10000, 99999), true); } else { emailSyncCount++; email.CreateEmailMsgFile(message, ArchivesChecker.CreateArchiveDirectory(email.Subject) + @"\" + email.Subject); newEmails.Add(email); } inbox.AddFlags(new[] { uid }, MessageFlags.Deleted, true); inbox.Expunge(); } catch { Log.Append(String.Format("ERROR: Email can't be processed with ID={0}", workingID)); } } catch (Exception ex) { errorLevel++; Log.Append(String.Format("ERROR [Inbox]: {0}", ex)); // Undetermined error from automated system } } #endregion #region Subfolders var personal = client.GetFolder(client.PersonalNamespaces[0]); foreach (var folder in personal.GetSubfolders(false)) { if (folder.Name.ToLower() != "sent") { if (Readiness.CheckTerminationStatus(true)) { break; } try { folder.Open(FolderAccess.ReadOnly); query = SearchQuery.DeliveredAfter(LastUpdateTime); foreach (var uid in folder.Search(query)) { if (Readiness.CheckTerminationStatus()) { return(newEmails); } MimeMessage message = folder.GetMessage(uid); var date = message.Date.ToString(); Email email = new Email { UID = uid.ToString(), ID = Global.GetAttachmentID(), MailDate = Convert.ToDateTime(date), From = message.From.ToString(), To = Email, Subject = message.Subject, }; if (email.Subject.Trim().Length != 6 || !email.Subject.Trim().All(char.IsDigit)) { Random r = new Random(); email.CreateEmailMsgFile(message, ArchivesChecker._errorPath + DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Year + "_" + r.Next(10000, 99999)); } else { emailSyncCount++; email.CreateEmailMsgFile(message, ArchivesChecker.CreateArchiveDirectory(email.Subject) + @"\" + email.Subject); newEmails.Add(email); } inbox.AddFlags(new[] { uid }, MessageFlags.Deleted, true); inbox.Expunge(); } } catch { Log.Append(String.Format(" Sub folder IMAP retrieval error for folder=\"{0}\"", folder.Name)); } } } #endregion client.Disconnect(true); } catch (Exception ex) { errorLevel++; Log.Append(String.Format("ERROR [Overall]: {0}", ex)); } } Log.Append(String.Format("{0} emails archived.", emailSyncCount)); if (errorLevel <= 0) { Log.Append("Complete!"); } return(newEmails); }
public List <Email> GetEmails() { if (Global.isSyncing) { Log.Append("Error: Existing sync in progress"); return(new List <Email>()); } Global.isSyncing = true; int errorLevel = 0; Log.Append(String.Format("Getting new emails (since {1}) from '{0}'...", Email, LastUpdateTime.ToShortDateString())); // Generate the list of uids from current emails stored for current user (used to check if email already exists) List <string> ExistingUID = Global.EmailList.Where(x => x.To == Email && x.MailDate >= LastUpdateTime.AddDays(-5)).Select(y => y.UID).ToList(); List <Email> newEmails = new List <Email>(); int emailSyncCount = 0; using (var client = new MailKit.Net.Imap.ImapClient()) { try { //For demo-purposes, accept all SSL certificates client.ServerCertificateValidationCallback = (s, c, h, e) => true; #region Connect using receiving parameters try { client.Connect(ReceivingProtocol, Convert.ToInt32(ReceivingPort), true); } catch { Log.Append(String.Format("ERROR: Failed to connect to {0} using {1}:{2}", Email, ReceivingProtocol, ReceivingPort)); return(new List <Email>()); } #endregion // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); #region Login using credentials try { client.Authenticate(Email, Password); } catch { Log.Append(String.Format("ERROR: Failed to login using user credentials for '{0}'", Email)); return(new List <Email>()); } #endregion #region Inbox // The Inbox folder is always available on all IMAP servers... var inbox = client.Inbox; inbox.Open(FolderAccess.ReadOnly); Log.Append(" Checking 'Inbox'"); var query = SearchQuery.DeliveredAfter(LastUpdateTime); foreach (var uid in inbox.Search(query)) { try { if (Readiness.CheckTerminationStatus(true)) { break; } string workingID = Global.GetAttachmentID(); try { // Verify that this email does not exist. if (!ExistingUID.Contains(uid.ToString())) { MimeMessage message = inbox.GetMessage(uid); var date = message.Date.ToString(); Email email = new Email() { UID = uid.ToString(), ID = workingID, MailDate = Convert.ToDateTime(date), From = message.From.ToString(), To = Email, Subject = message.Subject, }; emailSyncCount++; email.CreateEmailMsgFile(message); email.RetrieveMsg(); Global.AppendEmail(email); newEmails.Add(email); } } catch { Log.Append(String.Format("ERROR: Email can't be processed with ID={0}", workingID)); } } catch (Exception ex) { errorLevel++; Log.Append(String.Format("ERROR [Inbox]: {0}", ex)); // Undetermined error from automated system } } #endregion #region Subfolders var personal = client.GetFolder(client.PersonalNamespaces[0]); foreach (var folder in personal.GetSubfolders(false)) { Log.Append(String.Format(" Checking folder '{0}'", folder.Name)); if (folder.Name.ToLower() != "sent") { if (Readiness.CheckTerminationStatus(true)) { break; } try { folder.Open(FolderAccess.ReadOnly); query = SearchQuery.DeliveredAfter(LastUpdateTime); foreach (var uid in folder.Search(query)) { if (Readiness.CheckTerminationStatus()) { return(newEmails); } // Verify that this email does not exist. if (!ExistingUID.Contains(uid.ToString())) { MimeMessage message = folder.GetMessage(uid); var date = message.Date.ToString(); Email email = new Email() { UID = uid.ToString(), ID = Global.GetAttachmentID(), MailDate = Convert.ToDateTime(date), From = message.From.ToString(), To = Email, Subject = message.Subject, }; emailSyncCount++; email.CreateEmailMsgFile(message); email.RetrieveMsg(); Global.AppendEmail(email); newEmails.Add(email); } } } catch { Log.Append(String.Format(" Sub folder IMAP retrieval error for folder=\"{0}\"", folder.Name)); } } } #endregion client.Disconnect(true); } catch (Exception ex) { errorLevel++; Log.Append(String.Format("ERROR [Overall]: {0}", ex)); } } Log.Append(String.Format("{0} emails synced.", emailSyncCount)); if (errorLevel <= 0) { LastUpdateTime = DateTime.Now; Log.Append("Complete!"); } GetEmailCount(); Global.SaveSettings(); Global.ExportEmailFile(); Global.isSyncing = false; // Sort by date Global.EmailList = Global.EmailList.OrderByDescending(x => x.MailDate).ToList(); return(newEmails); }
public void PickupEmails() { // Reference to a directory string directory = "C:\\DATA\\home\\AnnytabDoxStandards\\Open\\"; // Create and use an imap client using (var client = new MailKit.Net.Imap.ImapClient()) { // Add credentials client.Connect(this.options.Host, 993, true); client.Authenticate(this.options.Pickup, this.options.Password); // Get inbox folder MailKit.IMailFolder inbox = client.Inbox; inbox.Open(MailKit.FolderAccess.ReadWrite); // Write information about the inbox Console.WriteLine("Total messages: {0}", inbox.Count); Console.WriteLine("Recent messages: {0}", inbox.Recent); // Create a query MailKit.Search.SearchQuery query = MailKit.Search.SearchQuery.NotDeleted.And(MailKit.Search.SearchQuery.NotSeen); // Loop messages foreach(MailKit.UniqueId uid in inbox.Search(query)) { // Get the message var message = inbox.GetMessage(uid); // Print subject Console.WriteLine("Subject: {0}", message.Subject); // Get attachments foreach (var attachment in message.Attachments) { // Get information about the attachment var file_name = attachment.ContentDisposition?.FileName; file_name = string.IsNullOrEmpty(file_name) ? Guid.NewGuid().ToString() + ".noname" : Guid.NewGuid().ToString() + Tools.GetExtensions(file_name); var content_type = attachment.ContentType; // Only accept files that ends with dox.zip if(file_name.EndsWith(".dox.zip") == true) { // Save the attachment to disk using (FileStream stream = new FileStream(directory + file_name, FileMode.Create)) { if (attachment is MimeKit.MessagePart) { var part = (MimeKit.MessagePart)attachment; part.Message.WriteTo(stream); } else { var part = (MimeKit.MimePart)attachment; part.Content.DecodeTo(stream); } } } } // Flag email as seen inbox.AddFlags(uid, MailKit.MessageFlags.Seen, true); //inbox.AddFlags(uid, MailKit.MessageFlags.Deleted, true); } // Disconnect client client.Disconnect(true); } } // End of the PickupEmails method