/// <summary> /// Create a new folder within the outlook email server /// </summary> public void createMailBox() { Imap4Client client = new Imap4Client(); try { //Connect and Authenticate client.ConnectSsl(Constant.OutlookImapHost, 993); client.Login(Constant.OutlookUserName, Constant.GenericPassword); //create mailbox client.CreateMailbox("Mailbox-A"); Console.WriteLine("Created Mailbox"); } catch (Imap4Exception) { throw new Imap4Exception(); } catch (Exception) { throw new Exception(); } finally { client.Disconnect(); } }
public void GivenAnEmailVerifyAllInlineAttachmentsAreDownloaded() { var imap = new Imap4Client(); string emailFolder = "inlineImageUT"; string directoryPath = "C:\\Users\\maddirsh\\Desktop\\testFolder\\"; List <Message> inlineAttachmentList = new List <Message>(); //Authentication imap.ConnectSsl("imap-mail.outlook.com", 993); imap.Login("*****@*****.**", "secret"); var inbox = imap.SelectMailbox(emailFolder); var unread = inbox.Search("ALL"); for (var i = 0; i < unread.Length; i++) { var unreadMessage = inbox.Fetch.MessageObject(unread[i]); inlineAttachmentList.Add(unreadMessage); } for (int i = 0; i < inlineAttachmentList.Count; i++) { foreach (MimePart embedded in inlineAttachmentList[i].EmbeddedObjects) { var fileName = embedded.ContentName; var binary = embedded.BinaryContent; //downloads one file from the email from the MANY inline attachments that can exists File.WriteAllBytes(string.Concat(directoryPath, fileName), binary); } } Assert.AreEqual(1, Directory.GetFiles(directoryPath).Length); }
private void _bRetrieveSpecificMessage_Click(object sender, EventArgs e) { // We create Imap client Imap4Client imap = new Imap4Client(); try { // We connect to the imap4 server imap.Connect(_tbImap4Server.Text); this.AddLogEntry(string.Format("Connection to {0} successfully", _tbImap4Server.Text)); // Login to mail box imap.Login(_tbUserName.Text, _tbPassword.Text); this.AddLogEntry(string.Format("Login to {0} successfully", _tbImap4Server.Text)); Mailbox inbox = imap.SelectMailbox("inbox"); if (inbox.MessageCount > 0) { for (int i = 1; i < inbox.MessageCount + 1; i++) { ActiveUp.Net.Mail.Message message = inbox.Fetch.MessageObject(i); ListViewItem lvi = new ListViewItem(); lvi.Text = i.ToString("0000"); lvi.SubItems.AddRange(new string[] { message.Subject }); lvi.Tag = message; _lvMessages.Items.Add(lvi); this.AddLogEntry(string.Format("{3} Subject: {0} From :{1} Message Body {2}" , message.Subject, message.From.Email, message.BodyText, i.ToString("0000"))); } } else { this.AddLogEntry("There is no message in the imap4 account"); } } catch (Imap4Exception iex) { this.AddLogEntry(string.Format("Imap4 Error: {0}", iex.Message)); } catch (Exception ex) { this.AddLogEntry(string.Format("Failed: {0}", ex.Message)); } finally { if (imap.IsConnected) { imap.Disconnect(); } } }
public void download_imap_test() { try { var _selectedMailBox = "INBOX"; using (var _clientImap4 = new Imap4Client()) { _clientImap4.ConnectSsl(_imapServerAddress, _imapPort); //_clientImap4.Connect(_mailServer.address, _mailServer.port); _clientImap4.Login(_imapLogin, _imapPassword); // Efetua login e carrega as MailBox da conta. //_clientImap4.LoginFast(_imapLogin, _imapPassword); // Efetua login e não carrega as MailBox da conta. var _mailBox = _clientImap4.SelectMailbox(_selectedMailBox); foreach (var messageId in _mailBox.Search("ALL").AsEnumerable()) { var message = _mailBox.Fetch.Message(messageId); var _imapMessage = Parser.ParseMessage(message); } _clientImap4.Disconnect(); } Assert.IsTrue(true); } catch (Exception e) { Assert.Fail("Don't work.", e); } }
/// <summary> /// Gets the imap client. /// </summary> /// <returns>Imap 4 client.</returns> public Imap4Client GetImapClient() { string imapServer = _configurationPropertiesProvider.GetProperty(SettingKeyNames.ImapServer); int imapPort = _configurationPropertiesProvider.GetPropertyInt(SettingKeyNames.ImapPort); // Retrieves the Current User Context UserInformationDto info = _userInformationDtoFactory.CreateUserInformationDto(); // Retrieves the corresponding Staff record for the current user Staff staff = _sessionProvider.GetSession().QueryOver <Staff>().Where(s => s.Key == info.StaffKey).SingleOrDefault(); //string username = "******"; //string password = "******"; string username = null; string password = null; if (staff.DirectAddressCredential.DirectAddress != null) { username = staff.DirectAddressCredential.DirectAddress.Address; password = staff.DirectAddressCredential.DirectAddressPassword; } if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) { throw new ApplicationException("Username/password are not provided to access IMAP mail server."); } var imap4Client = new Imap4Client(); imap4Client.Connect(imapServer, imapPort, username, password); return(imap4Client); }
public void VerifyThatReadMessagesCannotBeMoved() { Imap4Client client = new Imap4Client(); client.ConnectSsl("imap-mail.outlook.com", 993); client.Login("*****@*****.**", "secret"); Mailbox targetMailbox = client.SelectMailbox("inboxA"); Mailbox destinationMailbox = client.SelectMailbox("inboxB"); int[] targetMailInts = targetMailbox.Search("ALL"); List <Message> targetList = new List <Message>(); for (int i = 0; i < targetMailInts.Length; i++) { Message targetMessage = targetMailbox.Fetch.MessageObject(targetMailInts[i]); targetList.Add(targetMessage); } //Now all the messages are marked as read int[] targetReadMailInts = targetMailbox.Search("UNSEEN"); for (int i = 0; i < targetReadMailInts.Length; i++) { targetMailbox.MoveMessage(i, "inboxB"); } Assert.AreEqual(0, destinationMailbox.MessageCount); }
public void delete_inbox_undeleted_messages_gmail() { var _selectedMailBox = "INBOX"; using (var _clientImap4 = new Imap4Client()) { _clientImap4.ConnectSsl(_imapServerAddress, _imapPort); _clientImap4.LoginFast(_imapLogin, _imapPassword); // To see the names os all MailBox and found Trash _clientImap4.LoadMailboxes(); var allMailBox = _clientImap4.AllMailboxes; var mails = _clientImap4.SelectMailbox(_selectedMailBox); var ids = mails.Search("UNDELETED"); foreach (var id in ids) { mails.DeleteMessage(id, expunge: false); mails.MoveMessage(id, "[Gmail]/Lixeira"); } var mailsUndeleted = _clientImap4.SelectMailbox(_selectedMailBox); Assert.AreEqual(0, mailsUndeleted.Search("UNDELETED")); _clientImap4.Disconnect(); } }
/// <summary> /// Tries to connect to the e-mail indox using the standard IMAP v4 interface. /// </summary> /// <param name="errorMessage">The error Message.</param> /// <returns>True if connected ok.</returns> private bool ConnectToMailboxUsingStdImap4(out string errorMessage) { errorMessage = string.Empty; string selectedMailBox = StandardMailBoxName; using (var clientImap4 = new Imap4Client()) { try { clientImap4.ConnectSsl(ImapServerAddress, ImapPort); clientImap4.Login(_emailAddress, _password); Mailbox mailbox = clientImap4.SelectMailbox(selectedMailBox); if (mailbox.Permission != MailboxPermission.ReadWrite) { errorMessage = "Mailbox permission is " + mailbox.Permission; } } catch (Exception e) { errorMessage = e.Message + " : " + e.InnerException; } } return(string.IsNullOrEmpty(errorMessage)); }
public Imap4Client ImapLogin(String username, String password) { this.ImapClient = new Imap4Client(); this.ImapConnect(true); this.ImapAttemptLogin(username, CryptoHelper.DecryptDefaultKey(password)); return(this.ImapClient); }
public void GivenAnEmailDownloadAllAttachments() { //Authenticate Imap4Client client = new Imap4Client(); client.ConnectSsl("imap-mail.outlook.com", 993); client.Login("*****@*****.**", "secret"); //File IO string directoryPath = "C:\\Users\\suman\\Desktop\\testFolder"; Mailbox attachmentMailbox = client.SelectMailbox("attachment"); int[] attachmentMessages = attachmentMailbox.Search("UNSEEN"); List <Message> unreadAttachments = new List <Message>(); for (int i = 0; i < attachmentMessages.Length; i++) { Message unreadMessage = attachmentMailbox.Fetch.MessageObject(attachmentMessages[i]); unreadAttachments.Add(unreadMessage); } foreach (var msg in unreadAttachments) { if (msg.Attachments.Count > 0) { msg.Attachments.StoreToFolder(directoryPath); } } Assert.AreEqual(2, Directory.GetFiles(directoryPath).Length); }
public override void Aggregate() { Imap4Client imap = null; try { imap = (Imap4Client)Connect(); UpdateTimeCheckedIfNeeded(); // Were we already canceled? cancelToken.ThrowIfCancellationRequested(); ProcessMessages(imap); } finally { try { if (imap != null && imap.IsConnected) { imap.Disconnect(); } } catch (Exception ex) { log.Warn("Aggregate() Imap4->Disconnect: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n", Account.Server, Account.Port, Account.Account, ex.Message); } } }
private void AuthenticateImapPlain(Imap4Client imap) { switch (Account.IncomingEncryptionType) { case EncryptionType.StartTLS: _log.Info("IMAP StartTLS connecting to {0}", Account.EMail); imap.ConnectTLS(Account.Server, Account.Port); break; case EncryptionType.SSL: _log.Info("IMAP SSL connecting to {0}", Account.EMail); imap.ConnectSsl(Account.Server, Account.Port); break; case EncryptionType.None: _log.Info("IMAP connecting to {0}", Account.EMail); imap.Connect(Account.Server, Account.Port); break; } _log.Info("IMAP connecting OK {0}", Account.EMail); _log.Info("IMAP logging in to {0}", Account.EMail); if (Account.AuthenticationTypeIn == SaslMechanism.Login) { imap.Login(Account.Account, Account.Password, ""); } else { imap.Authenticate(Account.Account, Account.Password, Account.AuthenticationTypeIn); } _log.Info("IMAP logged in to {0}", Account.EMail); }
public static void AuthenticateImap(this Imap4Client imap, MailBox account, ILogger log = null) { if (log == null) { log = new NullLogger(); } if (account.RefreshToken != null) { var service_type = (AuthorizationServiceType)account.ServiceType; switch (service_type) { case AuthorizationServiceType.Google: imap.AuthenticateImapGoogleOAuth2(account, log); return; } } imap.Authorize(new MailServerSettings { AccountName = account.Account, AccountPass = account.Password, AuthenticationType = account.AuthenticationTypeIn, EncryptionType = account.IncomingEncryptionType, Port = account.Port, Url = account.Server }, account.AuthorizeTimeoutInMilliseconds, log); log.Info("IMAP logged in to {0}", account.EMail); }
/// <summary> /// Method to pull images that could have been copied & pasted, instead of attaching /// </summary> public void downlodInlineAttachments() { var imap = new Imap4Client(); //Authenticate imap.ConnectSsl(Constant.GoogleImapHost, Constant.ImapPort); imap.Login(Constant.GoogleUserName, Constant.GenericPassword); var inbox = imap.SelectMailbox("Inbox"); var unread = inbox.Search("unseen"); Console.WriteLine("Unread Messgaes: " + unread.Length); if (unread.Length > 0) { for (int i = 0; i < unread.Length; i++) { var unreadMessage = inbox.Fetch.MessageObject(unread[i]); foreach (MimePart embedded in unreadMessage.EmbeddedObjects) { var filename = embedded.ContentName; var binary = embedded.BinaryContent; File.WriteAllBytes(String.Concat(Constant.InlineAttachmentsDirectory, filename), binary); Console.WriteLine("Downloaded: " + filename); } } } else { Console.WriteLine("Unread Messages Not Found"); } }
static void Main(string[] args) { System.Console.WriteLine("Start work"); string sHostPop = "pop.googlemail.com"; string sHostImap = "imap.googlemail.com"; int nPort = 995; string sUserName = "******"; string sPasword = "theSimpsons"; try { string sEml = @"E:\ut8_encripted_teamlab.eml"; ActiveUp.Net.Mail.Message m = ActiveUp.Net.Mail.Parser.ParseMessageFromFile(sEml); var header = ActiveUp.Net.Mail.Parser.ParseHeader(sEml); Pop3Client pop = new Pop3Client(); // Connect to the pop3 client pop.ConnectSsl(sHostPop, nPort, "recent:" + sUserName, sPasword); if (pop.MessageCount > 0) { ActiveUp.Net.Mail.Message message = pop.RetrieveMessageObject(4); string sHtml = message.BodyHtml.Text; } else { System.Console.WriteLine("No letters!"); } pop.Disconnect(); Imap4Client imap = new Imap4Client(); imap.ConnectSsl(sHostImap, 993); imap.Login(sUserName, sPasword, ""); Mailbox inbox = imap.SelectMailbox("inbox"); if (inbox.MessageCount > 0) { ActiveUp.Net.Mail.Message message = inbox.Fetch.MessageObject(6); string sHtml = message.BodyHtml.Text; } imap.Disconnect(); } catch (Exception ex) { System.Console.Write("\r\n" + ex); } System.Console.WriteLine("Stop work"); System.Console.ReadKey(); }
public void EnsureNonUnreadMessagesAreNotAddedToList() { //get imap obj Imap4Client client = new Imap4Client(); //authenicate client.ConnectSsl("imap-mail.outlook.com", 993); client.Login("*****@*****.**", "secret"); Mailbox inbox = client.SelectMailbox("Conversations"); int[] unreadMessages = inbox.Search("UNSEEN"); int numberOfUnreadMessages = unreadMessages.Length; List <Message> unreadMessageCollection = new List <Message>(); if (numberOfUnreadMessages > 0) { for (int i = 0; i < numberOfUnreadMessages; i++) { Message msg = inbox.Fetch.MessageObject(unreadMessages[i]); unreadMessageCollection.Add(msg); } } Assert.AreEqual(0, unreadMessageCollection.Count); }
public void EnsureUnreadMessagesCanBeMoved() { var _selectedMailBox = "Inbox"; var _targetMailBox = "Processed"; Mailbox finalMailbox; using (var client = new Imap4Client()) { client.ConnectSsl("imap.gmail.com", 993); client.Login("*****@*****.**", "secret"); Mailbox mails = client.SelectMailbox(_selectedMailBox); var mailMessages = mails.Search("ALL"); foreach (var x in mailMessages) { mails.MoveMessage(x, _targetMailBox); } finalMailbox = client.SelectMailbox("Processed"); client.Disconnect(); } Assert.AreEqual(15, finalMailbox.MessageCount); }
public Fetcher(String username, String password) { this.Receiver = new Connector().ImapLogin(username, password); this.AccountMailboxesBySpecialProperty = new NameValueCollection(); this.LoadMailboxesAndSpecialProperties(this.Receiver.Command("LIST \"\" \"*\"")); this.CurrentOpenedMailbox = null; }
/// <summary> /// IncomingConnect the imap client. /// </summary> /// <param name="accountInfo">The information account</param> public Boolean Connect(MailUser accountInfo) { Boolean bRetVal = false; ErrorMessage = ""; if (this._imap4Client == null || !this._imap4Client.IsConnected) { if (accountInfo != null) // && accountInfo.IncomingProtocol == IncomingProtocols.POP3) { this._imap4Client = new Imap4Client(); this._imap4Client.Disconnected += new DisconnectedEventHandler(On_ImapClientDisconnected); this._imap4Client.Connected += new ConnectedEventHandler(On_ImapClientConnected); int port = accountInfo.PortIncomingServer; bool ssl = accountInfo.IsIncomeSecureConnection; string serverName = accountInfo.IncomingServer; string user = accountInfo.LoginId; string password = accountInfo.Password; bool useInPort = accountInfo.PortIncomingChecked; try { if (ssl) { if (useInPort) { this._imap4Client.ConnectSsl(serverName, port); } else { this._imap4Client.ConnectSsl(serverName); } } else { if (useInPort) { this._imap4Client.Connect(serverName, port); } else { this._imap4Client.Connect(serverName); } } this._imap4Client.Login(user, password); bRetVal = true; } catch (Exception ex) { ErrorMessage = ex.Message; StatusConnected = false; bRetVal = false; } } } return(bRetVal); } // Boolean Connect(...
/// <summary> /// Start the asynchronous email message operation. /// </summary> /// <param name="client">The current imap4 client.</param> /// <param name="callback">The asynchronous call back method.</param> /// <param name="state">The state object value.</param> public AsyncGetMessageSize(Imap4Client client, AsyncCallback callback, object state) : base(callback, state) { _client = client; ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncGetMessageSizeThread2)); Thread.Sleep(20); }
public void Dispose() { if (this.fclient != null) { this.fclient.Disconnect(); this.fclient = null; } }
/// <summary> /// Start the asynchronous email message operation. /// </summary> /// <param name="client">The current imap4 client.</param> /// <param name="callback">The asynchronous call back method.</param> /// <param name="state">The state object value.</param> public AsyncGetAccountFolders(Imap4Client client, AsyncCallback callback, object state) : base(callback, state) { _client = client; ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncGetAccountFoldersThread1)); Thread.Sleep(20); }
public void AuthenticateWithOutlook() { Imap4Client client = new Imap4Client(); client.ConnectSsl("imap-mail.outlook.com", 993); client.Login("*****@*****.**", "secret"); Assert.AreEqual(true, client.IsConnected); }
public Sync(string rallyUserName, string rallyPassword, string outlookUserName, string outlookPassword) { _rallyApi = new RallyRestApi(); _imap4Client = new Imap4Client(); this.OutlookUserName = outlookUserName; this.OutlookPassword = outlookPassword; this.RallyUserName = rallyUserName; this.RallyPassword = rallyPassword; }
// gets mailboxes, messages from wich we should get public static IEnumerable <ImapMailboxInfo> GetImapMailboxes(this Imap4Client client, string server, Dictionary <string, Dictionary <string, MailboxInfo> > special_domain_folders, string[] skip_imap_flags, Dictionary <string, int> imap_flags) { // get all mailboxes var response = client.GetImapMailboxes(); var mailboxes = ParseImapMailboxes(response, server, special_domain_folders, skip_imap_flags, imap_flags); return(mailboxes); }
static void Main(string[] args) { using (Imap4Client imap = new Imap4Client()) { string Body; int ReferenceOrdinalNumber = 96600; string ReferenceDate = DateTime.Now.ToString("dd-MMM-yyy hh:mm:ss" + " +0100", CultureInfo.CreateSpecificCulture("en-US")); string DeliveryLink; imap.Connect("mail.moj-eracun.hr"); imap.Login("*****@*****.**", "m0j.d05tava"); Mailbox inbox = imap.SelectMailbox("Inbox"); int OrdinalNumber = inbox.MessageCount; string Date = inbox.Fetch.InternalDate(OrdinalNumber); string MerPattern1 = ".*?"; string MerPattern2 = "((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s\"]*))"; Regex MerLink = new Regex(MerPattern1 + MerPattern2, RegexOptions.IgnoreCase | RegexOptions.Singleline); string MerCheck1 = "(Return)"; string MerCheck2 = "(-)"; string MerCheck3 = "(Path)"; string MerCheck4 = "(:)"; string MerCheck5 = "( )"; string MerCheck6 = "(dostava@moj-eracun\\.hr)"; Regex MerChecker = new Regex(MerCheck1 + MerCheck2 + MerCheck3 + MerCheck4 + MerCheck5 + MerCheck6, RegexOptions.IgnoreCase | RegexOptions.Singleline); while (Date != ReferenceDate) { OrdinalNumber = inbox.MessageCount; Date = inbox.Fetch.InternalDate(OrdinalNumber); for (OrdinalNumber = inbox.MessageCount; Date != ReferenceDate && OrdinalNumber > ReferenceOrdinalNumber; OrdinalNumber--) { Body = inbox.Fetch.MessageString(OrdinalNumber); try { Match MerLinkMatch = MerLink.Match(Body); Match MerCheckerMatch = MerChecker.Match(Body); if (MerLinkMatch.Success && MerCheckerMatch.Success) { DeliveryLink = MerLinkMatch.Groups[1].ToString(); ParseJson(DeliveryLink); } } //TO DO: Add Exceptions catch { throw; } } ReferenceOrdinalNumber = OrdinalNumber; } imap.Disconnect(); } }
/// <summary> /// Start the asynchronous email message operation. /// </summary> /// <param name="folderName">The folder to view details on.</param> /// <param name="client">The current imap4 client.</param> /// <param name="callback">The asynchronous call back method.</param> /// <param name="state">The state object value.</param> public AsyncGetAccountFolders(string folderName, Imap4Client client, AsyncCallback callback, object state) : base(callback, state) { _client = client; _folderName = folderName; ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncGetAccountFolderDetailsThread3)); Thread.Sleep(20); }
/// <summary> /// Start the asynchronous email message operation. /// </summary> /// <param name="messageNumber">The email message number.</param> /// <param name="client">The current imap4 client.</param> /// <param name="callback">The asynchronous call back method.</param> /// <param name="state">The state object value.</param> public AsyncGetEmailBody(long messageNumber, Imap4Client client, AsyncCallback callback, object state) : base(callback, state) { _client = client; _messageNumber = messageNumber; ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncGetEmailBodyThread1)); Thread.Sleep(20); }
/// <summary> /// Start the asynchronous email message operation. /// </summary> /// <param name="subscribed">The subscribed folder list.</param> /// <param name="client">The current imap4 client.</param> /// <param name="callback">The asynchronous call back method.</param> /// <param name="state">The state object value.</param> public AsyncGetAccountFolders(bool subscribed, Imap4Client client, AsyncCallback callback, object state) : base(callback, state) { _client = client; _subscribed = subscribed; ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncGetAccountSubFoldersThread2)); Thread.Sleep(20); }
private void _bSearch_Click(object sender, EventArgs e) { // We create Imap client Imap4Client imap = new Imap4Client(); try { // We connect to the imap4 server imap.Connect(_tbImap4Server.Text); this.AddLogEntry(string.Format("Connection to {0} successfully", _tbImap4Server.Text)); // Login to mail box imap.Login(_tbUserName.Text, _tbPassword.Text); this.AddLogEntry(string.Format("Login to {0} successfully", _tbImap4Server.Text)); Mailbox inbox = imap.SelectMailbox("inbox"); // We gets the message matching the search criteria. MessageCollection messages = inbox.SearchParse("searchcritiria"); if (messages.Count > 0) { for (int n = 0; n < messages.Count; n++) { this.AddLogEntry(string.Format("Message ({0}) : {1}", n.ToString(), messages[n].Subject)); } } else { this.AddLogEntry("There is no message using this search pattern"); } } catch (Imap4Exception iex) { this.AddLogEntry(string.Format("Imap4 Error: {0}", iex.Message)); } catch (Exception ex) { this.AddLogEntry(string.Format("Failed: {0}", ex.Message)); } finally { if (imap.IsConnected) { imap.Disconnect(); } } }