Пример #1
0
        public void TestArgumentExceptions()
        {
            using (var client = new Pop3Client()) {
                var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

                // Connect
                Assert.Throws <ArgumentNullException> (() => client.Connect((Uri)null));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync((Uri)null));
                Assert.Throws <ArgumentNullException> (() => client.Connect(null, 110, false));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync(null, 110, false));
                Assert.Throws <ArgumentException> (() => client.Connect(string.Empty, 110, false));
                Assert.Throws <ArgumentException> (async() => await client.ConnectAsync(string.Empty, 110, 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, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync(null, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (() => client.Connect(string.Empty, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (async() => await client.ConnectAsync(string.Empty, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentOutOfRangeException> (() => client.Connect("host", -1, SecureSocketOptions.None));
                Assert.Throws <ArgumentOutOfRangeException> (async() => await client.ConnectAsync("host", -1, SecureSocketOptions.None));

                Assert.Throws <ArgumentNullException> (() => client.Connect(null, "host", 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (() => client.Connect(socket, "host", 110, 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));
            }
        }
Пример #2
0
        /// <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);
        }
Пример #3
0
        // Method which only tests the POP connection to email host
        async internal Task ConnectPOPAsync()
        {
            using (popClient = new Pop3Client())
            {
                // Veriy all certficates
                popClient.ServerCertificateValidationCallback = (s, c, h, e) => true;

                try
                {
                    logger.Info("Testing Connection to " + email);
                    await popClient.ConnectAsync(host, port, SSL);  // Try to connect using POP protocol

                    await popClient.AuthenticateAsync(email, pass); // Try to Authenticate the Username/Password

                    logger.Info("Successfully Connected to " + email);
                }
                catch (System.Net.Sockets.SocketException) // Catch any internet connectivity errors
                {
                    logger.Error("Internet Connectivity Issue");
                }
                catch (MailKit.Security.AuthenticationException) // Catch invalid Usernam/Password/Hostname errors
                {
                    logger.Error("Wrong Username/Password/Host");
                }
            }
        }
Пример #4
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);
            }
        }
Пример #5
0
        public async Task <List <EmailMessage> > RecieveEmailAsync(int maxCount = 10)
        {
            using (var emailClient = new Pop3Client())
            {
                await emailClient.ConnectAsync(_emailConfiguration.PopServer, _emailConfiguration.PopPort, true);

                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                await emailClient.AuthenticateAsync(_emailConfiguration.PopUsername, _emailConfiguration.PopPassword);

                List <EmailMessage> emails = new List <EmailMessage>();
                for (int i = 0; i < emailClient.Count && i < maxCount; i++)
                {
                    var message      = emailClient.GetMessage(i);
                    var 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 {
                        Email = x.Address, FullName = x.Name
                    }));
                    emailMessage.FromAddresses.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Email = x.Address, FullName = x.Name
                    }));
                    emails.Add(emailMessage);
                }

                return(emails);
            }
        }
Пример #6
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>());
            }
        }
Пример #7
0
        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);
        }
Пример #8
0
        public async Task <GetResult <IReadOnlyList <Packet> > > GetPacketsAsync(ClientConfiguration clientConfiguration = null)
        {
            var getResult = new GetResult <IReadOnlyList <Packet> >();
            var userName  = clientConfiguration == null ? _configuration.PopUsername : clientConfiguration.UserName;
            var password  = clientConfiguration == null ? _configuration.PopPassword : clientConfiguration.Password;

            try
            {
                using (var emailClient = new Pop3Client())
                {
                    emailClient.Connect(_configuration.PopServer, _configuration.PopPort, true);
                    await emailClient.AuthenticateAsync(userName, password);

                    var list = new List <Packet>();
                    for (var i = 0; i < emailClient.Count; i++)
                    {
                        var message = emailClient.GetMessage(i);
                        var packet  = new Packet()
                        {
                            Message = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                            Topic   = message.Subject
                        };

                        // Check for attachments
                        if (message.Attachments.Any())
                        {
                            foreach (var attachment in message.Attachments)
                            {
                                var part = (MimePart)attachment;

                                using (var stream = new MemoryStream())
                                {
                                    part.Content.DecodeTo(stream);
                                    packet.Data = stream.ToArray();
                                }
                            }
                        }

                        list.Add(packet);
                        emailClient.DeleteMessage(i);
                    }

                    getResult.Content   = list;
                    getResult.Succeeded = true;
                    emailClient.Disconnect(true);
                }
            }
            catch (Exception e)
            {
                _logManager.LogError(e, $@"EmailProvider.GetPacketAsync");
                getResult.Succeeded = false;
                getResult.Errors.Add(new CommunicationError
                {
                    Code        = e.HResult.ToString(),
                    Description = e.Message
                });
            }
            return(getResult);
        }
