Exemple #1
0
        public async Task <List <EmailMessage> > ReceiveEmail(int maxCount = 10)
        {
            if (_config.MailServiceActive)
            {
                using var pop3Client = new Pop3Client();
                await pop3Client.ConnectAsync(_config.PopServer, _config.PopPort, _config.EnableSsl);

                await pop3Client.AuthenticateAsync(_config.PopUsername, _config.PopPassword);

                List <EmailMessage> emails = new List <EmailMessage>();
                for (int i = 0; i < pop3Client.Count && i < maxCount; i++)
                {
                    var message = await pop3Client.GetMessageAsync(i);

                    var emailMessage = new EmailMessage
                    {
                        Body    = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                        Subject = message.Subject
                    };
                    emailMessage.To.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                    emailMessage.From.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                    emails.Add(emailMessage);
                }
                return(emails);
            }
            else
            {
                return(new List <EmailMessage>());
            }
        }
        public async Task <Models.MailMessage[]> ReceiveAsync()
        {
            try
            {
                using Pop3Client emailClient = new Pop3Client();

                await emailClient.ConnectAsync(_serverAddress, _port, false).ConfigureAwait(false);

                //emailClient.AuthenticationMechanisms.Add("USER/PASS");
                await emailClient.AuthenticateAsync(_username, _password);

                int totalMessages = await emailClient.GetMessageCountAsync().ConfigureAwait(false);

                IList <Models.MailMessage> emails = new List <Models.MailMessage>();

                for (int i = 0; i < 50 && i < totalMessages; i++)
                {
                    MimeMessage message = await emailClient.GetMessageAsync(i).ConfigureAwait(false);

                    emails.Add(new Models.MailMessage()
                    {
                        Body    = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                        Subject = message.Subject,
                        To      = message.To.Select(x => (MailboxAddress)x).Select(x => x.Address).First(),
                        From    = message.From.Select(x => (MailboxAddress)x).Select(x => x.Address).First()
                    });
                }

                return(emails.ToArray());
            }
            catch { }

            return(null);
        }
Exemple #3
0
        public async Task <List <EmailMessage> > ReceiveEmail(EmailSettings emailSettings, int maxCount = 10)
        {
            using (Pop3Client emailClient = new Pop3Client())
            {
                await emailClient.ConnectAsync(emailSettings.PopServer, emailSettings.PopPort, true).ConfigureAwait(true);

                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                await emailClient.AuthenticateAsync(emailSettings.PopUsername, emailSettings.PopPassword).ConfigureAwait(true);

                List <EmailMessage> emails = new List <EmailMessage>();

                for (int i = 0; i < emailClient.Count && i < maxCount; i++)
                {
                    MimeMessage message = await emailClient.GetMessageAsync(i).ConfigureAwait(true);

                    EmailMessage emailMessage = new EmailMessage
                    {
                        Content = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                        Subject = message.Subject
                    };

                    emailMessage.ToAddresses.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                    emailMessage.FromAddresses.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                }

                return(emails);
            }
        }
Exemple #4
0
        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");
            }
        }
        // Method which will connect using POP and save attachments to specified folder
        async public Task <ImapClient> SaveAttachmentsPOPAsync(System.Threading.CancellationToken token)
        {
            using (popClient = new Pop3Client()) // Use POP client
            {
                // Verify all certificates
                popClient.ServerCertificateValidationCallback = (s, c, h, e) => true;

                try
                {
                    logger.Info("Connecting to " + email);
                    await popClient.ConnectAsync(host, port, SSL, token);  // Try to connect to email host

                    await popClient.AuthenticateAsync(email, pass, token); // Try to authenticate Username/Password/Hostname

                    logger.Info("Connected to " + email);
                    logger.Info("Sychronization Started...");

                    while (true)
                    {
                        for (int i = 0; i < popClient.Count; i++)                                                      // For every email found in POP server
                        {
                            var message = await popClient.GetMessageAsync(i, token);                                   // Get the message object of speicifed email

                            foreach (var attachment in message.Attachments)                                            // For every attachment found in Message
                            {
                                var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name; // Get the name of attachment
                                using (var stream = File.Create(directory + Path.DirectorySeparatorChar + fileName))   // Create empty file with same name as we found in attachment
                                {
                                    if (attachment is MessagePart)                                                     // If attachment is MessagePart
                                    {
                                        var part = (MessagePart)attachment;                                            // Cast attachment to MessagePart
                                        logger.Trace("Found -> " + fileName);
                                        await part.Message.WriteToAsync(stream, token);                                // Download attachment using stream
                                    }
                                    else // If attachment is MimePart
                                    {
                                        var part = (MimePart)attachment;                 // Cast attachment to MimePart Object
                                        logger.Trace("Found -> " + fileName);
                                        await part.Content.DecodeToAsync(stream, token); // Download attachment using stream
                                    }
                                }
                            }
                        }
                    }
                }
                catch (System.Net.Sockets.SocketException) // Check for any internet connectivity errors
                {
                    throw;
                }
                catch (MailKit.Security.AuthenticationException) // Check for invalid Username/Password/Hostname
                {
                    throw;
                }
            }
        }
        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));
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Загрузим сообщения
        /// </summary>
        /// <param name="mailBox"></param>
        /// <param name="client"></param>
        /// <returns></returns>
        private async Task LoadMessagesAsync(IMailBox mailBox, Pop3Client client)
        {
            var count = client.Count;

            for (var i = count - 1; i > 0; i--)
            {
                var message = await client.GetMessageAsync(i);

                // только такая проверка т.к. в POP3 без вариантов
                if (await MustBeSavedAsync(mailBox, message))
                {
                    await SaveMessageAsync(mailBox, message);

                    continue;
                }
                //если письмо сохранять не нужно то сразу выходим
                break;
            }
        }
Exemple #8
0
        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");
            }
        }
Exemple #9
0
        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");
            }
        }
Exemple #10
0
        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");
            }
        }
Exemple #11
0
        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");
            }
        }