使用MailKit从gmail检索电子邮件

本文关键字:检索 电子邮件 gmail MailKit 使用 | 更新日期: 2023-09-27 18:14:38

我使用下面的代码来检索电子邮件。但我得到一个套接字异常时,试图连接服务器(客户端)。连接(uri, cancel.Token);)。

未处理的例外:System.Net.Sockets.SocketException: Connection timed out

using MailKit;
using MimeKit;
using System.Net;
using System.Threading;
using MailKit.Net.Pop3;
namespace TestMail
{
class Program
{
    public static void Main (string[] args)
    {
            using (var client = new Pop3Client ()) {
            var Server  = "gmail.com";
            var Port = "995";
            var UseSsl = false;
            var credentials = new NetworkCredential("abc@gmail.com", "abc");
            var cancel = new CancellationTokenSource ();
            var uri = new Uri(string.Format("pop{0}://{1}:{2}", (UseSsl ? "s" : ""), Server, Port));
            //Connect to email server
            client.Connect(uri, cancel.Token);
            client.AuthenticationMechanisms.Remove ("XOAUTH2");
            client.Authenticate (credentials, cancel.Token);
            //Fetch Emails
            for (int i = 0; i < client.Count; i++) {
                var message = client.GetMessage (i);
                Console.WriteLine ("Subject: {0}", message.Subject);
            }
            //Disconnect Connection
            client.Disconnect(true);
        }
    }
}
}

使用MailKit从gmail检索电子邮件

我很确定您需要使用pop.gmail.com而不仅仅是gmail.com作为服务器字符串。

使用以下代码,我只是在我的一个项目中测试它,它运行良好

   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; 
 client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
 client.Connect("pop.gmail.com", "995", true);
 client.AuthenticationMechanisms.Remove("XOAUTH2"); 
 client.Authenticate(MailUsername, MailPassword);
..
....
......
}