Hey everyone, I’m stuck with a problem while trying to send emails using Gmail in my ASP.NET C# project. Every time I try to send an email, I get this annoying error:
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. 64.233.166.109:465
I’ve set up my email config and written a method to send emails, but something’s not clicking. Here’s a simplified version of what I’m working with:
public async Task SendEmailAsync(string recipient, string subject, string body)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(_config.SenderName, _config.SenderEmail));
message.To.Add(new MailboxAddress(string.Empty, recipient));
message.Subject = subject;
message.Body = new TextPart(TextFormat.Html) { Text = body };
using var client = new SmtpClient();
await client.ConnectAsync(_config.SmtpServer, _config.Port, SecureSocketOptions.Auto);
await client.AuthenticateAsync(_config.Username, _config.Password);
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
I’m pretty sure I’m missing something obvious, but I can’t figure out what. Any ideas on what might be causing this or how I can fix it? Thanks in advance for any help!
hey henryg, had similar issues b4. try changing port to 587 and use SecureSocketOptions.StartTls instead of Auto. also check ur firewall n antivirus, they mite be blocking the connection. if that don’t work, try using gmail’s api instead of smtp. goodluck!
I’ve dealt with this headache before. Your code looks solid, but Gmail can be finicky. Have you enabled “Less secure app access” in your Google account settings? If not, that’s likely the culprit. Also, double-check your app password - those can be tricky to copy correctly.
If those don’t solve it, try using port 587 with SSL/TLS. Sometimes that works better than 465. And make sure you’re not behind a corporate firewall or VPN that might be blocking outgoing SMTP traffic.
Lastly, if all else fails, consider using a third-party email service like SendGrid or Mailgun. They’re more reliable and often easier to set up than dealing with Gmail’s quirks directly in your code.
I’ve encountered this issue in my projects as well. One crucial step often overlooked is ensuring your Google account has 2-step verification enabled. Once that’s done, generate an app-specific password for your application. This approach is more secure and reliable than using your regular account password.
Another point to consider is the timeout settings. Sometimes, the default timeout is too short for Gmail’s servers to respond. Try increasing the timeout in your SmtpClient configuration:
client.Timeout = 30000; // 30 seconds
If you’re still facing issues, it might be worth exploring alternative email service providers like Amazon SES or Mailjet. They often provide more robust SMTP services with better documentation and support for developers.