public async Task <IEnumerable <ExtractedEmailMessage> > GetEmailMessageFromServerViaPopAsync(IEmailConfiguration popEmailConfiguration, int batchsize = -1) { var results = new List <ExtractedEmailMessage>(); using (var client = new Pop3Client()) { await ConnectToServer(popEmailConfiguration, client); var totalMessages = batchsize <= -1 || batchsize > client.Count ? client.Count : batchsize; for (int i = 0; i < totalMessages; i++) { var uid = client.GetMessageUid(i); var message = client.GetMessage(i); var extractedMessage = new ExtractedEmailMessage { FromAddress = message.From.Mailboxes.FirstOrDefault()?.Address, ToAddress = message.To.Mailboxes.Select(x => x.Address).ToList(), HtmlBody = message.HtmlBody, TextBody = message.TextBody, Subject = message.Subject, MessageUniqueId = uid, Attachments = await GetAttachmentsInBase64String(message) }; results.Add(extractedMessage); } await client.DisconnectAsync(true); } return(results); }
/// <summary> /// 接收邮件 /// </summary> public static async Task <IEnumerable <MailEntity> > ReceiveEmail(string userName, string password, string host, int port, bool useSsl, int count = 1) { try { using (var client = new Pop3Client()) { // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; await client.ConnectAsync(host, port, useSsl); await client.AuthenticateAsync(userName, password); var msg = await client.GetMessagesAsync(Enumerable.Range(client.Count - count, count).ToList()); var list = msg.Select(it => new MailEntity { Date = it.Date, MessageId = it.MessageId, Subject = it.Subject, TextBody = it.TextBody, HtmlBody = it.HtmlBody, }); await client.DisconnectAsync(true); return(list); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(null); }
public async void TestBasicPop3ClientUnixLineEndings() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "comcast.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "comcast.capa1.txt")); commands.Add(new Pop3ReplayCommand("USER username\r\n", "comcast.ok.txt")); commands.Add(new Pop3ReplayCommand("PASS password\r\n", "comcast.ok.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "comcast.capa2.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "comcast.stat1.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "comcast.retr1.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "comcast.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, true)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(ComcastCapa1, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(31, client.ExpirePolicy); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(ComcastCapa2, client.Capabilities); Assert.AreEqual("ZimbraInc", client.Implementation); Assert.AreEqual(2, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("X-ZIMBRA"), "Expected SASL X-ZIMBRA auth mechanism"); Assert.AreEqual(-1, client.ExpirePolicy); Assert.AreEqual(1, client.Count, "Expected 1 message"); try { var message = await client.GetMessageAsync(0); // TODO: assert that the message is byte-identical to what we expect } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage: {0}", ex); } try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public async Task DisconnectFailNotConnectAsync() { Pop3Client pop3Client = new Pop3Client(new PlainMessagesDummyNetworkOperations()); Assert.IsFalse(pop3Client.IsConnected); await pop3Client.DisconnectAsync(); Assert.IsFalse(pop3Client.IsConnected); }
public override async Task <EmailLoadingStatus> LoadFromEmailAsync(IMailBox mailBox) { using (var client = new Pop3Client()) { await ConnectAsync(client, mailBox.Server); await AuthorizeAsync(client, mailBox); Logger.Info($"Подключены к {mailBox.Login} c помощью {nameof(ImapLoader)}"); await LoadMessagesAsync(mailBox, client); await client.DisconnectAsync(true, CancellationToken.None); } return(EmailLoadingStatus.Active); }
public async Task DisconnectOkAsync() { Pop3Client pop3Client = new Pop3Client(new PlainMessagesDummyNetworkOperations()); Assert.IsFalse(pop3Client.IsConnected); await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD"); Assert.IsTrue(pop3Client.IsConnected); await pop3Client.DisconnectAsync(); Assert.IsFalse(pop3Client.IsConnected); }
public async Task <ApiResponse> ReceiveMailPopAsync(int min = 0, int max = 0) { using (var emailClient = new Pop3Client()) { try { await emailClient.ConnectAsync(_emailConfiguration.PopServer, _emailConfiguration.PopPort).ConfigureAwait(false); // omitting usessl to allow mailkit to autoconfigure emailClient.AuthenticationMechanisms.Remove("XOAUTH2"); if (!String.IsNullOrWhiteSpace(_emailConfiguration.PopUsername)) { await emailClient.AuthenticateAsync(_emailConfiguration.PopUsername, _emailConfiguration.PopPassword).ConfigureAwait(false); } List <EmailMessageDto> emails = new List <EmailMessageDto>(); if (max == 0) { max = await emailClient.GetMessageCountAsync(); // if max not defined, get all messages } for (int i = min; i < max; i++) { var message = await emailClient.GetMessageAsync(i); var emailMessage = new EmailMessageDto { Body = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody, IsHtml = !string.IsNullOrEmpty(message.HtmlBody) ? true : false, 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(200, null, emails)); } catch (Exception ex) { return(new ApiResponse(500, ex.Message)); } } }
public async Task <List <RawMailMessageEntity> > CollectMailAsync(EmailConfiguration emailConfig) { var emailsRetrieved = new List <RawMailMessageEntity>(); var emailsOnServer = new List <MimeMessage>(); Dependencies.DiagnosticLogging.Verbose("MailCollection: Attempting to collect a maximum of {maxEmails} emails", emailConfig.MaxEmailsToRetrieve); try { using (var emailClient = new Pop3Client()) { var emailServerInfo = $"[{emailConfig.PopServerHost}:{emailConfig.PopServerPort}]"; Dependencies.DiagnosticLogging.Verbose("MailCollection: Collecting mail from Host:{emailServer}", emailServerInfo); await SetupConnectToEmailServerAndAuthenticate(emailConfig, emailClient, emailServerInfo); var msgCountToCollect = emailClient.Count > emailConfig.MaxEmailsToRetrieve ? emailConfig.MaxEmailsToRetrieve : emailClient.Count;; Dependencies.DiagnosticLogging.Debug("MailCollection: Successfully authenticated to email server:{emailServer}, {msgCount} mail msgs in queue, retrieving {msgCountToCollect}", emailServerInfo, emailClient.Count, msgCountToCollect); if (msgCountToCollect == 0) { return(emailsRetrieved); } emailsOnServer.AddRange(await emailClient.GetMessagesAsync(0, msgCountToCollect)); await DeleteMessagesIfRequired(emailConfig, emailClient, msgCountToCollect); await emailClient.DisconnectAsync(true); var cnt = emailsOnServer.Count; Dependencies.DiagnosticLogging.Info("MailCollection: Collected {cnt} emails from server.", cnt); emailsRetrieved.AddRange(emailsOnServer.Select(m => m.ToMailMessageEntity())); return(emailsRetrieved); } } catch (Exception ex) { Dependencies.DiagnosticLogging.Fatal(ex, "MailCollection: Error attempting to collect mail"); return(emailsRetrieved); } }
public async Task DeleteEmailMessageFromPopServerAsync(IList <ExtractedEmailMessage> messages, IEmailConfiguration popEmailConfiguration) { using (var client = new Pop3Client()) { await ConnectToServer(popEmailConfiguration, client); var uids = messages.Select(x => UniqueId.Parse(x.MessageUniqueId)).ToList(); for (int i = 0; i < client.Count; i++) { var message = client.GetMessage(i); var uid = client.GetMessageUid(i); if (uids.Any(x => x.ToString().Equals(uid))) { await client.DeleteMessageAsync(i); } } await client.DisconnectAsync(true); } }
public static async Task GetMessagesAsync(string server, string userName, string password, bool useSsl) { try { Pop3Client pop3Client = new Pop3Client( ); Console.WriteLine("Connecting to POP3 server '{0}'...{1}", server, Environment.NewLine); await pop3Client.ConnectAsync(server, userName, password, useSsl); Console.WriteLine("List and Retrieve Messages...{0}", Environment.NewLine); IEnumerable <Pop3Message> messages = await pop3Client.ListAndRetrieveAsync( ); foreach (Pop3Message message in messages) { Console.WriteLine("- Number: {0}", message.Number); Console.WriteLine("\t* MessageId: {0}", message.MessageId); Console.WriteLine("\t* Date: {0}", message.Date); Console.WriteLine("\t* From: {0}", message.From); Console.WriteLine("\t* To: {0}", message.To); Console.WriteLine("\t* Subject: {0}", message.Subject); Console.WriteLine("\t* Retrieved: {0}", message.Retrieved); Console.WriteLine("\t* Body Length: {0}", message.Body.Length); Console.WriteLine("\t* Attachments Count: {0}", ((List <Pop3Attachment>)message.Attachments).Count); Console.WriteLine( ); } Console.WriteLine("Disconnecting...{0}", Environment.NewLine); await pop3Client.DisconnectAsync( ); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.Message); Console.ForegroundColor = ConsoleColor.White; } }
public static async Task GetMessagesAsync( string server, string userName, string password, bool useSsl ) { try { Pop3Client pop3Client = new Pop3Client( ); Console.WriteLine( "Connecting to POP3 server '{0}'...{1}", server, Environment.NewLine ); await pop3Client.ConnectAsync( server, userName, password, useSsl ); Console.WriteLine( "List and Retrieve Messages...{0}", Environment.NewLine ); IEnumerable<Pop3Message> messages = await pop3Client.ListAndRetrieveAsync( ); foreach ( Pop3Message message in messages ) { Console.WriteLine( "- Number: {0}", message.Number ); Console.WriteLine( "\t* MessageId: {0}", message.MessageId ); Console.WriteLine( "\t* Date: {0}", message.Date ); Console.WriteLine( "\t* From: {0}", message.From ); Console.WriteLine( "\t* To: {0}", message.To ); Console.WriteLine( "\t* Subject: {0}", message.Subject ); Console.WriteLine( "\t* Retrieved: {0}", message.Retrieved ); Console.WriteLine( "\t* Body Length: {0}", message.Body.Length ); Console.WriteLine( "\t* Attachments Count: {0}", ((List<Pop3Attachment>)message.Attachments).Count ); Console.WriteLine( ); } Console.WriteLine( "Disconnecting...{0}", Environment.NewLine ); await pop3Client.DisconnectAsync( ); } catch ( Exception ex ) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine( ex.Message ); Console.ForegroundColor = ConsoleColor.White; } }
/// <summary> /// 验证是否能够接收邮件 /// </summary> public static async Task <bool> CanReceiveEmail(string userName, string password, string host, int port, bool useSsl) { try { using (var client = new Pop3Client()) { // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; await client.ConnectAsync(host, port, useSsl); await client.AuthenticateAsync(userName, password); await client.DisconnectAsync(true); return(true); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } }
public async void TestGMailPop3Client() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "gmail.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "gmail.capa1.txt")); commands.Add(new Pop3ReplayCommand("AUTH PLAIN\r\n", "gmail.plus.txt")); commands.Add(new Pop3ReplayCommand("AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "gmail.auth.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "gmail.capa2.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "gmail.stat.txt")); commands.Add(new Pop3ReplayCommand("UIDL\r\n", "gmail.uidl.txt")); commands.Add(new Pop3ReplayCommand("UIDL 1\r\n", "gmail.uidl1.txt")); commands.Add(new Pop3ReplayCommand("UIDL 2\r\n", "gmail.uidl2.txt")); commands.Add(new Pop3ReplayCommand("UIDL 3\r\n", "gmail.uidl3.txt")); commands.Add(new Pop3ReplayCommand("LIST\r\n", "gmail.list.txt")); commands.Add(new Pop3ReplayCommand("LIST 1\r\n", "gmail.list1.txt")); commands.Add(new Pop3ReplayCommand("LIST 2\r\n", "gmail.list2.txt")); commands.Add(new Pop3ReplayCommand("LIST 3\r\n", "gmail.list3.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "gmail.retr1.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt")); commands.Add(new Pop3ReplayCommand("TOP 1 0\r\n", "gmail.top.txt")); commands.Add(new Pop3ReplayCommand("TOP 1 0\r\nTOP 2 0\r\nTOP 3 0\r\n", "gmail.top123.txt")); commands.Add(new Pop3ReplayCommand("TOP 1 0\r\nTOP 2 0\r\nTOP 3 0\r\n", "gmail.top123.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "gmail.retr1.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt")); commands.Add(new Pop3ReplayCommand("NOOP\r\n", "gmail.noop.txt")); commands.Add(new Pop3ReplayCommand("DELE 1\r\n", "gmail.dele.txt")); commands.Add(new Pop3ReplayCommand("RSET\r\n", "gmail.rset.txt")); commands.Add(new Pop3ReplayCommand("DELE 1\r\nDELE 2\r\nDELE 3\r\n", "gmail.dele123.txt")); commands.Add(new Pop3ReplayCommand("RSET\r\n", "gmail.rset.txt")); commands.Add(new Pop3ReplayCommand("DELE 1\r\nDELE 2\r\nDELE 3\r\n", "gmail.dele123.txt")); commands.Add(new Pop3ReplayCommand("RSET\r\n", "gmail.rset.txt")); commands.Add(new Pop3ReplayCommand("DELE 1\r\nDELE 2\r\nDELE 3\r\n", "gmail.dele123.txt")); commands.Add(new Pop3ReplayCommand("RSET\r\n", "gmail.rset.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "gmail.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(GMailCapa1, client.Capabilities); Assert.AreEqual(2, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH2"), "Expected SASL XOAUTH2 auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); // Note: remove the XOAUTH2 auth mechanism to force PLAIN auth client.AuthenticationMechanisms.Remove("XOAUTH2"); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(GMailCapa2, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(3, client.Count, "Expected 3 messages"); var uids = await client.GetMessageUidsAsync(); Assert.AreEqual(3, uids.Count); Assert.AreEqual("101", uids[0]); Assert.AreEqual("102", uids[1]); Assert.AreEqual("103", uids[2]); for (int i = 0; i < 3; i++) { var uid = await client.GetMessageUidAsync(i); Assert.AreEqual(uids[i], uid); } var sizes = await client.GetMessageSizesAsync(); Assert.AreEqual(3, sizes.Count); Assert.AreEqual(1024, sizes[0]); Assert.AreEqual(1025, sizes[1]); Assert.AreEqual(1026, sizes[2]); for (int i = 0; i < 3; i++) { var size = await client.GetMessageSizeAsync(i); Assert.AreEqual(sizes[i], size); } try { var message = await client.GetMessageAsync(0); using (var jpeg = new MemoryStream()) { var attachment = message.Attachments.OfType <MimePart> ().FirstOrDefault(); attachment.ContentObject.DecodeTo(jpeg); jpeg.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { var md5sum = HexEncode(md5.ComputeHash(jpeg)); Assert.AreEqual("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match."); } } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage: {0}", ex); } try { var messages = await client.GetMessagesAsync(0, 3); foreach (var message in messages) { using (var jpeg = new MemoryStream()) { var attachment = message.Attachments.OfType <MimePart> ().FirstOrDefault(); attachment.ContentObject.DecodeTo(jpeg); jpeg.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { var md5sum = HexEncode(md5.ComputeHash(jpeg)); Assert.AreEqual("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match."); } } } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessages: {0}", ex); } try { var messages = await client.GetMessagesAsync(new [] { 0, 1, 2 }); foreach (var message in messages) { using (var jpeg = new MemoryStream()) { var attachment = message.Attachments.OfType <MimePart> ().FirstOrDefault(); attachment.ContentObject.DecodeTo(jpeg); jpeg.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { var md5sum = HexEncode(md5.ComputeHash(jpeg)); Assert.AreEqual("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match."); } } } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessages: {0}", ex); } try { var header = await client.GetMessageHeadersAsync(0); Assert.AreEqual("Test inline image", header[HeaderId.Subject]); } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageHeaders: {0}", ex); } try { var headers = await client.GetMessageHeadersAsync(0, 3); Assert.AreEqual(3, headers.Count); for (int i = 0; i < headers.Count; i++) { Assert.AreEqual("Test inline image", headers[i][HeaderId.Subject]); } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageHeaders: {0}", ex); } try { var headers = await client.GetMessageHeadersAsync(new [] { 0, 1, 2 }); Assert.AreEqual(3, headers.Count); for (int i = 0; i < headers.Count; i++) { Assert.AreEqual("Test inline image", headers[i][HeaderId.Subject]); } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageHeaders: {0}", ex); } try { using (var stream = await client.GetStreamAsync(0)) { } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetStream: {0}", ex); } try { var streams = await client.GetStreamsAsync(0, 3); Assert.AreEqual(3, streams.Count); for (int i = 0; i < 3; i++) { streams[i].Dispose(); } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetStreams: {0}", ex); } try { var streams = await client.GetStreamsAsync(new int[] { 0, 1, 2 }); Assert.AreEqual(3, streams.Count); for (int i = 0; i < 3; i++) { streams[i].Dispose(); } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetStreams: {0}", ex); } try { await client.NoOpAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in NoOp: {0}", ex); } try { await client.DeleteMessageAsync(0); } catch (Exception ex) { Assert.Fail("Did not expect an exception in DeleteMessage: {0}", ex); } try { await client.ResetAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Reset: {0}", ex); } try { await client.DeleteMessagesAsync(new [] { 0, 1, 2 }); } catch (Exception ex) { Assert.Fail("Did not expect an exception in DeleteMessages: {0}", ex); } try { await client.ResetAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Reset: {0}", ex); } try { await client.DeleteMessagesAsync(0, 3); } catch (Exception ex) { Assert.Fail("Did not expect an exception in DeleteMessages: {0}", ex); } try { await client.ResetAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Reset: {0}", ex); } try { await client.DeleteAllMessagesAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in DeleteAllMessages: {0}", ex); } try { await client.ResetAsync(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Reset: {0}", ex); } try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public async Task DisconnectFailNotConnectAsync( ) { Pop3Client pop3Client = new Pop3Client( new PlainMessagesDummyNetworkOperations( ) ); Assert.IsFalse( pop3Client.IsConnected ); await pop3Client.DisconnectAsync( ); Assert.IsFalse( pop3Client.IsConnected ); }
public async Task DisconnectOkAsync( ) { Pop3Client pop3Client = new Pop3Client( new PlainMessagesDummyNetworkOperations( ) ); Assert.IsFalse( pop3Client.IsConnected ); await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD" ); Assert.IsTrue( pop3Client.IsConnected ); await pop3Client.DisconnectAsync( ); Assert.IsFalse( pop3Client.IsConnected ); }
public async void TestGMailPop3Client() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "gmail.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "gmail.capa1.txt")); commands.Add(new Pop3ReplayCommand("AUTH PLAIN\r\n", "gmail.plus.txt")); commands.Add(new Pop3ReplayCommand("AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "gmail.auth.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "gmail.capa2.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "gmail.stat.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "gmail.retr1.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\nRETR 2\r\nRETR 3\r\n", "gmail.retr123.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "gmail.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(GMailCapa1, client.Capabilities); Assert.AreEqual(2, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH2"), "Expected SASL XOAUTH2 auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); // Note: remove the XOAUTH2 auth mechanism to force PLAIN auth client.AuthenticationMechanisms.Remove("XOAUTH2"); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(GMailCapa2, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(3, client.Count, "Expected 3 messages"); try { var message = await client.GetMessageAsync(0); using (var jpeg = new MemoryStream()) { var attachment = message.Attachments.OfType <MimePart> ().FirstOrDefault(); attachment.ContentObject.DecodeTo(jpeg); jpeg.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { var md5sum = HexEncode(md5.ComputeHash(jpeg)); Assert.AreEqual("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match."); } } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage: {0}", ex); } try { var messages = await client.GetMessagesAsync(new [] { 0, 1, 2 }); foreach (var message in messages) { using (var jpeg = new MemoryStream()) { var attachment = message.Attachments.OfType <MimePart> ().FirstOrDefault(); attachment.ContentObject.DecodeTo(jpeg); jpeg.Position = 0; using (var md5 = new MD5CryptoServiceProvider()) { var md5sum = HexEncode(md5.ComputeHash(jpeg)); Assert.AreEqual("5b1b8b2c9300c9cd01099f44e1155e2b", md5sum, "MD5 checksums do not match."); } } } } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessages: {0}", ex); } try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public async void TestLangExtension() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "lang.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "lang.capa1.txt")); commands.Add(new Pop3ReplayCommand("UTF8\r\n", "lang.utf8.txt")); commands.Add(new Pop3ReplayCommand("APOP username d99894e8445daf54c4ce781ef21331b7\r\n", "lang.auth.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "lang.capa2.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "lang.stat.txt")); commands.Add(new Pop3ReplayCommand("LANG\r\n", "lang.getlang.txt")); commands.Add(new Pop3ReplayCommand("LANG en\r\n", "lang.setlang.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "gmail.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(LangCapa1, client.Capabilities); Assert.AreEqual(2, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH2"), "Expected SASL XOAUTH2 auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); try { await client.EnableUTF8Async(); } catch (Exception ex) { Assert.Fail("Did not expect an exception in EnableUTF8: {0}", ex); } // Note: remove the XOAUTH2 auth mechanism to force PLAIN auth client.AuthenticationMechanisms.Remove("XOAUTH2"); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(LangCapa2, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(3, client.Count, "Expected 3 messages"); var languages = await client.GetLanguagesAsync(); Assert.AreEqual(6, languages.Count); Assert.AreEqual("en", languages[0].Language); Assert.AreEqual("English", languages[0].Description); Assert.AreEqual("en-boont", languages[1].Language); Assert.AreEqual("English Boontling dialect", languages[1].Description); Assert.AreEqual("de", languages[2].Language); Assert.AreEqual("Deutsch", languages[2].Description); Assert.AreEqual("it", languages[3].Language); Assert.AreEqual("Italiano", languages[3].Description); Assert.AreEqual("es", languages[4].Language); Assert.AreEqual("Espanol", languages[4].Description); Assert.AreEqual("sv", languages[5].Language); Assert.AreEqual("Svenska", languages[5].Description); await client.SetLanguageAsync("en"); try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public async void TestInvalidStateExceptions() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "comcast.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "comcast.capa1.txt")); commands.Add(new Pop3ReplayCommand("USER username\r\n", "comcast.ok.txt")); commands.Add(new Pop3ReplayCommand("PASS password\r\n", "comcast.err.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "comcast.quit.txt")); using (var client = new Pop3Client()) { Assert.Throws <ServiceNotConnectedException> (async() => await client.AuthenticateAsync("username", "password")); Assert.Throws <ServiceNotConnectedException> (async() => await client.AuthenticateAsync(new NetworkCredential("username", "password"))); Assert.Throws <ServiceNotConnectedException> (async() => await client.NoOpAsync()); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageSizesAsync()); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageSizeAsync("uid")); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageSizeAsync(0)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageUidsAsync()); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageUidAsync(0)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageAsync("uid")); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageAsync(0)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageHeadersAsync("uid")); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetMessageHeadersAsync(0)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetStreamAsync(0)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetStreamsAsync(0, 1)); Assert.Throws <ServiceNotConnectedException> (async() => await client.GetStreamsAsync(new int[] { 0 })); Assert.Throws <ServiceNotConnectedException> (async() => await client.DeleteMessageAsync("uid")); Assert.Throws <ServiceNotConnectedException> (async() => await client.DeleteMessageAsync(0)); try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(ComcastCapa1, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(31, client.ExpirePolicy); Assert.Throws <AuthenticationException> (async() => await client.AuthenticateAsync("username", "password")); Assert.IsTrue(client.IsConnected, "AuthenticationException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageSizesAsync()); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageSizeAsync("uid")); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageSizeAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageUidsAsync()); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageUidAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageAsync("uid")); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageHeadersAsync("uid")); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetMessageHeadersAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetStreamAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetStreamsAsync(0, 1)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.GetStreamsAsync(new int[] { 0 })); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.DeleteMessageAsync("uid")); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); Assert.Throws <ServiceNotAuthenticatedException> (async() => await client.DeleteMessageAsync(0)); Assert.IsTrue(client.IsConnected, "ServiceNotAuthenticatedException should not cause a disconnect."); try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public async void TestExchangePop3Client() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "exchange.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "exchange.capa.txt")); commands.Add(new Pop3ReplayCommand("AUTH PLAIN\r\n", "exchange.plus.txt")); commands.Add(new Pop3ReplayCommand("AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "exchange.auth.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "exchange.capa.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "exchange.stat.txt")); commands.Add(new Pop3ReplayCommand("UIDL\r\n", "exchange.uidl.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "exchange.retr1.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "exchange.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false)); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(ExchangeCapa, client.Capabilities); Assert.AreEqual(3, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("GSSAPI"), "Expected SASL GSSAPI auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("NTLM"), "Expected SASL NTLM auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); // Note: remove these auth mechanisms to force PLAIN auth client.AuthenticationMechanisms.Remove("GSSAPI"); client.AuthenticationMechanisms.Remove("NTLM"); try { await client.AuthenticateAsync("username", "password"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(ExchangeCapa, client.Capabilities); Assert.AreEqual(3, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("GSSAPI"), "Expected SASL GSSAPI auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("NTLM"), "Expected SASL NTLM auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); Assert.AreEqual(7, client.Count, "Expected 7 messages"); try { var uids = await client.GetMessageUidsAsync(); Assert.AreEqual(7, uids.Count, "Expected 7 uids"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageUids: {0}", ex); } try { var message = await client.GetMessageAsync(0); // TODO: assert that the message is byte-identical to what we expect } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage: {0}", ex); } try { await client.DisconnectAsync(true); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
private async Task TestEmailConnect(string email_address, string login_user, string pass_user, string pop3_server_address, string smtp_server_address, Switch switchToggler) { Regex regexServerPort = new Regex(@":\d+$"); int smtp_server_port; Match matchServerPort = regexServerPort.Match(smtp_server_address); if (!matchServerPort.Success) { RunOnUiThread(() => { switchToggler.Checked = false; Toast.MakeText(this, GetText(Resource.String.error_cloud_email_smtp_port), ToastLength.Long).Show(); }); goto Finish; } smtp_server_port = int.Parse(matchServerPort.Value.Substring(1)); smtp_server_address = smtp_server_address.Substring(0, smtp_server_address.Length - matchServerPort.Value.Length); int pop3_server_port; matchServerPort = regexServerPort.Match(pop3_server_address); if (!matchServerPort.Success) { RunOnUiThread(() => { switchToggler.Checked = false; Toast.MakeText(this, GetText(Resource.String.error_cloud_email_pop3_port), ToastLength.Long).Show(); }); goto Finish; } pop3_server_port = int.Parse(matchServerPort.Value.Substring(1)); pop3_server_address = pop3_server_address.Substring(0, pop3_server_address.Length - matchServerPort.Value.Length); MimeMessage emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress(email_address, email_address)); emailMessage.To.Add(new MailboxAddress(email_address, email_address)); emailMessage.Subject = GetType().Name; emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Text) { Text = nameof(TestEmailConnect) }; using (SmtpClient client = new SmtpClient()) { try { await client.ConnectAsync(smtp_server_address, smtp_server_port, true); await client.AuthenticateAsync(login_user, pass_user); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); RunOnUiThread(() => { Toast.MakeText(this, GetText(Resource.String.cloud_connection_smtp_successfully), ToastLength.Short).Show(); }); } catch (Exception e) { RunOnUiThread(() => { switchToggler.Checked = false; Toast.MakeText(this, $"{GetText(Resource.String.error_connecting_smtp_cloud)}{System.Environment.NewLine}{e.Message}", ToastLength.Long).Show(); switchToggler.Enabled = true; (switchToggler.Parent as LinearLayout).RemoveViewAt(1); }); return; } } using (Pop3Client client = new Pop3Client()) { try { await client.ConnectAsync(pop3_server_address, pop3_server_port, SecureSocketOptions.SslOnConnect); await client.AuthenticateAsync(login_user, pass_user); if (!client.Capabilities.HasFlag(Pop3Capabilities.UIDL)) { throw new Exception("The POP3 server does not support UIDL!"); } //System.Collections.Generic.IList<string> uids = client.GetMessageUids(); //for (int i = 0; i < client.Count; i++) //{ // check that we haven't already downloaded this message // in a previous session //if (previouslyDownloadedUids.Contains(uids[i])) // continue; //MimeMessage message = client.GetMessage(i); // write the message to a file //message.WriteTo(string.Format("{0}.msg", uids[i])); // add the message uid to our list of downloaded uids //previouslyDownloadedUids.Add(uids[i]); //} await client.DisconnectAsync(true); RunOnUiThread(() => { Toast.MakeText(this, GetText(Resource.String.cloud_connection_pop3_successfully), ToastLength.Short).Show(); }); } catch (Exception e) { RunOnUiThread(() => { switchToggler.Checked = false; Toast.MakeText(this, $"{GetText(Resource.String.error_connecting_pop3_cloud)}{System.Environment.NewLine}{e.Message}", ToastLength.Long).Show(); switchToggler.Enabled = true; (switchToggler.Parent as LinearLayout).RemoveViewAt(1); }); return; } } Finish: switchToggler.Enabled = true; (switchToggler.Parent as LinearLayout).RemoveViewAt(1); }