Beispiel #1
0
        /// <summary>
        /// 连接到IMAP服务器
        /// </summary>
        private ImapClient ConnectIMAP()
        {
            try
            {
                ImapClient client = new ImapClient();
                client.Connect(serverIMAP, portIMAP);
                client.Authenticate(account, pwd);

                /**********************************************************************/
                // 网易126 163相关邮箱时,要用这两句话,表明客户端身份.在连接后调用.否则无法登录邮箱.
                var clientImplementation = new ImapImplementation
                {
                    Name    = "MeSince",
                    Version = "2.0"
                };
                var serverImplementation = client.Identify(clientImplementation);
                /*********************************************************************/

                return(client);
            }
            catch (Exception e)
            {
                ErrMsg = $"连接到IMAP服务器异常:{e.ToString()} [{e.Message}]";
                return(null);
            }
        }
Beispiel #2
0
        private static void RetrievingMessagesWithIMAP()
        {
            using (var client = new ImapClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Connect("imap.163.com", 993, true);
                client.Authenticate(FromAddress, FromPassword);

                var clientImplementation = new ImapImplementation
                {
                    Name    = "MailKitDemo",
                    Version = "1.0.0"
                };
                var serverImplementation = client.Identify(clientImplementation);

                var inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);

                Console.WriteLine("Total messages: {0}", inbox.Count);
                Console.WriteLine("Recent messages: {0}", inbox.Recent);

                for (int i = 0; i < inbox.Count; i++)
                {
                    var message = inbox.GetMessage(i);
                    Console.WriteLine("Subject: {0}", message.Subject);
                }

                client.Disconnect(true);
            }
        }
Beispiel #3
0
    public static async Task <ImapClient> CreateClientAndConnectAsync()
    {
        var imapClient = new ImapClient();
        await imapClient.ConnectAsync(MailHostOptions.Imap163Host, MailHostOptions.Imap163Port);

        await imapClient.AuthenticateAsync(MailHostOptions.Imap163Account, MailHostOptions.QqPassword);

        var clientImplementation = new ImapImplementation()
        {
            Name      = "Study-C-Sharp",
            Version   = "1.0.0",
            OS        = "Windows",
            OSVersion = "21H2"
        };
        await imapClient.IdentifyAsync(clientImplementation);

        return(imapClient);
    }
        /// <summary>
        /// get a imap client
        /// </summary>
        /// <returns>imap client</returns>
        public ImapClient GetImapClient()
        {
            ImapClient client = new ImapClient();

            client.ServerCertificateValidationCallback = (s, c, h, e) => true;
            client.Connect(imapServer, imapPort, imapSsl);
            client.Authenticate(account, password);
            //判断是否 添加ID COMMOND命令
            if ((client.Capabilities | ImapCapabilities.Id) == client.Capabilities)
            {
                var clientImplementation = new ImapImplementation
                {
                    Name    = "Foxmail",
                    Version = "9.156"
                };
                var serverImplementation = client.Identify(clientImplementation);
            }
            return(client);
        }
