static void Main(string[] args) { var vrt = "sercret hehe"; var split = vrt.Split(':'); var source = new ImapClient(split[2], split[0], split[1]); var destination = new ImapClient(split[6], split[4], split[5], AuthMethods.Login, int.Parse(split[7]), true, true); Console.WriteLine("Begining"); var sourceFolder = source.ListMailboxes(string.Empty, "*"); var destinationFolder = destination.ListMailboxes(string.Empty, "*"); foreach (var mailbox in sourceFolder) { if (!mailbox.Name.Contains("Gmail")) { if (FolderExists(mailbox.Name, destinationFolder)) { BeginCopy(source, mailbox, destination); } else { destination.CreateMailbox(mailbox.Name); destinationFolder = destination.ListMailboxes(string.Empty, "*"); BeginCopy(source, mailbox, destination); } } } Console.WriteLine("Sending Done"); Console.ReadKey(); }
public IEnumerable <string> GetMailBoxNames() { ConnectToServer(); List <string> result = new List <string>(); try { Mailbox[] listMailboxes = Imap.ListMailboxes(string.Empty, "*"); foreach (Mailbox listMailbox in listMailboxes) { result.Add(listMailbox.Name); } return(result); } catch { throw new MailException("Something went wrong while retreiving MailBox names, please check internet connectivity, username and password"); } finally { DisconnectFromServer(); } }
private bool ExtractAttatchments(MailerSearch _search, Action <string> callback) { using (ImapClient Client = new ImapClient(this.Host, this.Port, this.UserName, this.Password, AuthMethodType, this.Ssl)) { var b = Client.ListMailboxes(); IEnumerable <uint> uids = Client.Search(_search.SetSearchConditions()); IEnumerable <MailMessage> messages = Client.GetMessages(uids, FetchOptions.Normal); // Lets Create a Parent Directory with Current DateTime Stamp RootFolderWithUniqueName(_search); int index = 0; foreach (var msg in messages) { foreach (var view in msg.AlternateViews) { // Generate a Folder with Current Datetime of Email and Attatchment File Name GenerateDirectorySaveAtttachment(msg, ref index, view, _search); } foreach (var attachment in msg.Attachments) { // Generate a Folder with Current Datetime of Email and Attatchment File Name GenerateDirectorySaveAtttachment(msg, ref index, attachment, _search); } } callback(this.RootPath); } return(true); }
public static bool openNewImapClient() { try { if (UserData.checkIsGmailEmail()) { mImapClient = new ImapClient(GMAIL_IMAP_SERVER, UserData.getEmailAddres(), UserData.getEmailPassword(), AE.Net.Mail.AuthMethods.Login, 993, true); } else { mImapClient = new ImapClient(MAIL_IMAP_SERVER, UserData.getEmailAddres(), UserData.getEmailPassword(), AE.Net.Mail.AuthMethods.Login, 993, true); } mImapClient.SelectMailbox(INBOX_MAILBOX); AE.Net.Mail.Imap.Mailbox[] mailBoxes = mImapClient.ListMailboxes(string.Empty, "*"); foreach (var mailBox in mailBoxes) { var mailboxName = mailBox.Name; } } catch (Exception e) { return(false); } return(true); }
public IEnumerable <string> GetMailboxes() { ImapClient client = GetClient(); using (client) { IEnumerable <string> mailboxes = client.ListMailboxes(); return(mailboxes); } }
public IEnumerable <string> GetMailboxes() { ImapClient client = new ImapClient(hostname, 993, Username, Password, AuthMethod.Login, true); using (client) { IEnumerable <string> mailboxes = client.ListMailboxes(); return(mailboxes); } }
public void Run() { if (this.Options.ImapPort == 0) { this.Options.ImapPort = this.Options.ImapSsl ? 993 : 143; } if (this.Options.Password == null) { Console.WriteLine("Enter password:"******"Opening imap connection to {this.Options.ImapServer}:{this.Options.ImapPort} using {this.Options.AuthMethod}."); // The default port for IMAP over SSL is 993. using ( var client = new ImapClient( this.Options.ImapServer, this.Options.ImapPort, this.Options.UserName, this.Options.Password, this.Options.AuthMethod, this.Options.ImapSsl)) { Log.Info($"Retrieving mailboxes."); var mailboxes = client.ListMailboxes(); var targetDirectory = Directory.CreateDirectory(this.Options.Target); // delete obsolete folders foreach (var dir in targetDirectory.GetDirectories("*.*", SearchOption.AllDirectories).OrderByDescending(d => d.FullName) // Descending to ensure child folders are first .Where(dir => !mailboxes.Any(m => IsSameDirectory(Path.Combine(targetDirectory.FullName, m), dir.FullName)))) { if (this.Options.Delete) { Log.Verbose($"Deleting depricated mailbox {dir}."); dir.Delete(true); } else { Log.Verbose($"Mailbox {dir} is depricated."); } } foreach (var mailbox in mailboxes) { this.SynchronizeMailbox(client, mailbox, Directory.CreateDirectory(Path.Combine(targetDirectory.FullName, mailbox))); } //IEnumerable<uint> uids = client.Search(SearchCondition.All()); Log.Verbose("Disconnecting."); } Log.Info("Disconnected."); }
public string[] ListFolders() { if (folders == null) { using (ImapClient client = new ImapClient(imapHost, 993, username, password, AuthMethod.Login, true)) { folders = client.ListMailboxes(); } } return(folders); }
public void mailboxList() { // move specific emails using (ImapClient Client = new ImapClient("imap.gmail.com", 993, "*****@*****.**", "aq1sw2de3fr4", AuthMethod.Login, true)) { IEnumerable <uint> uids = Client.Search(SearchCondition.All()); IEnumerable <string> mailboxes = Client.ListMailboxes(); foreach (string i in mailboxes) { Console.WriteLine(i.ToString()); } } }
public void ListSelectableMailboxes() { string[] expected = new string[] { "INBOX", "[Gmail]/Όλα τα μηνύματα", "[Gmail]/Ανεπιθύμητα", "[Gmail]/Απεσταλμένα", "[Gmail]/Κάδος απορριμμάτων", "[Gmail]/Με αστέρι", "[Gmail]/Πρόχειρα", "[Gmail]/Σημαντικά" }; using(ImapClient client = new ImapClient( new MockStream(Properties.Resources.ImapListResponse))) { IEnumerable<string> list = client.ListMailboxes(); Assert.IsTrue(expected.SequenceEqual(list)); } }
public void ListSelectableMailboxes() { string[] expected = new string[] { "INBOX", "[Gmail]/Όλα τα μηνύματα", "[Gmail]/Ανεπιθύμητα", "[Gmail]/Απεσταλμένα", "[Gmail]/Κάδος απορριμμάτων", "[Gmail]/Με αστέρι", "[Gmail]/Πρόχειρα", "[Gmail]/Σημαντικά" }; using (ImapClient client = new ImapClient( new MockStream(Resources.ImapListResponse))) { IEnumerable <string> list = client.ListMailboxes(); Assert.IsTrue(expected.SequenceEqual(list)); } }
public ActionResult GetMailBoxes() { if (CheckLogin) { using (ImapClient Client = QLogin()) { try { IEnumerable <string> MailBoxs = Client.ListMailboxes(); List <MailboxInfo> MailBoxes = new List <MailboxInfo>(); foreach (string MailBox in MailBoxs) { MailBoxes.Add(Client.GetMailboxInfo(MailBox)); } return(OkSuccess(MailBoxes)); } catch (Exception e) { return(BadRequestFail(e.Message)); } } } return(AccessDenied()); }
public static GAAutentication Autenticate(string _client_id, string _client_secret) { GAAutentication result = new GAAutentication(); //If you want to test new gmail account, //Go to the browser, log off, log in with the new account, //and then change this 'tmpUser' var tmpUser = "******"; try { result.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = _client_id, ClientSecret = _client_secret }, new[] { "https://mail.google.com/ email" }, tmpUser, CancellationToken.None, new FileDataStore("Analytics.Auth.Store")).Result; } catch (Exception ex) { } if (result.credential != null) { result.service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = result.credential, ApplicationName = "Google mail", }); Google.Apis.Plus.v1.Data.Person me = result.service.People.Get("me").Execute(); Google.Apis.Plus.v1.Data.Person.EmailsData myAccountEmail = me.Emails.Where(a => a.Type == "account").FirstOrDefault(); // Connect to the IMAP server. The 'true' parameter specifies to use SSL // which is important (for Gmail at least) ImapClient ic = new ImapClient("imap.gmail.com", myAccountEmail.Value, result.credential.Token.AccessToken, ImapClient.AuthMethods.SaslOAuth, 993, true); var listOfMainboxes = ic.ListMailboxes(string.Empty, "*"); Console.WriteLine("ListMailboxes"); foreach (Mailbox mb in listOfMainboxes) { Console.WriteLine(mb.Name); var original = Console.ForegroundColor; var examine = ic.Examine(mb.Name); if (examine != null) { //Count? ic.SelectMailbox(mb.Name); Console.WriteLine(" - Count: " + ic.GetMessageCount()); //Get One Email per folder MailMessage[] mm = ic.GetMessages(0, 0); Console.ForegroundColor = ConsoleColor.Blue; foreach (MailMessage m in mm) { Console.WriteLine(" - " + m.Subject + " " + m.Date); } Console.ForegroundColor = original; } else { Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine("* Folder doesn't exists: " + mb.Name); Console.ForegroundColor = original; } } /* * // Select a mailbox. Case-insensitive * ic.SelectMailbox("INBOX"); * * Console.WriteLine(ic.GetMessageCount()); * // Get the first *11* messages. 0 is the first message; * // and it also includes the 10th message, which is really the eleventh ;) * // MailMessage represents, well, a message in your mailbox * MailMessage[] mm = ic.GetMessages(0, 10); * foreach (MailMessage m in mm) * { * Console.WriteLine(m.Subject + " " + m.Date.ToString()); * } * // Probably wiser to use a using statement */ ic.Dispose(); } return(result); }
public IEnumerable <string> GetBoxes() { return(_client.ListMailboxes()); }
public void retrieveMail(String mailbox = "INBOX") { currentMailBox = mailbox; MailList.Clear(); if (imapHost.Equals(null) || imapHost.Equals(null) || password.Equals(null)) { ALSMessageBox mb = new ALSMessageBox("Not logged in"); mb.Show(); return; } try { // The default port for IMAP over SSL is 993. using (ImapClient client = new ImapClient(imapHost, 993, username, password, AuthMethod.Login, true)) { folders = client.ListMailboxes(); Console.WriteLine("We are connected!"); // Returns a collection of identifiers of all mails matching the specified search criteria. IEnumerable <uint> uids = null; uids = client.Search(SearchCondition.All(), mailbox); // Download mail messages from the default mailbox. uint[] uidArray = uids.ToArray(); Array.Reverse(uidArray); uids = uids.Reverse(); if (uidArray.Length > DOWNLOAD_COUNT) { Array.Resize(ref uidArray, DOWNLOAD_COUNT); } IEnumerable <MailMessage> messages = client.GetMessages(uidArray, FetchOptions.NoAttachments, true, mailbox); IEnumerator <MailMessage> messageList = messages.GetEnumerator(); IEnumerator <uint> uidList = uids.GetEnumerator(); while (messageList.MoveNext()) { uidList.MoveNext(); string toAddress; try { toAddress = messageList.Current.To[0].Address; } catch { toAddress = "None"; } EmailMessage temp = new EmailMessage(messageList.Current.Subject, messageList.Current.Body, toAddress, messageList.Current.From.Address, EmailClient.Date(messageList.Current), uidList.Current); int hash = temp.GetHashCode(); bool contains = false; foreach (EmailMessage m in MailList) { if (m.GetHashCode().Equals(hash)) { contains = true; } } if (!contains) { bool added = false; int index = 0; if (MailList.Count == 0) { MailList.Add(temp); } else { while (!added && index < MailList.Count) { switch (MailList[index].CompareTo(temp)) { case -1: MailList.Insert(index, temp); added = true; break; case 0: MailList.Insert(index, temp); added = true; break; case 1: index++; break; case -99: //error code break; } } if (!added) { MailList.Add(temp); } } } } } MailList.Reverse(); } catch (InvalidCredentialsException) { }catch (System.Net.Sockets.SocketException e) { ALSMessageBox mb = new ALSMessageBox("Not connected to internet"); mb.Show(); }catch (Exception e) { ALSMessageBox mb = new ALSMessageBox("Unknown error occurred"); mb.Show(); } }
public override void Initialise(List <MailFolder> folderList) { Status = MessageProcessorStatus.Initialising; _folders = new List <ImapFolder>(); try { _imapClient = new ImapClient(_server, _useSsl ? 993 : 143, _username, _password, AuthMethod.Login, _useSsl, delegate { return(true); }); Logger.Debug("Logged into " + _server + " as " + _username); var folders = _imapClient.ListMailboxes(); if (_startDate != null || _endDate != null) { // ok we need to do a search if (_startDate != null) { _searchCondition = SearchCondition.Since((DateTime)_startDate); } if (_endDate != null) { _searchCondition = _searchCondition == null ? SearchCondition.Before((DateTime)_endDate) : _searchCondition.And(SearchCondition.Before((DateTime)_endDate)); } Logger.Debug("Only getting messages " + _searchCondition); } // Are we limiting the folder list? if (_limitFolderList != null) { var newFolders = new List <String>(); foreach (var mailbox in _limitFolderList) { var mailboxMatch = mailbox.ToLower().Replace('\\', '/');; newFolders.AddRange(folders.Where(folder => folder.ToLower().Equals(mailboxMatch))); } folders = newFolders; } foreach (var folderPath in folders) { bool isPublicFolder = false; var destinationFolder = FolderMapping.ApplyMappings(folderPath, Provider); if (IncludePublicFolders && (String.Equals(destinationFolder, PublicFolderRoot) || destinationFolder.StartsWith(PublicFolderRoot + @"\"))) { isPublicFolder = true; var start = PublicFolderRoot.Length + (destinationFolder.StartsWith(PublicFolderRoot + @"\") ? 1 : 0); destinationFolder = destinationFolder.Substring(start, destinationFolder.Length - start); } if (!String.IsNullOrWhiteSpace(destinationFolder)) { try { var folder = _imapClient.GetMailboxInfo(folderPath); if (folder.Messages == 0) { Logger.Debug("Skipping folder " + folderPath + ", no messages at all."); continue; } int messageCount = 0; if (_searchCondition != null) { var uids = _imapClient.Search(_searchCondition, folderPath); messageCount = uids.Count(); } else { messageCount = folder.Messages; } // Add it to our main folder list _mainFolderList.Add(new MailFolder() { DestinationFolder = destinationFolder, MessageCount = FailedMessageCount, SourceFolder = folderPath }); if (messageCount == 0) { Logger.Debug("Skipping folder " + folderPath + ", no messages within criteria."); continue; } _folders.Add(new ImapFolder() { MappedDestination = destinationFolder, FolderPath = folder, IsPublicFolder = isPublicFolder }); TotalMessages += !_testOnly ? messageCount : (messageCount > 20 ? 20 : messageCount); Logger.Debug("Will process " + folderPath + " => " + (isPublicFolder ? "[PUBLIC FOLDER]/" : "") + destinationFolder + ", " + messageCount + " messages, " + TotalMessages + " messages total so far."); } catch (Exception ex) { Logger.Error("Failed to get Mailbox " + folderPath + ", skipping.", ex); } } else { Logger.Info("Ignoring folder " + folderPath + ", no destination specified."); } } } catch (InvalidCredentialsException ex) { Logger.Error("Imap Runner for " + _username + " [********] to " + _server + " failed : " + ex.Message, ex); throw new MessageProcessorException("Imap Runner for " + _username + " [********] to " + _server + " failed : " + ex.Message) { Status = MessageProcessorStatus.SourceAuthFailure }; } catch (SocketException ex) { Logger.Error("Imap Runner for " + _username + " [********] to " + _server + " failed : " + ex.Message, ex); throw new MessageProcessorException("Imap Runner for " + _username + " [********] to " + _server + " failed : " + ex.Message) { Status = MessageProcessorStatus.ConnectionError }; } NextReader.Initialise(_mainFolderList); Status = MessageProcessorStatus.Initialised; Logger.Info("ExchangeExporter Initialised"); }
private async void ListMail_Loaded(object sender, RoutedEventArgs e) { //----------------------------------------------------------------------------------------------Десериализация юзера var file = await folder.CreateFileAsync("UserData.xml", CreationCollisionOption.OpenIfExists); str = await FileIO.ReadTextAsync(file); var stream = await file.OpenStreamForReadAsync(); if (str.Length != 0) { user = (List <UserData>)xml2.Deserialize(stream); } else { user = new List <UserData>(); } stream.Close(); //----------------------------------------------------------------------------------------------Десериализация айдишника file = await folder.CreateFileAsync("ID.xml", CreationCollisionOption.OpenIfExists); str = await FileIO.ReadTextAsync(file); var stream1 = await file.OpenStreamForReadAsync(); if (str.Length != 0) { id = (int)xml.Deserialize(stream1); } else { id = 0; } stream1.Close(); try { ic = new ImapClient(user[id].imap, user[id].Login, user[id].Pass, AuthMethods.Login, 993, true); var mailbox = ic.ListMailboxes("", "*"); string[] mailboxes = new string[3]; if (user[id].imap == "imap.mail.ru") { mailboxes = new string[] { "Отправленные", "Черновики", "Корзина", } } ; if (user[id].imap == "imap.gmail.com") { mailboxes = new string[] { "[Gmail]/Отправленные", "[Gmail]/Черновики", "[Gmail]/Корзина", } } ; if (user[id].imap == "imap.yandex.ru") { mailboxes = new string[] { "Исходящие", "Черновики", "Удаленные", } } ; if (user[id].imap == "imap.rambler.ru") { mailboxes = new string[] { "SentBox", "DraftBox", "Trash", } } ; if (navName == "Исходящие") { ic.SelectMailbox(mailboxes[0]); } if (navName == "Черновик") { ic.SelectMailbox(mailboxes[1]); } if (navName == "Корзина") { ic.SelectMailbox(mailboxes[2]); } if (navName == "Входящие") { ic.SelectMailbox("INBOX"); } if (navName == "") { ic.SelectMailbox("INBOX"); } mm = ic.GetMessages(0, ic.GetMessageCount(), false); foreach (MailMessage mail in mm) { ListBoxItem message = new ListBoxItem(); message.Content = mail.Subject; message.RightTapped += (s, ev) => { MenuFlyout flyout = new MenuFlyout(); MenuFlyoutItem answer = new MenuFlyoutItem(); answer.Text = "Ответить"; flyout.Items.Add(answer); answer.Click += (send, eve) => { var frame = this.Frame as Frame; frame.Navigate(typeof(EditPage), mail.From.Address.ToString()); //ic.DeleteMessage(mail); //ic.Expunge(); //var frame = this.Frame as Frame; //frame.Navigate(typeof(MailPage)); }; FlyoutBase.SetAttachedFlyout(message, flyout); FlyoutBase.ShowAttachedFlyout((FrameworkElement)s); }; ListMail.Items.Add(message); } ic.Dispose(); } catch (Exception ex) { ContentDialog prog = new ContentDialog() { Title = "Ошибка", Content = $"Произошла ошибка: {ex.Message}", PrimaryButtonText = "OK" }; try { await prog.ShowAsync(); } catch { }; } }