public async Task ConnectAlreadyConnectAsync()
        {
            Pop3Client pop3Client = new Pop3Client(new PlainMessagesDummyNetworkOperations());

            Assert.IsFalse(pop3Client.IsConnected);

            await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD", true);

            Assert.IsTrue(pop3Client.IsConnected);

            await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD", 995, true);
        }
Esempio n. 2
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>());
            }
        }
        // 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");
                }
            }
        }
Esempio n. 4
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);
        }
Esempio n. 5
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);
            }
        }
        public async Task ListAndRetrieveHeaderOkAsync()
        {
            Pop3Client pop3Client = new Pop3Client(new OnlyHeadersDummyNetworkOperations());

            await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD");

            IEnumerable <Pop3Message> result = await pop3Client.ListAndRetrieveHeaderAsync();

            List <Pop3Message> messages = new List <Pop3Message>(result);;

            Assert.IsFalse(messages[0].Retrieved);
            Assert.IsNotNull(messages[0].RawHeader);
            Assert.IsNull(messages[0].RawMessage);
            Assert.AreEqual("Rodolfo Finochietti <*****@*****.**>", messages[0].From);
            Assert.AreEqual("\"[email protected]\" <*****@*****.**>", messages[0].To);
            Assert.AreEqual("Tue, 13 Nov 2012 10:57:04 -0500", messages[0].Date);
            Assert.AreEqual("<*****@*****.**>", messages[0].MessageId);
            Assert.AreEqual("quoted-printable", messages[0].ContentTransferEncoding);
            Assert.IsNull(messages[0].Body);
            Assert.AreEqual("1.0", messages[0].GetHeaderData("MIME-Version"));
            Assert.AreEqual("by 10.112.163.194 with SMTP id yk2csp334265lbb;\r\nTue, 13 Nov 2012 07:57:16 -0800 (PST)", messages[0].GetHeaderData("Received"));
            Assert.AreEqual("Ac3Bt4nMDtM3y3FyQ1yd71JVtsSGJQ==", messages[0].GetHeaderData("Thread-Index"));
            Assert.IsFalse(messages[1].Retrieved);
            Assert.IsNotNull(messages[1].RawHeader);
            Assert.IsNull(messages[1].RawMessage);
            Assert.AreEqual("Rodolfo Finochietti <*****@*****.**>", messages[1].From);
            Assert.AreEqual("\"[email protected]\" <*****@*****.**>", messages[1].To);
            Assert.AreEqual("Tue, 13 Nov 2012 10:57:28 -0500", messages[1].Date);
            Assert.AreEqual("<*****@*****.**>", messages[1].MessageId);
            Assert.AreEqual("Test 2", messages[1].Subject);
            Assert.AreEqual("base64", messages[1].ContentTransferEncoding);
            Assert.IsNull(messages[1].Body);
            Assert.AreEqual("Microsoft-MacOutlook/14.2.4.120824", messages[1].GetHeaderData("user-agent:"));
            Assert.AreEqual(String.Empty, messages[1].GetHeaderData("X-MS-Has-Attach:"));
        }
Esempio n. 7
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);
            }
        }
Esempio n. 8
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);
        }
        public async Task ConnectFailAsync()
        {
            Pop3Client pop3Client = new Pop3Client(new DummyNetworkOperations("-ERR"));

            Assert.IsFalse(pop3Client.IsConnected);

            await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD", true);
        }
Esempio n. 10
0
        public async Task ConnectFailNotResponseAsync()
        {
            Pop3Client pop3Client = new Pop3Client(new DummyNetworkOperations(null));

            Assert.IsFalse(pop3Client.IsConnected);

            await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD");
        }
Esempio n. 11
0
        public async Task SendCommandFailNullResponseAsync()
        {
            Pop3Client pop3Client = new Pop3Client(new QueueDummyNetworkOperations("+OK", String.Empty));

            Assert.IsFalse(pop3Client.IsConnected);

            await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD", false);
        }
Esempio n. 12
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));
            }
        }
Esempio n. 13
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);
        }
