MailKit can't connect to Google SMTP server - c#

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.

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

Getting MailKit.Security.SslHandshakeException on my .NET 5.0 web API when trying send an email through Gmail SMTP

I'm trying to setup email alerts from my .NET core web api. I've created the following email service to test it.
I'm connecting to the gmail smtp server using the following details:
url:smtp.gmail.com
port: 465
ssl: true
And authenticating using my gmail address and password.
using MailKit.Net.Smtp;
using MimeKit;
public class EmailService
{
public SmtpClient ConnectSMTP() {
SmtpClient client = new SmtpClient();
//remove hard coding from this and place details in env settings
client.Connect("smtp.gmail.com", 465, true);
client.Authenticate("<EMAIL>", "<PASSWORD>");
return client;
}
public void EmailTest(string toAddress)
{
MimeMessage msg = new MimeMessage();
MailboxAddress from = new MailboxAddress("EzGig","ezgigrota#gmail.com");
msg.From.Add(from);
MailboxAddress to = new MailboxAddress("EzGig User", toAddress);
msg.Subject ="Test Email";
BodyBuilder bodyBuilder = new BodyBuilder();
bodyBuilder.TextBody = "This is a test email body";
msg.Body = bodyBuilder.ToMessageBody();
SmtpClient client = ConnectSMTP();
client.Send(msg);
client.Disconnect(true);
client.Dispose();
}
}
When I try to call the EmailTest method from one of my controllers I'm getting the following error
MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.
The server's SSL certificate could not be validated for the following reasons:
• The server certificate has the following errors:
• The revocation function was unable to check revocation for the certificate.
I had the same issue. #jstedfast was correct but he forgot to mention one thing.
Ensure the client.CheckCertificateRevocation = false; comes before client.connect()
client.CheckCertificateRevocation = false;
client.connect();
Based on the error message, it probably means that the CRL server was down which would prevent the SslStream from checking revocation status of the server's SSL certificate.
You can disable CRL checks by setting client.CheckCertificateRevocation = false;

SMTP authentication error on send mail, in a legacy code

I'm experiencing a weird problem, as the title says whenever I try to send a mail, the following exception is thrown:
System.Net.Mail.SmtpException: 'The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at'
Nothing out of the ordinary, however this is a code that was written about 2 years ago and hasn't been touched since, today when I ran it - suddenly doesn't work.
public static Task SendEmailAsync(string email, string subject, string htmlMessage)
{
return Task.Run(() =>
{
using (var client = BuildClient())
{
var message = BuildMessage(email, subject, htmlMessage);
client.Send(message);
}
});
}
private static SmtpClient BuildClient()
{
var smtp = new SmtpClient("smtp.gmail.com", 587)
{
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("xxxxx#abv.bg", "xxx")
};
return smtp;
}
private static MailMessage BuildMessage(string email, string subject, string htmlMessage)
{
var mailMessage = new MailMessage
{
From = new MailAddress("xxxx#abv.com"),
Subject = subject,
Body = htmlMessage
};
mailMessage.To.Add(email);
return mailMessage;
}
As you can see the host is gmail.com, but I'm using a different email provider abv.bg, I've also tried swapping that with a gmail account, but the error is still the same.
This is a somewhat shortened version of the original code, but this also produces the error, since im not using gmail, there is no such a thing as "Less secure apps", or 2fa, this cant be the cause and even if it was when I attempted to use a gmail account, I enabled the less secure apps option, to no avail. I've ran this code under both .net core 3.0 and .net framework 4.7.2, same results. I'm also running this completely locally, so time zones shouldn't be a problem. And I've tripled, quadrupled checked the password and email.
So I'm basically clueless to why this is happening, any tips would be appreciated.

How do I fix the error "The type initializer for '?' threw an exception." when sending e-mails through C# with EASendMail?

