'Using MailKit to retrieve emails from gmail
I'm using below code to retrieve the emails. But I'm getting a Socket exception when trying to connect the server (client.Connect(uri, cancel.Token);).
Unhandled Exception: 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("[email protected]", "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);
}
}
}
}
Solution 1:[1]
I'm pretty sure that you need to use pop.gmail.com and not just gmail.com as the server string.
Solution 2:[2]
use the following code i just test it in one of my projects and its working well
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);
..
....
......
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jstedfast |
| Solution 2 | M.Ali El-Sayed |