Esempio n. 14
0
        /// <summary>
        /// Check the import mailbox.  Returns the first CSV file in the mailbox.
        /// </summary>
        /// <returns></returns>
        public async Task CheckMailBoxForImport(PerformContext hangfireContext)
        {
            Pop3Client pop3Client = new Pop3Client();
            await pop3Client.ConnectAsync(Configuration["SPD_IMPORT_POP3_SERVER"],
                                          Configuration["SPD_IMPORT_POP3_USERNAME"],
                                          Configuration["SPD_IMPORT_POP3_PASSWORD"], true);

            List <Pop3Message> messages = (await pop3Client.ListAndRetrieveAsync()).ToList();

            foreach (Pop3Message message in messages)
            {
                var attachments = message.Attachments.ToList();
                if (attachments.Count > 0)
                {
                    // string payload = null; // File.ReadAllText("C:\\tmp\\testimport.csv");

                    string payload = Encoding.Default.GetString(attachments[0].GetData());
                    if (payload != null) // parse the payload
                    {
                        List <WorkerResponse> responses = WorkerResponseParser.ParseWorkerResponse(payload);
                        foreach (WorkerResponse workerResponse in responses)
                        {
                            // search for the Personal History Record.
                            MicrosoftDynamicsCRMadoxioPersonalhistorysummary record = _dynamics.Personalhistorysummaries.GetByWorkerJobNumber(workerResponse.RecordIdentifier);

                            if (record != null)
                            {
                                // update the record.
                                MicrosoftDynamicsCRMadoxioPersonalhistorysummary patchRecord = new MicrosoftDynamicsCRMadoxioPersonalhistorysummary()
                                {
                                    AdoxioSecuritystatus = SPDResultTranslate.GetTranslatedSecurityStatus(workerResponse.Result),
                                    AdoxioCompletedon    = workerResponse.DateProcessed
                                };

                                try
                                {
                                    _dynamics.Personalhistorysummaries.Update(record.AdoxioPersonalhistorysummaryid, patchRecord);
                                }
                                catch (OdataerrorException odee)
                                {
                                    hangfireContext.WriteLine("Error updating worker personal history");
                                    hangfireContext.WriteLine("Request:");
                                    hangfireContext.WriteLine(odee.Request.Content);
                                    hangfireContext.WriteLine("Response:");
                                    hangfireContext.WriteLine(odee.Response.Content);
                                }
                            }
                        }
                    }
                }

                await pop3Client.DeleteAsync(message);

                hangfireContext.WriteLine("Deleted message:");
            }
        }
Esempio n. 15
0
        public async Task ConnectOkAsync( )
        {
            Pop3Client pop3Client = new Pop3Client(new FullMessagesDummyNetworkOperations( ));

            Assert.IsFalse(pop3Client.IsConnected);

            await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD");

            Assert.IsTrue(pop3Client.IsConnected);
        }
Esempio n. 16
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);
    }
Esempio n. 17
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;
                }
            }
        }
Esempio n. 18
0
        public async Task DeleteFailNullArgumentAsync()
        {
            Pop3Client pop3Client = new Pop3Client(new DummyNetworkOperations("+OK"));

            Assert.IsFalse(pop3Client.IsConnected);

            await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD", true);

            Assert.IsTrue(pop3Client.IsConnected);

            await pop3Client.DeleteAsync(null);
        }
Esempio n. 19
0
        public async Task DeleteOkAsync()
        {
            Pop3Client pop3Client = new Pop3Client(new DummyNetworkOperations("+OK"));

            Assert.IsFalse(pop3Client.IsConnected);

            await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD", false);

            await pop3Client.DeleteAsync(new Pop3Message()
            {
                Number = 1
            });
        }
        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));
                }
            }
        }
Esempio n. 21
0
        public async Task ListOkAsync()
        {
            Pop3Client pop3Client = new Pop3Client(new PlainMessagesDummyNetworkOperations());

            await pop3Client.ConnectAsync("SERVER", "USERNAME", "PASSWORD", 995, true);

            IEnumerable <Pop3Message> result = await pop3Client.ListAsync();

            List <Pop3Message> messages = new List <Pop3Message>(result);

            Assert.AreEqual(2, messages.Count);
            Assert.AreEqual(1, messages[0].Number);
            Assert.AreEqual(1586, messages[0].Bytes);
            Assert.IsFalse(messages[0].Retrieved);
            Assert.AreEqual(2, messages[1].Number);
            Assert.AreEqual(1584, messages[1].Bytes);
            Assert.IsFalse(messages[1].Retrieved);
        }
Esempio n. 22
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));
        }
        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);
            }
        }
Esempio n. 24
0
        private async Task <IMailClient> GetClientAsync(string type, string host, int port, bool ssl, string username, string password)
        {
            if ("imap".Equals(type, StringComparison.OrdinalIgnoreCase))
            {
                ImapClient client = new ImapClient(ImapClient.AuthMethods.Login);
                await client.ConnectAsync(host, username, password, port, ssl);

                return(client);
            }

            if ("pop3".Equals(type, StringComparison.OrdinalIgnoreCase))
            {
                Pop3Client client = new Pop3Client();
                await client.ConnectAsync(host, username, password, port, ssl);

                return(client);
            }

            throw new NotImplementedException(type + " is not implemented");
        }
