Home > Blockchain >  MailKit can't connect to Google SMTP server
MailKit can't connect to Google SMTP server

Time:12-18

I am using MailKit in my project to send email. When I try to connect to smtp.gmail.com an exception is thrown in client.ConnectAsync() method. My EmailSender class code is below:

using MimeKit;
using MailKit.Net.Smtp;

public class EmailSender
{ 
    public async Task SendEmailAsync(string email, string subject, string message)
    {
        var emailMessage = new MimeMessage();
        var addressFrom = new MailboxAddress("username",
                                             "email");
        var addressTo = new MailboxAddress(string.Empty,
                                           email);

        emailMessage.From.Add(addressFrom);
        emailMessage.To.Add(addressTo);
        emailMessage.Subject = subject;
        emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html)
        {
            Text = message,
        };

        using var client = new SmtpClient();

        await client.ConnectAsync("smtp.gmail.com",
                                  465,
                                  useSsl: true);



        client.Authenticate(addressFrom.Address,
                            "password");
        await client.SendAsync(emailMessage);
        await client.DisconnectAsync(true);
    }
}

Exception:

System.Net.Sockets.SocketException: 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.'

I tried to ping gmail smtp server from command line, and all is okey with reaching this server. Also tried to connect via TSL on 587 port, but had the same problem.

CodePudding user response:

I tried many things, but the problem was not on my side. It looks like my ISP is blocking this connection. When I used my mobile phone as a modem, everything worked correctly.

  • Related