Beispiel #5
0
        public void TestImapImplementationProperties()
        {
            var impl = new ImapImplementation();

            impl.Address = "50 Church St.";
            Assert.AreEqual("50 Church St.", impl.Address, "Address");

            impl.Arguments = "-p -q";
            Assert.AreEqual("-p -q", impl.Arguments, "Arguments");

            impl.Command = "mono ./imap.exe";
            Assert.AreEqual("mono ./imap.exe", impl.Command, "Command");

            impl.Environment = "MONO_GC=sgen";
            Assert.AreEqual("MONO_GC=sgen", impl.Environment, "Environment");

            impl.Name = "MailKit";
            Assert.AreEqual("MailKit", impl.Name, "Name");

            impl.OS = "Windows";
            Assert.AreEqual("Windows", impl.OS, "OS");

            impl.OSVersion = "6.1";
            Assert.AreEqual("6.1", impl.OSVersion, "OSVersion");

            impl.ReleaseDate = "${Date}";
            Assert.AreEqual("${Date}", impl.ReleaseDate, "ReleaseDate");

            impl.SupportUrl = "https://github.com/jstedfast/MailKit";
            Assert.AreEqual("https://github.com/jstedfast/MailKit", impl.SupportUrl, "SupportUrl");

            impl.Vendor = "Microsoft";
            Assert.AreEqual("Microsoft", impl.Vendor, "Vendor");

            impl.Version = "2.0.7";
            Assert.AreEqual("2.0.7", impl.Version, "Version");
        }
        public async void TestImapClientFeatures()
        {
            var commands = new List <ImapReplayCommand> ();

            commands.Add(new ImapReplayCommand("", "gmail.greeting.txt"));
            commands.Add(new ImapReplayCommand("A00000000 CAPABILITY\r\n", "gmail.capability.txt"));
            commands.Add(new ImapReplayCommand("A00000001 AUTHENTICATE PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "gmail.authenticate.txt"));
            commands.Add(new ImapReplayCommand("A00000002 NAMESPACE\r\n", "gmail.namespace.txt"));
            commands.Add(new ImapReplayCommand("A00000003 LIST \"\" \"INBOX\"\r\n", "gmail.list-inbox.txt"));
            commands.Add(new ImapReplayCommand("A00000004 XLIST \"\" \"*\"\r\n", "gmail.xlist.txt"));
            commands.Add(new ImapReplayCommand("A00000005 ID (\"name\" \"MailKit\" \"version\" \"1.0\" \"vendor\" \"Xamarin Inc.\")\r\n", "common.id.txt"));
            commands.Add(new ImapReplayCommand("A00000006 GETQUOTAROOT INBOX\r\n", "common.getquota.txt"));

            using (var client = new ImapClient()) {
                try {
                    client.ReplayConnect("localhost", new ImapReplayStream(commands, false));
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Connect: {0}", ex);
                }

                Assert.IsTrue(client.IsConnected, "Client failed to connect.");
                Assert.IsFalse(client.IsSecure, "IsSecure should be false.");

                Assert.AreEqual(GMailInitialCapabilities, client.Capabilities);
                Assert.AreEqual(4, client.AuthenticationMechanisms.Count);
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH"), "Expected SASL XOAUTH auth mechanism");
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("XOAUTH2"), "Expected SASL XOAUTH2 auth mechanism");
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism");
                Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN-CLIENTTOKEN"), "Expected SASL PLAIN-CLIENTTOKEN auth mechanism");

                Assert.AreEqual(100000, client.Timeout, "Timeout");
                client.Timeout *= 2;

                // Note: Do not try XOAUTH2
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                try {
                    await client.AuthenticateAsync(new NetworkCredential ("username", "password"));
                } catch (Exception ex) {
                    Assert.Fail("Did not expect an exception in Authenticate: {0}", ex);
                }

                Assert.AreEqual(GMailAuthenticatedCapabilities, client.Capabilities);

                var implementation = new ImapImplementation {
                    Name = "MailKit", Version = "1.0", Vendor = "Xamarin Inc."
                };

                implementation = await client.IdentifyAsync(implementation);

                Assert.IsNotNull(implementation, "Expected a non-null ID response.");
                Assert.AreEqual("GImap", implementation.Name);
                Assert.AreEqual("Google, Inc.", implementation.Vendor);
                Assert.AreEqual("http://support.google.com/mail", implementation.SupportUrl);
                Assert.AreEqual("gmail_imap_150623.03_p1", implementation.Version);
                Assert.AreEqual("127.0.0.1", implementation.Properties["remote-host"]);

                var personal = client.GetFolder(client.PersonalNamespaces[0]);
                var inbox    = client.Inbox;

                Assert.IsNotNull(inbox, "Expected non-null Inbox folder.");
                Assert.AreEqual(FolderAttributes.Inbox | FolderAttributes.HasNoChildren, inbox.Attributes, "Expected Inbox attributes to be \\HasNoChildren.");

                var quota = await inbox.GetQuotaAsync();

                Assert.IsNotNull(quota, "Expected a non-null GETQUOTAROOT response.");
                Assert.AreEqual(personal.FullName, quota.QuotaRoot.FullName);
                Assert.AreEqual(personal, quota.QuotaRoot);
                Assert.AreEqual(3783, quota.CurrentStorageSize.Value);
                Assert.AreEqual(15728640, quota.StorageLimit.Value);
                Assert.IsFalse(quota.CurrentMessageCount.HasValue);
                Assert.IsFalse(quota.MessageLimit.HasValue);

                await client.DisconnectAsync(false);
            }
        }
Beispiel #7
0
        public static void Capabilities()
        {
            using (var client = new ImapClient()) {
                client.Connect("imap.gmail.com", 993, SecureSocketOptions.SslOnConnect);

                var mechanisms = string.Join(", ", client.AuthenticationMechanisms);
                Console.WriteLine("The IMAP server supports the following SASL authentication mechanisms: {0}", mechanisms);

                client.Authenticate("username", "password");

                if (client.Capabilities.HasFlag(ImapCapabilities.Id))
                {
                    var clientImplementation = new ImapImplementation {
                        Name = "MailKit", Version = "1.0"
                    };
                    var serverImplementation = client.Identify(clientImplementation);

                    Console.WriteLine("Server implementation details:");
                    foreach (var property in serverImplementation.Properties)
                    {
                        Console.WriteLine("  {0} = {1}", property.Key, property.Value);
                    }
                }

                if (client.Capabilities.HasFlag(ImapCapabilities.Acl))
                {
                    Console.WriteLine("The IMAP server supports Access Control Lists.");

                    Console.WriteLine("The IMAP server supports the following access rights: {0}", client.Rights);

                    Console.WriteLine("The Inbox has the following access controls:");
                    var acl = client.Inbox.GetAccessControlList();
                    foreach (var ac in acl)
                    {
                        Console.WriteLine("  {0} = {1}", ac.Name, ac.Rights);
                    }

                    var myRights = client.Inbox.GetMyAccessRights();
                    Console.WriteLine("Your current rights for the Inbox folder are: {0}", myRights);
                }

                if (client.Capabilities.HasFlag(ImapCapabilities.Quota))
                {
                    Console.WriteLine("The IMAP server supports quotas.");

                    Console.WriteLine("The current quota for the Inbox is:");
                    var quota = client.Inbox.GetQuota();

                    if (quota.StorageLimit.HasValue && quota.StorageLimit.Value)
                    {
                        Console.WriteLine("  Limited by storage space. Using {0} out of {1} bytes.", quota.CurrentStorageSize.Value, quota.StorageLimit.Value);
                    }

                    if (quota.MessageLimit.HasValue && quota.MessageLimit.Value)
                    {
                        Console.WriteLine("  Limited by the number of messages. Using {0} out of {1} bytes.", quota.CurrentMessageCount.Value, quota.MessageLimit.Value);
                    }

                    Console.WriteLine("The quota root is: {0}", quota.QuotaRoot);
                }

                if (client.Capabilities.HasFlag(ImapCapabilities.Thread))
                {
                    if (client.ThreadingAlgorithms.Contains(ThreadingAlgorithm.OrderedSubject))
                    {
                        Console.WriteLine("The IMAP server supports threading by subject.");
                    }
                    if (client.ThreadingAlgorithms.Contains(ThreadingAlgorithm.References))
                    {
                        Console.WriteLine("The IMAP server supports threading by references.");
                    }
                }

                client.Disconnect(true);
            }
        }
Beispiel #8
0
        public bool GetEmailContent(string userName, string pwd, string keyWords, out string content, out string rtnMsg, int tryCount = 1)
        {
            content = "";
            rtnMsg  = "";
            try
            {
                using (var client = new ImapClient())
                {
                    if (userName.Contains("@163.com"))
                    {
                        client.Connect("imap.163.com", 993, true);
                    }
                    else if (userName.Contains("@126.com"))
                    {
                    }

                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    try
                    {
                        client.Authenticate(userName, pwd);
                    }
                    catch (AuthenticationException ex)
                    {
                        throw new Exception("无效的用户名或密码:" + ex.Message);
                    }
                    catch (ImapCommandException ex)
                    {
                        throw new Exception("尝试验证错误:" + ex.Message);
                    }
                    catch (ImapProtocolException ex)
                    {
                        throw new Exception("尝试验证时的协议错误:" + ex.Message);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("账户认证错误:" + ex.Message);
                    }

                    var clientImplementation = new ImapImplementation
                    {
                        Name    = "我的邮箱",
                        Version = "2.0"
                    };
                    var serverImplementation = client.Identify(clientImplementation);

                    int count = 0;
methodStart:
                    count++;
                    if (count <= tryCount)
                    {
                        //获取未读邮件
                        var inbox = client.Inbox;
                        inbox.Open(FolderAccess.ReadWrite);
                        var uidss = inbox.Search(SearchQuery.NotSeen);
                        if (uidss == null || uidss.Count == 0)
                        {
                            //没有未读邮件,
                            if (count < tryCount)
                            {
                                Thread.Sleep(1000);
                            }
                            goto methodStart;
                        }

                        for (int i = 0; i < uidss.Count; i++)
                        {
                            var    message  = inbox.GetMessage(uidss[i]);
                            string bodyText = message.HtmlBody;
                            if (bodyText.Contains(keyWords))
                            {
                                content = bodyText;

                                Regex regex = new Regex(@"<[^>]+>|</[^>]+>");

                                string stroutput = regex.Replace(bodyText, "");
                                stroutput = stroutput.Replace(" ", "");
                                stroutput = stroutput.Replace("\r\n", "");
                                stroutput = stroutput.Replace("\r", "");
                                stroutput = stroutput.Replace("\n", "");

                                content = stroutput;
                                if (content.Contains("验证码是:"))
                                {
                                    content = content.Substring(content.IndexOf("验证码是:") + 5, content.IndexOf("验证码有效期") - (content.IndexOf("验证码是:") + 5));
                                }


                                inbox.SetFlags(uidss[i], MessageFlags.Seen, false);
                                break;
                            }
                        }

                        //没有获取到指定的邮件
                        if (string.IsNullOrEmpty(content))
                        {
                            Thread.Sleep(1000);
                            goto methodStart;
                        }
                    }
                    else
                    {
                        rtnMsg = "未获取到符合条件的邮件!";
                    }
                    client.Disconnect(true);
                }
            }
            catch (Exception ex)
            {
                rtnMsg = ex.Message;
            }
            return(!string.IsNullOrEmpty(content));
        }
Beispiel #9
0
        /// <summary>
        /// 接收邮件
        /// </summary>
        public static void ReceiveEmail()
        {
            // 确定一个目录来保存内容
            var directory = AppDomain.CurrentDomain.BaseDirectory + "MailBody\\";

            Directory.CreateDirectory(directory);
            var sendServerConfiguration = SetSendMessage();

            if (sendServerConfiguration == null)
            {
                throw new ArgumentNullException();
            }

            //var smtpclient = new SmtpClient();
            //smtpclient.Connect(sendServerConfiguration.SmtpHost, sendServerConfiguration.SmtpPort, sendServerConfiguration.IsSsl);

            var kfd = new ImapClient();

            kfd.ServerCertificateValidationCallback = (s, c, h, e) => true;
            kfd.Connect(sendServerConfiguration.ImapHost, sendServerConfiguration.ImapPort, sendServerConfiguration.IsSsl);
            kfd.Authenticate(sendServerConfiguration.SenderAccount, sendServerConfiguration.SenderPassword);
            //判断是否 添加ID COMMOND命令
            if (HasImapCapabilitiesId(kfd.Capabilities, ImapCapabilities.Id))
            {
                var clientImplementation = new ImapImplementation
                {
                    Name    = "MeSince",
                    Version = "2.0"
                };
                var serverImplementation = kfd.Identify(clientImplementation);
            }
            var inbox = kfd.Inbox;

            inbox.Open(FolderAccess.ReadOnly);
            int cnt  = inbox.Count;
            int rec  = inbox.Recent;
            var uids = inbox.Search(SearchQuery.DeliveredAfter(DateTime.Parse("2020-01-20")));
            // 获取搜索结果的摘要信息(我们需要UID和BODYSTRUCTURE每条消息,以便我们可以提取文本正文和附件)
            var items = kfd.Inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);

            foreach (var item in items)
            {
                MimeMessage message  = inbox.GetMessage(item.UniqueId);
                DateTime    senddate = message.Date.Date;
                string      htmlbody = message.HtmlBody;
                string      from     = message.From.Count > 0?message.From.FirstOrDefault().ToString():"";
                string      subject  = message.Subject;


                foreach (var attachment in item.Attachments)
                {
                    // 像我们对内容所做的那样下载附件
                    var entity = inbox.GetBodyPart(item.UniqueId, attachment);

                    // 附件可以是message / rfc822部件或常规MIME部件
                    var messagePart = entity as MessagePart;
                    if (messagePart != null)
                    {
                        var rfc822 = messagePart;

                        var path = Path.Combine(directory, attachment.FileName);

                        rfc822.Message.WriteTo(path);
                    }
                    else
                    {
                        var part = (MimePart)entity;

                        // 注意:这可能是空的,但大多数会指定一个文件名
                        var fileName = part.FileName;

                        var path = Path.Combine(directory, fileName);

                        // decode and save the content to a file
                        using (var stream = File.Create(path))
                            part.Content.DecodeTo(stream);
                    }
                }
            }
            kfd.Disconnect(true);
        }