private async Task <ImapClient> GetImapConnectionAsyncInternal(CancellationToken cancellationToken = default) { var client = new ImapClient(); if (config.DebugDisableEmailServerCertificateCheck) { client.ServerCertificateValidationCallback = client.ServerCertificateValidationCallback = (s, c, h, e) => true; } try { await client.ConnectAsync(imapHostName, imapPort, SecureSocketOptions.Auto, cancellationToken); // SecureSockecOptions } catch (SocketException e) { if (e.SocketErrorCode == SocketError.ConnectionRefused) { // no server running?; terminal exception throw; } throw new TeasmCompanionException("Exception while connecting to IMAP server, but we'll retry", e); } catch (ArgumentException) { // those are exceptions like host name not set etc.; terminal exception throw; } catch (ImapProtocolException imapProtocolException) { if (imapProtocolException.Message.Equals("The IMAP server has unexpectedly disconnected.", StringComparison.InvariantCultureIgnoreCase)) { throw new TeasmCompanionException("The IMAP server has unexpectedly disconnected, but we'll retry", imapProtocolException); } else { throw; } } catch (OperationCanceledException) { throw; } catch (Exception e) { throw new TeasmCompanionException("Exception while connecting to IMAP server, but we'll retry", e); } await client.AuthenticateAsync(imapUserName, imapPassword, cancellationToken); return(client); }
public async Task TestSortAnnotationsAsync() { var commands = CreateSortAnnotationsCommands(); using (var client = new ImapClient()) { var credentials = new NetworkCredential("username", "password"); try { await client.ReplayConnectAsync("localhost", new ImapReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } // Note: we do not want to use SASL at all... client.AuthenticationMechanisms.Clear(); try { await client.AuthenticateAsync(credentials); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.IsInstanceOf <ImapEngine> (client.Inbox.SyncRoot, "SyncRoot"); var inbox = (ImapFolder)client.Inbox; await inbox.OpenAsync(FolderAccess.ReadWrite); Assert.AreEqual(AnnotationAccess.ReadOnly, inbox.AnnotationAccess, "AnnotationAccess"); Assert.AreEqual(AnnotationScope.Both, inbox.AnnotationScopes, "AnnotationScopes"); Assert.AreEqual(0, inbox.MaxAnnotationSize, "MaxAnnotationSize"); var orderBy = new OrderByAnnotation(AnnotationEntry.AltSubject, AnnotationAttribute.SharedValue, SortOrder.Ascending); var uids = await inbox.SortAsync(SearchQuery.All, new OrderBy[] { orderBy }); Assert.AreEqual(14, uids.Count, "Unexpected number of UIDs"); orderBy = new OrderByAnnotation(AnnotationEntry.AltSubject, AnnotationAttribute.SharedValue, SortOrder.Descending); uids = await inbox.SortAsync(SearchQuery.All, new OrderBy[] { orderBy }); Assert.AreEqual(14, uids.Count, "Unexpected number of UIDs"); // disable ANNOTATE-EXPERIMENT-1 and try again client.Capabilities &= ~ImapCapabilities.Annotate; Assert.Throws <NotSupportedException> (async() => await inbox.SortAsync(SearchQuery.All, new OrderBy[] { orderBy })); await client.DisconnectAsync(false); } }
public async Task TestStoreAsync() { var commands = CreateStoreCommands(); using (var client = new ImapClient()) { var credentials = new NetworkCredential("username", "password"); try { await client.ReplayConnectAsync("localhost", new ImapReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } // Note: we do not want to use SASL at all... client.AuthenticationMechanisms.Clear(); try { await client.AuthenticateAsync(credentials); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.IsInstanceOf <ImapEngine> (client.Inbox.SyncRoot, "SyncRoot"); var inbox = (ImapFolder)client.Inbox; await inbox.OpenAsync(FolderAccess.ReadWrite); Assert.AreEqual(AnnotationAccess.ReadWrite, inbox.AnnotationAccess, "AnnotationAccess"); Assert.AreEqual(AnnotationScope.Shared, inbox.AnnotationScopes, "AnnotationScopes"); Assert.AreEqual(20480, inbox.MaxAnnotationSize, "MaxAnnotationSize"); var annotation = new Annotation(AnnotationEntry.AltSubject); annotation.Properties.Add(AnnotationAttribute.SharedValue, "This is an alternate subject."); var annotations = new[] { annotation }; await inbox.StoreAsync(0, annotations); await inbox.StoreAsync(new UniqueId (1), annotations); annotation.Properties[AnnotationAttribute.SharedValue] = null; await inbox.StoreAsync(0, annotations); await inbox.StoreAsync(new UniqueId (1), annotations); await client.DisconnectAsync(false); } }
public async Task <IEnumerable <IMessageSummary> > GetAllSubjects(MailDto mailDto, bool useSsl) { using (var imapClient = new ImapClient()) { imapClient.CheckCertificateRevocation = false; await imapClient.ConnectAsync(mailDto.Server, ImapPort, useSsl); await imapClient.AuthenticateAsync(mailDto.Name, mailDto.Password); var inbox = imapClient.Inbox; await inbox.OpenAsync(FolderAccess.ReadOnly); return(await inbox.FetchAsync(0, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId)); } }
public async Task <MimeMessage> GetMessage(MailDto mailDto, bool useSsl, UniqueId emailId) { using (var imapClient = new ImapClient()) { imapClient.CheckCertificateRevocation = false; await imapClient.ConnectAsync(mailDto.Server, ImapPort, useSsl); await imapClient.AuthenticateAsync(mailDto.Name, mailDto.Password); var inbox = imapClient.Inbox; await inbox.OpenAsync(FolderAccess.ReadOnly); return(await inbox.GetMessageAsync(emailId)); } }
public async Task <ActionResult> Index(Authentication login) { Response.Cookies["serverId"].Value = login.Server.Id.ToString(); try { login.Server = await Task.Run(() => GetServer(login.Server.Id)); } catch (Exception) { ViewData["Login error"] = "Неизвесная ошибка"; return(Index()); } ImapClient client = new ImapClient(); try { await client.ConnectAsync(login.Server.Ip, login.Server.Port, MailKit.Security.SecureSocketOptions.Auto); } catch (Exception e) { ViewData["Login error"] = $"Почтовый сервер {login.Server.Name} не доступен. Попробуйте позже."; return(Index()); } if (!client.IsConnected) { ViewData["Login error"] = $"Почтовый сервер {login.Server.Name} не доступен. Попробуйте позже."; return(Index()); } try { await client.AuthenticateAsync(login.Email, login.Password); } catch (Exception) { ViewData["Login error"] = "Неверные ел. почта и/или пароль."; return(Index()); } if (!client.IsAuthenticated) { ViewData["Login error"] = "Неверные ел. почта и/или пароль."; return(Index()); } Session["login"] = login; Session["connection"] = client; IMailFolder inbox = client.Inbox; Session["folder"] = inbox; Session["messages"] = null; return(Index()); }
private async Task <ImapClient> CreateClient() { string host = Configuration.GetValue <string>("Email:ImapHost"); int port = Configuration.GetValue <int>("Email:ImapPort"); bool enableSsl = Configuration.GetValue <bool>("Email:EnableSsl"); string username = Configuration.GetValue <string>("Email:Username"); string password = Configuration.GetValue <string>("Email:Password"); var result = new ImapClient(); await result.ConnectAsync(host, port, enableSsl); await result.AuthenticateAsync(username, password); return(result); }
public static async Task ReconnectAsync(string host, int port, SecureSocketOptions options) { // Note: for demo purposes, we're ignoring SSL validation errors (don't do this in production code) Client.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; await Client.ConnectAsync(host, port, options); await Client.AuthenticateAsync(Credentials); if (Client.Capabilities.HasFlag(ImapCapabilities.UTF8Accept)) { await Client.EnableUTF8Async(); } CurrentTask = Task.FromResult(true); }
static async Task Process() { using (var client = new ImapClient()) { // Connection await client.ConnectAsync(_host, _port, _secure); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH"); // Authentication await client.AuthenticateAsync(_userName, _password); } }
public async Task DeleteMessageAsync(DateTime date) { using (var client = new ImapClient()) { await client.ConnectAsync(ServerPath, Port, SecureSocketOptions.SslOnConnect); await client.AuthenticateAsync(Email, Password); await client.Inbox.OpenAsync(FolderAccess.ReadWrite); var uids = await client.Inbox.SearchAsync(SearchQuery.DeliveredOn(date)); await client.Inbox.SetFlagsAsync(uids[0], MessageFlags.Deleted, false).ConfigureAwait(false); await client.DisconnectAsync(true); } }
public async void TestMessageCount() { var commands = new List <ImapReplayCommand> (); commands.Add(new ImapReplayCommand("", "gmail.greeting.txt")); commands.Add(new ImapReplayCommand("A00000000 CAPABILITY\r\n", "gmail.capability.txt")); commands.Add(new ImapReplayCommand("A00000001 AUTHENTICATE PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "gmail.authenticate.txt")); commands.Add(new ImapReplayCommand("A00000002 NAMESPACE\r\n", "gmail.namespace.txt")); commands.Add(new ImapReplayCommand("A00000003 LIST \"\" \"INBOX\"\r\n", "gmail.list-inbox.txt")); commands.Add(new ImapReplayCommand("A00000004 XLIST \"\" \"*\"\r\n", "gmail.xlist.txt")); // INBOX has 1 message present in this test commands.Add(new ImapReplayCommand("A00000005 EXAMINE INBOX (CONDSTORE)\r\n", "gmail.count.examine.txt")); // next command simulates one expunge + one new message commands.Add(new ImapReplayCommand("A00000006 NOOP\r\n", "gmail.count.noop.txt")); using (var client = new ImapClient()) { try { client.ReplayConnect("localhost", new ImapReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); // Note: Do not try XOAUTH2 client.AuthenticationMechanisms.Remove("XOAUTH2"); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } var count = -1; await client.Inbox.OpenAsync(FolderAccess.ReadOnly); client.Inbox.CountChanged += delegate { count = client.Inbox.Count; }; await client.NoOpAsync(); Assert.AreEqual(1, count, "Count is not correct"); } }
public async Task TestAppendWithAnnotationsAsync(bool withInternalDates) { var expectedFlags = MessageFlags.Answered | MessageFlags.Flagged | MessageFlags.Deleted | MessageFlags.Seen | MessageFlags.Draft; var expectedPermanentFlags = expectedFlags | MessageFlags.UserDefined; List <DateTimeOffset> internalDates; List <Annotation> annotations; List <MimeMessage> messages; List <MessageFlags> flags; var commands = CreateAppendWithAnnotationsCommands(withInternalDates, out messages, out flags, out internalDates, out annotations); using (var client = new ImapClient()) { try { await client.ReplayConnectAsync("localhost", new ImapReplayStream (commands, true)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } client.AuthenticationMechanisms.Clear(); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } for (int i = 0; i < messages.Count; i++) { UniqueId?uid; if (withInternalDates) { uid = await client.Inbox.AppendAsync(messages[i], flags[i], internalDates[i], new[] { annotations[i] }); } else { uid = await client.Inbox.AppendAsync(messages[i], flags[i], null, new[] { annotations[i] }); } Assert.IsTrue(uid.HasValue, "Expected a UIDAPPEND resp-code"); Assert.AreEqual(i + 1, uid.Value.Id, "Unexpected UID"); } await client.DisconnectAsync(true); } }
public async Task GetNewMessages() { using var client = new ImapClient(); client.Connect(_hostName, _port, _ssl); await client.AuthenticateAsync(_userName, _password); var inbox = client.Inbox; await inbox.OpenAsync(FolderAccess.ReadOnly); Console.WriteLine($"Total Messages: {inbox.Count}"); Console.WriteLine($"Recent Messages: {inbox.Recent}"); await searchMessages(inbox); await client.DisconnectAsync(true); }
public async Task ReconnectAsync() { // TODO: SSL validation Client.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; try { await Client.ConnectAsync(host, port, options); await Client.AuthenticateAsync(Credentials); } catch (Exception ex) { NewLogMessage?.Invoke(this, $"{DateTime.Now}: {ex.Message}"); } if (Client.Capabilities.HasFlag(ImapCapabilities.UTF8Accept)) { await Client.EnableUTF8Async(); } if (folders == null) { folders = new Dictionary <IMailFolder, TreeNode>(); var folder = Client.GetFolder(Client.PersonalNamespaces[0]); rootNode = new TreeNode() { Name = "root", Text = host, Tag = folder }; folders.Add(folder, rootNode); Stopwatch stopWhatch = new Stopwatch(); stopWhatch.Start(); await ReadSubFolders(rootNode); stopWhatch.Stop(); NewLogMessage?.Invoke(this, $"{DateTime.Now}: {host} folders readed by {stopWhatch.ElapsedMilliseconds} ms."); UpdateFoldersTree?.Invoke(this, rootNode); } }
public static async Task <ImapClient> CreateClientAndConnectAsync() { var imapClient = new ImapClient(); await imapClient.ConnectAsync(MailHostOptions.Imap163Host, MailHostOptions.Imap163Port); await imapClient.AuthenticateAsync(MailHostOptions.Imap163Account, MailHostOptions.QqPassword); var clientImplementation = new ImapImplementation() { Name = "Study-C-Sharp", Version = "1.0.0", OS = "Windows", OSVersion = "21H2" }; await imapClient.IdentifyAsync(clientImplementation); return(imapClient); }
public async Task MakeReadAsync(uint uid) { using (var emailClient = new ImapClient()) { //emailClient.AuthenticationMechanisms.Remove("XOAUTH2"); await emailClient.ConnectAsync(ec.ImapServerAddress, Convert.ToInt32(ec.ImapServerPort), SecureSocketOptions.Auto).ConfigureAwait(false); await emailClient.AuthenticateAsync(new NetworkCredential(ec.UserId, ec.UserPassword)); await emailClient.Inbox.OpenAsync(MailKit.FolderAccess.ReadWrite); emailClient.Inbox.AddFlags(new MailKit.UniqueId(uid), MessageFlags.Seen, true); var message = await emailClient.Inbox.GetMessageAsync(new MailKit.UniqueId(uid)); var Email = message.From.Mailboxes.FirstOrDefault().Address.ToString(); await emailClient.DisconnectAsync(true).ConfigureAwait(false); } }
public async Task <string> ValidateCredentials(MailCreateDto mailCreateDto) { try { using (var imapClient = new ImapClient()) { imapClient.CheckCertificateRevocation = false; await imapClient.ConnectAsync(mailCreateDto.Server, ImapPort, true); await imapClient.AuthenticateAsync(mailCreateDto.Name, mailCreateDto.Password); } } catch (Exception ex) { return(ex.Message); } return(default);
private async Task <bool> TestConnection() { UseWaitCursor = true; SetAllControlsDisabled(this, false); var cancellation = new CancellationTokenSource(); void Cancel(object?sender, EventArgs e) { cancellation.Cancel(); } _cancel.Enabled = true; // Allow cancellation _cancel.DialogResult = DialogResult.None; _cancel.Click += Cancel; try { var imapClient = new ImapClient(); await imapClient.ConnectAsync(_server.Text, (int)_port.Value, _ssl.Checked, cancellation.Token); await imapClient.AuthenticateAsync(_username.Text, _password.Text, cancellation.Token); if (imapClient.Capabilities.HasFlag(ImapCapabilities.Idle)) { return(true); } MessageBox.Show(this, "IMAP server does not support IDLE", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (TaskCanceledException) { } catch (Exception ex) { MessageBox.Show(this, "Unable to connect to IMAP server:\n\n" + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { UseWaitCursor = false; SetAllControlsDisabled(this, true); _cancel.DialogResult = DialogResult.Cancel; _cancel.Click -= Cancel; } return(false); }
public async Task <ApiResponse> ReceiveMailImapAsync() { using (var emailClient = new ImapClient()) { // use this if you need to specify using ssl; MailKit should usually be able to autodetect the appropriate settings // await emailClient.ConnectAsync(_emailConfiguration.ImapServer, _emailConfiguration.ImapPort, _emailConfiguration.ImapUseSSL); await emailClient.ConnectAsync(_emailConfiguration.ImapServer, _emailConfiguration.ImapPort); emailClient.AuthenticationMechanisms.Remove("XOAUTH2"); if (!string.IsNullOrWhiteSpace(_emailConfiguration.ImapUsername)) { await emailClient.AuthenticateAsync(_emailConfiguration.ImapUsername, _emailConfiguration.ImapPassword); } List <EmailMessageDto> emails = new List <EmailMessageDto>(); await emailClient.Inbox.OpenAsync(MailKit.FolderAccess.ReadOnly); //TODO implement email results filtering var uids = await emailClient.Inbox.SearchAsync(SearchQuery.All); foreach (var uid in uids) { var message = await emailClient.Inbox.GetMessageAsync(uid); var emailMessage = new EmailMessageDto { Body = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody, Subject = message.Subject }; emailMessage.ToAddresses.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new EmailAddressDto(x.Name, x.Address))); emailMessage.FromAddresses.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EmailAddressDto(x.Name, x.Address))); emails.Add(emailMessage); } await emailClient.DisconnectAsync(true); return(new ApiResponse(Status200OK, null, emails)); } }
public async Task <ImapClient> CreateClientAndConnect() { try { var client = new ImapClient(); var data = GetData(); client.ServerCertificateValidationCallback = (s, c, h, e) => true; await client.ConnectAsync(data.Server, data.Port, data.SSL); await client.AuthenticateAsync(data.Username, data.Password); return(client.IsConnected && client.IsAuthenticated? client : null); } catch (Exception) { return(null); } }
public static async Task <bool> TryAuthenticateAsync(this ImapClient client, IEmailConfiguration configuration, int timeout, ICqLogger cqLogger) { try { client.Timeout = timeout; await client.ConnectAsync(configuration.ImapServer, configuration.ImapPort, true); client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.AuthenticateAsync(configuration.Email, configuration.Password); return(true); } catch (Exception e) { await cqLogger.LogToFile(e.ToString(), "Email Assistant Extensions Error"); return(false); } }
public Task AuthorizeAsync(string userName, string password, EmailService emailService = EmailService.Gmail) { _username = userName; _password = password; _emailService = emailService; return(Task.Run(async() => { var emailServiceInfo = EmailServiceProvider.GetEmailServiceInfo(emailService); _imapClient = new ImapClient { ServerCertificateValidationCallback = (s, c, h, e) => true }; await _imapClient.ConnectAsync(emailServiceInfo.ImapHost, emailServiceInfo.ImapPort, true); await _imapClient.AuthenticateAsync(userName, password); })); }
public void TestArgumentExceptions() { using (var client = new ImapClient()) { var credentials = new NetworkCredential("username", "password"); // Connect Assert.Throws <ArgumentNullException> (() => client.Connect((Uri)null)); Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync((Uri)null)); Assert.Throws <ArgumentNullException> (() => client.Connect(null, 143, false)); Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync(null, 143, false)); Assert.Throws <ArgumentException> (() => client.Connect(string.Empty, 143, false)); Assert.Throws <ArgumentException> (async() => await client.ConnectAsync(string.Empty, 143, false)); Assert.Throws <ArgumentOutOfRangeException> (() => client.Connect("host", -1, false)); Assert.Throws <ArgumentOutOfRangeException> (async() => await client.ConnectAsync("host", -1, false)); Assert.Throws <ArgumentNullException> (() => client.Connect(null, 143, SecureSocketOptions.None)); Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync(null, 143, SecureSocketOptions.None)); Assert.Throws <ArgumentException> (() => client.Connect(string.Empty, 143, SecureSocketOptions.None)); Assert.Throws <ArgumentException> (async() => await client.ConnectAsync(string.Empty, 143, SecureSocketOptions.None)); Assert.Throws <ArgumentOutOfRangeException> (() => client.Connect("host", -1, SecureSocketOptions.None)); Assert.Throws <ArgumentOutOfRangeException> (async() => await client.ConnectAsync("host", -1, SecureSocketOptions.None)); // Authenticate Assert.Throws <ArgumentNullException> (() => client.Authenticate(null)); Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null)); Assert.Throws <ArgumentNullException> (() => client.Authenticate(null, "password")); Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null, "password")); Assert.Throws <ArgumentNullException> (() => client.Authenticate("username", null)); Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync("username", null)); Assert.Throws <ArgumentNullException> (() => client.Authenticate(null, credentials)); Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null, credentials)); Assert.Throws <ArgumentNullException> (() => client.Authenticate(Encoding.UTF8, null)); Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(Encoding.UTF8, null)); Assert.Throws <ArgumentNullException> (() => client.Authenticate(null, "username", "password")); Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null, "username", "password")); Assert.Throws <ArgumentNullException> (() => client.Authenticate(Encoding.UTF8, null, "password")); Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(Encoding.UTF8, null, "password")); Assert.Throws <ArgumentNullException> (() => client.Authenticate(Encoding.UTF8, "username", null)); Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(Encoding.UTF8, "username", null)); } }
public async Task Connect() { try { using (var client = new SmtpClient()) { await client.ConnectAsync(Smtp.Server, Smtp.Port, Smtp.UseSsl); await client.AuthenticateAsync(Address, _password); await client.DisconnectAsync(true); } using (var client = new ImapClient()) { await client.ConnectAsync(Imap.Server, Imap.Port, Imap.UseSsl); await client.AuthenticateAsync(Address, _password); await client.DisconnectAsync(true); } } catch (SocketException ex) { string message = "Невозможно установить соединение " + "с почтовым сервером. "; if (ex.ErrorCode == 11001) { message += "Проверьте подключение к интернету."; } else { message += ex.Message; } throw new Exception(message); } catch { throw new Exception("Логин или пароль неверны."); } }
private async Task EnsureConnectionOf(ImapClient imap, IMailClientConfiguration configuration) { if (!imap.IsConnected) { _logger?.LogDebug($"Connecting {nameof(ImapClient)} to {configuration.Host}."); await imap.ConnectAsync(configuration.Host, configuration.ImapPort, SocketOptions); } if (!imap.IsAuthenticated) { _logger?.LogDebug($"Authenticating {nameof(ImapClient)}."); await imap.AuthenticateAsync(configuration.UserName, configuration.Password); } if (!imap.Inbox.IsOpen) { _logger?.LogDebug($"Opening Inbox of {nameof(ImapClient)}."); await imap.Inbox.OpenAsync(FolderAccess.ReadWrite); } }
public async Task Reconnect() { if (!_client.IsConnected) { _logger.LogInformation("{id}: Connecting to Mail Box {server}:{port} ...", Identifier, _mailBox.Server, _mailBox.Port); await _client.ConnectAsync(_mailBox.Server, _mailBox.Port, MailKit.Security.SecureSocketOptions.Auto, _cancel.Token); } if (!_client.IsAuthenticated) { _logger.LogInformation("{id}: Authenticating Mail Box ...", Identifier); await _client.AuthenticateAsync(_mailBox.Username, _mailBox.Password, _cancel.Token); _logger.LogInformation("{id}: Connecting to Inbox ...", Identifier); await _client.Inbox.OpenAsync(FolderAccess.ReadOnly, _cancel.Token); } }
public async Task MarkEmailAsSeen(UniqueId uid) { using var client = new ImapClient(); await client.ConnectAsync(_mailServer, _port, _ssl).ConfigureAwait(false); client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.AuthenticateAsync(_login, _password).ConfigureAwait(false); var folder = await client.GetFolderAsync(_currentFolder).ConfigureAwait(false); await folder.OpenAsync(FolderAccess.ReadWrite).ConfigureAwait(false); await folder.AddFlagsAsync(new List <UniqueId> { uid }, MessageFlags.Seen, true); await client.DisconnectAsync(true).ConfigureAwait(false); }
static async Task OAuthAsync(ImapClient client) { var clientSecrets = new ClientSecrets { ClientId = "XXX.apps.googleusercontent.com", ClientSecret = "XXX" }; var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore("CredentialCacheFolder", false), Scopes = new [] { "https://mail.google.com/" }, ClientSecrets = clientSecrets }); // Note: For a web app, you'll want to use AuthorizationCodeWebApp instead. var codeReceiver = new LocalServerCodeReceiver(); var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver); var credential = await authCode.AuthorizeAsync(GMailAccount, CancellationToken.None); if (credential.Token.IsExpired(SystemClock.Default)) { await credential.RefreshTokenAsync(CancellationToken.None); } // Note: We use credential.UserId here instead of GMailAccount because the user *may* have chosen a // different GMail account when presented with the browser window during the authentication process. SaslMechanism oauth2; if (client.AuthenticationMechanisms.Contains("OAUTHBEARER")) { oauth2 = new SaslMechanismOAuthBearer(credential.UserId, credential.Token.AccessToken); } else { oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken); } await client.AuthenticateAsync(oauth2); }
static async Task AuthenticateAsync(ImapClient client) { var options = new PublicClientApplicationOptions { ClientId = "Application (client) ID", TenantId = "Directory (tenant) ID", RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient" }; var publicClientApplication = PublicClientApplicationBuilder .CreateWithApplicationOptions(options) .Build(); var scopes = new string[] { "email", "offline_access", "https://outlook.office.com/IMAP.AccessAsUser.All", // Only needed for IMAP //"https://outlook.office.com/POP.AccessAsUser.All", // Only needed for POP //"https://outlook.office.com/SMTP.AccessAsUser.All", // Only needed for SMTP }; var authToken = await publicClientApplication.AcquireTokenInteractive(scopes).WithLoginHint(ExchangeAccount).ExecuteAsync(cancellationToken); await publicClientApplication.AcquireTokenSilent(scopes, authToken.Account).ExecuteAsync(cancellationToken); // Note: We use authToken.Account.Username here instead of ExchangeAccount because the user *may* have chosen a // different Microsoft Exchange account when presented with the browser window during the authentication process. SaslMechanism oauth2; if (client.AuthenticationMechanisms.Contains("OAUTHBEARER")) { oauth2 = new SaslMechanismOAuthBearer(authToken.Account.Username, authToken.AccessToken); } else { oauth2 = new SaslMechanismOAuth2(authToken.Account.Username, authToken.AccessToken); } await client.AuthenticateAsync(oauth2); }
private Task <ImapClient> ConnectToServerAsync(AppConfiguration config, string password, IProgress <string> progress) { return(Task.Run(async() => { var client = new ImapClient(); // Accept all SSL certificates client.ServerCertificateValidationCallback = (s, c, h, e) => true; progress.Report($"Connecting to host '{config.Host}:{config.Port}'..."); await client.ConnectAsync(config.Host, config.Port, config.UseSsl); progress.Report($"Connected succesfully."); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); progress.Report($"Authenticating with username '{config.Username}'..."); await client.AuthenticateAsync(config.Username, password); progress.Report($"Authenticated successfully"); return client; })); }