Esempio n. 25
0
        public static async Task GetMessagesAsync(string server, string userName, string password, bool useSsl)
        {
            try
            {
                using (Pop3Client pop3Client = new Pop3Client())
                {
                    Console.WriteLine("Connecting to POP3 server '{0}'...{1}", server, Environment.NewLine);

                    await pop3Client.ConnectAsync(server, userName, password, useSsl);

                    Console.WriteLine("List and Retrieve Messages...{0}", Environment.NewLine);

                    IEnumerable <Pop3Message> messages = await pop3Client.ListAndRetrieveAsync();

                    foreach (Pop3Message message in messages)
                    {
                        Console.WriteLine("- Number: {0}", message.Number);
                        Console.WriteLine("\t* MessageId: {0}", message.MessageId);
                        Console.WriteLine("\t* Date: {0}", message.Date);
                        Console.WriteLine("\t* From: {0}", message.From);
                        Console.WriteLine("\t* To: {0}", message.To);
                        Console.WriteLine("\t* Subject: {0}", message.Subject);
                        Console.WriteLine("\t* Retrieved: {0}", message.Retrieved);
                        Console.WriteLine("\t* Body Length: {0}", message.Body.Length);
                        Console.WriteLine("\t* Attachments Count: {0}", ((List <Pop3Attachment>)message.Attachments).Count);
                        Console.WriteLine();
                    }

                    Console.WriteLine("Disconnecting...{0}", Environment.NewLine);
                    //await pop3Client.DisconnectAsync();
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
Esempio n. 26
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;
                }
            }));
        }
Esempio n. 27
0
        public static async Task GetMessagesAsync( string server, string userName, string password, bool useSsl )
        {
            try
            {
                Pop3Client pop3Client = new Pop3Client( );

                Console.WriteLine( "Connecting to POP3 server '{0}'...{1}", server, Environment.NewLine );

                await pop3Client.ConnectAsync( server, userName, password, useSsl );

                Console.WriteLine( "List and Retrieve Messages...{0}", Environment.NewLine );

                IEnumerable<Pop3Message> messages = await pop3Client.ListAndRetrieveAsync( );

                foreach ( Pop3Message message in messages )
                {
                    Console.WriteLine( "- Number: {0}", message.Number );
                    Console.WriteLine( "\t* MessageId: {0}", message.MessageId );
                    Console.WriteLine( "\t* Date: {0}", message.Date );
                    Console.WriteLine( "\t* From: {0}", message.From );
                    Console.WriteLine( "\t* To: {0}", message.To );
                    Console.WriteLine( "\t* Subject: {0}", message.Subject );
                    Console.WriteLine( "\t* Retrieved: {0}", message.Retrieved );
                    Console.WriteLine( "\t* Body Length: {0}", message.Body.Length );
                    Console.WriteLine( "\t* Attachments Count: {0}", ((List<Pop3Attachment>)message.Attachments).Count );
                    Console.WriteLine( );
                }

                Console.WriteLine( "Disconnecting...{0}", Environment.NewLine );
                await pop3Client.DisconnectAsync( );
            }
            catch ( Exception ex )
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine( ex.Message );
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
Esempio n. 28
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);
            }
        }
Esempio n. 29
0
        public async Task DeleteFailNullArgumentAsync( )
        {
            Pop3Client pop3Client = new Pop3Client( new DummyNetworkOperations( "+OK" ) );
            Assert.IsFalse( pop3Client.IsConnected );

            await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD", true );
            Assert.IsTrue( pop3Client.IsConnected );

            await pop3Client.DeleteAsync( null );
        }
Esempio n. 30
0
        public async Task ConnectAlreadyConnectAsync( )
        {
            Pop3Client pop3Client = new Pop3Client( new FullMessagesDummyNetworkOperations( ) );
            Assert.IsFalse( pop3Client.IsConnected );

            await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD", true );
            Assert.IsTrue( pop3Client.IsConnected );

            await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD", 995, true );
        }
Esempio n. 31
0
        public async Task ConnectFailAsync( )
        {
            Pop3Client pop3Client = new Pop3Client( new DummyNetworkOperations( "-ERR" ) );
            Assert.IsFalse( pop3Client.IsConnected );

            await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD", true );
        }
Esempio n. 32
0
        public async Task ConnectFailNotResponseAsync( )
        {
            Pop3Client pop3Client = new Pop3Client( new DummyNetworkOperations( null ) );
            Assert.IsFalse( pop3Client.IsConnected );

            await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD" );
        }