Пример #9
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");
            }
        }
Пример #10
0
        private async Task SetupConnectToEmailServerAndAuthenticate(EmailConfiguration emailConfig, Pop3Client emailClient, string emailServerInfo)
        {
            emailClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
            await emailClient.ConnectAsync(emailConfig.PopServerHost, emailConfig.PopServerPort, SecureSocketOptions.Auto);

            emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
            Dependencies.DiagnosticLogging.Verbose("MailCollection: Authenticating to email server {emailServerInfo}, : Username: [{Username}]", emailServerInfo, emailConfig.Username);
            await emailClient.AuthenticateAsync(emailConfig.Username, emailConfig.Password);
        }
Пример #11
0
    private async Task <Pop3Client> CreateClientAsync()
    {
        var pop3Client = new Pop3Client();
        await pop3Client.ConnectAsync(MailHostOptions.Pop3163EnterpriseHost, MailHostOptions.Pop3163EnterprisePort);

        await pop3Client.AuthenticateAsync(MailHostOptions.Enterprise163Account,
                                           MailHostOptions.Enterprise163Password);

        return(pop3Client);
    }
Пример #12
0
        // 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;
                }
            }
        }
Пример #13
0
        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));
                }
            }
        }
Пример #14
0
        //public bool valid { get; set; }

        async public static Task <User> authenticate(String email, String password)
        {
            SmtpClient sendingClient   = new SmtpClient();
            Pop3Client receivingClient = new Pop3Client();

            await sendingClient.ConnectAsync("smtp.gmail.com", 465, true);

            await sendingClient.AuthenticateAsync(StrUtil.removeDomain(email), password);

            await receivingClient.ConnectAsync("pop.gmail.com", 995, true);

            await receivingClient.AuthenticateAsync(StrUtil.removeDomain(email), password);

            sendingClient.Disconnect(true);
            receivingClient.Disconnect(true);

            return(new User(email, password));
        }
Пример #15
0
        public async Task <Pop3Client> CreateClientAndConnect()
        {
            try
            {
                var pop3Client = new Pop3Client();
                var data       = GetData();
                pop3Client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                await pop3Client.ConnectAsync(data.Server, data.Port, data.SSL);

                await pop3Client.AuthenticateAsync(data.Username, data.Password);

                return(pop3Client.IsConnected && pop3Client.IsAuthenticated? pop3Client : null);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Пример #16
0
        public static async Task <bool> AcceptConfirm(string mail, string pass)
        {
            return(await Task.Run(async() =>
            {
                try
                {
                    using (var client = new Pop3Client())
                    {
                        await client.ConnectAsync("pop.mail.yahoo.com", 995, true);

                        // Note: since we don't have an OAuth2 token, disable
                        // the XOAUTH2 authentication mechanism.
                        client.AuthenticationMechanisms.Remove("XOAUTH2");
                        await client.AuthenticateAsync(mail, pass);

                        var msgs = await client.GetMessagesAsync(0, client.Count);
                        var confMess = msgs.First(x => x.Subject.Contains("Quora Account Confirmation"));

                        if (confMess == null)
                        {
                            return false;
                        }

                        var link = Regex.Match(confMess.HtmlBody, @"(?=https).+(?=\"")").Value;
                        Utils.GetRequest.Get(link).None();

                        await client.DeleteAllMessagesAsync();
                        client.Disconnect(true);
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    //Informer.RaiseOnResultReceived(ex.Message);
                    return false;
                }
            }));
        }
Пример #17
0
        /// <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);
            }
        }
Пример #18
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");
            }
        }
Пример #19
0
        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");
            }
        }
Пример #20
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");
            }
        }
Пример #21
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");
            }
        }
Пример #22
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");
            }
        }
Пример #23
0
        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);
        }