I have been working on this project to send an e-mail to a user and I have had an error come up all the time. (I'm using the EASendMail NuGet package) It is "The type initializer for '?' threw an exception." (this is in the console for the error system that the package has) I dont really know what that means, my code is this:
using EASendMail;
namespace Email
{
class Program
{
static void Main(string[] args)
{
try
{
SmtpMail oMail = new SmtpMail("TryIt");
// Set sender email address, please change it to yours
oMail.From = "Splat2ooner#gmail.com";
// Set recipient email address, please change it to yours
oMail.To = "Splat2ooner#gmail.com";
// Set email subject
oMail.Subject = "test email from c# project";
// Set email body
oMail.TextBody = "this is a test email sent from c# project, do not reply";
// SMTP server address
SmtpServer oServer = new SmtpServer("smtp.gmail.com");
// User and password for ESMTP authentication
oServer.User = "Splat2ooner#gmail.com";
oServer.Password = "password (not my passoword)";
// Most mordern SMTP servers require SSL/TLS connection now.
// ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
// If your SMTP server uses 587 port
//oServer.Port = 587;
// If your SMTP server requires SSL/TLS connection on 25/587/465 port
//oServer.Port = 25; // 25 or 587 or 465
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Console.WriteLine("start to send email ...");
SmtpClient oSmtp = new SmtpClient();
oSmtp.SendMail(oServer, oMail);
Console.WriteLine("email was sent successfully!");
}
catch (Exception ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
}
}
}
}
Thanks.
It looks like newer version of "EASendMail" (as of now the latest version is 7.5.0.3) package has this issue.
I don't have much time to do research on it, just installed older version (7.3.1.2) and it resolved this.
hope it helps.

Closing Transmission Error. Timeout waiting for the data from client

I am using local host to send bulk mails through SES. This question is answered by many but none of the solutions is helping me. The problem is I could send 100/ 150 mails at a time after that the above error is showing up. I tried to dispose of the client as suggested by some, but not working. I am using C# code to do this. Any answers/ suggestions is much appreciated. The below is the code I am using to send bulk mail using for loop. You might be thinking it might be a throttling issue, it is not because we have 70 emails/second and 500000 emails per day.
Parallel.For(0, mail.Count, i =>
{
// Replace with your "From" address. This address must be verified.
String TO = mail; // Replace with a "To" address. If your account is still in the
// sandbox, this address must be verified.
// Create an SMTP client with the specified host name and port.
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
// Create a network credential with your SMTP user name and password.
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
//Use SSL when accessing Amazon SES. The SMTP session will begin on an unencrypted connection, and then
//the client will issue a STARTTLS command to upgrade to an encrypted connection using SSL.
client.EnableSsl = true;
System.Net.Mail.MailMessage message1 = new System.Net.Mail.MailMessage(FROM, TO, SUBJECT, BODY);
message1.IsBodyHtml = true;
client.Send(message1);
client.Dispose();
}
});
I don't know the exact reason why it is working now, but it's working. I changed the logic of the above code, it started working. Instead of fetching the SMTP connection each time, for sending each mail previously, this time I fetched the smtp connection only once and used it to send all the bulk mails at once and it started working.But the problem is the sending time, it is taking too much to send all the mails.Anyways I will find the solution for this also.
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
client.EnableSsl = true;
for(i=0;i<mail.Count;i++)
{
String TO = mail[i];
System.Net.Mail.MailMessage message1 = new System.Net.Mail.MailMessage(FROM, TO, SUBJECT, BODY);
message1.IsBodyHtml = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(message1);
}
client.Dispose();
}
Label1.Text = mail.Count.ToString() + " mails sent !!";

SmtpException when trying to send Email

I am writing a method for sending Emails for one of my projects. This method will be used to send Emails through a Exchange Server. But for now, I want to test it with a GMX account. I have gotten the settings right but I always get an exception.
public static bool emailSenden(string strTo, string strSubject, string strContent)
{
string strFrom = "abwesenheiten_datagroup#gmx.de";
MailMessage mail = new MailMessage(strFrom, strTo, strSubject, strContent);
string strHost = "mail.gmx.net";
int port = 465;
SmtpClient client = new SmtpClient(strHost, port);
string strUsername = "abwesenheiten_datagroup#gmx.de";
string strPasswort = "pass";
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(strUsername, strPasswort);
client.Credentials = credentials;
client.EnableSsl = true;
try
{
client.Send(mail);
return true;
}
catch (Exception ex)
{
return false;
}
}
My Exception:
Access to a socket was invalid due to the access rights of the socket [xxx.xxx.xxx.xxx:xxx].
Things I have tried:
Setting different port.
Removing port and set EnableSsl to False.
Using different hosts (GMX, Web.de, etc.)
EDIT: Ok after disabling a setting in McAfee Anti Virus I get a different exception. Now it says:
"A connection attempt failed because the connected party did not properly respond after a certain period of time, or established connection failed because connected host has failed to respond"

Categories

Resources