Esempio n. 33
0
        public async Task DisconnectOkAsync( )
        {
            Pop3Client pop3Client = new Pop3Client( new PlainMessagesDummyNetworkOperations( ) );
            Assert.IsFalse( pop3Client.IsConnected );

            await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD" );
            Assert.IsTrue( pop3Client.IsConnected );

            await pop3Client.DisconnectAsync( );
            Assert.IsFalse( pop3Client.IsConnected );
        }
Esempio n. 34
0
        public async Task ListOkAsync( )
        {
            Pop3Client pop3Client = new Pop3Client( new PlainMessagesDummyNetworkOperations( ) );

            await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD", 995, true );

            IEnumerable<Pop3Message> result = await pop3Client.ListAsync( );
            List<Pop3Message> messages = new List<Pop3Message>( result );

            Assert.AreEqual( 2, messages.Count );
            Assert.AreEqual( 1, messages[ 0 ].Number );
            Assert.AreEqual( 1586, messages[ 0 ].Bytes );
            Assert.IsFalse( messages[ 0 ].Retrieved );
            Assert.AreEqual( 2, messages[ 1 ].Number );
            Assert.AreEqual( 1584, messages[ 1 ].Bytes );
            Assert.IsFalse( messages[ 1 ].Retrieved );
        }
Esempio n. 35
0
        public async Task RetrieveHeaderListOkAsync( )
        {
            Pop3Client pop3Client = new Pop3Client( new OnlyHeadersDummyNetworkOperations( ) );

            await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD" );

            IEnumerable<Pop3Message> result = await pop3Client.ListAsync( );
            List<Pop3Message> messages = new List<Pop3Message>( result );

            await pop3Client.RetrieveHeaderAsync( messages );
            Assert.IsFalse( messages[ 0 ].Retrieved );
            Assert.IsNotNull( messages[ 0 ].RawHeader );
            Assert.IsNull( messages[ 0 ].RawMessage );
            Assert.AreEqual( "Rodolfo Finochietti <*****@*****.**>", messages[ 0 ].From );
            Assert.AreEqual( "\"[email protected]\" <*****@*****.**>", messages[ 0 ].To );
            Assert.AreEqual( "Tue, 13 Nov 2012 10:57:04 -0500", messages[ 0 ].Date );
            Assert.AreEqual( "<*****@*****.**>", messages[ 0 ].MessageId );
            Assert.AreEqual( "Test 1", messages[ 0 ].Subject );
            Assert.AreEqual( "quoted-printable", messages[ 0 ].ContentTransferEncoding );
            Assert.IsNull( messages[ 0 ].Body );
            Assert.AreEqual( "1.0", messages[ 0 ].GetHeaderData( "MIME-Version" ) );
            Assert.AreEqual( "Ac3Bt4nMDtM3y3FyQ1yd71JVtsSGJQ==", messages[ 0 ].GetHeaderData( "Thread-Index" ) );
            Assert.IsFalse( messages[ 1 ].Retrieved );
            Assert.IsNotNull( messages[ 1 ].RawHeader );
            Assert.IsNull( messages[ 1 ].RawMessage );
            Assert.AreEqual( "Rodolfo Finochietti <*****@*****.**>", messages[ 1 ].From );
            Assert.AreEqual( "\"[email protected]\" <*****@*****.**>", messages[ 1 ].To );
            Assert.AreEqual( "Tue, 13 Nov 2012 10:57:28 -0500", messages[ 1 ].Date );
            Assert.AreEqual( "<*****@*****.**>", messages[ 1 ].MessageId );
            Assert.AreEqual( "Test 2", messages[ 1 ].Subject );
            Assert.AreEqual( "base64", messages[ 1 ].ContentTransferEncoding );
            Assert.IsNull( messages[ 1 ].Body );
            Assert.AreEqual( "Microsoft-MacOutlook/14.2.4.120824", messages[ 1 ].GetHeaderData( "user-agent:" ) );
            Assert.AreEqual( String.Empty, messages[ 1 ].GetHeaderData( "X-MS-Has-Attach:" ) );
        }
Esempio n. 36
0
        public async Task DeleteOkAsync( )
        {
            Pop3Client pop3Client = new Pop3Client( new DummyNetworkOperations( "+OK" ) );
            Assert.IsFalse( pop3Client.IsConnected );

            await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD", false );

            await pop3Client.DeleteAsync( new Pop3Message( ) { Number = 1 } );
        }
Esempio n. 37
0
        public async Task SendCommandFailNullResponseAsync( )
        {
            Pop3Client pop3Client = new Pop3Client( new QueueDummyNetworkOperations( "+OK", String.Empty ) );
            Assert.IsFalse( pop3Client.IsConnected );

            await pop3Client.ConnectAsync( "SERVER", "USERNAME", "PASSWORD", false );
        }
Esempio n. 38
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);
        }