How to fix System.Net.Sockets.Socket+AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)

Akinmatics 5 Reputation points
2023-12-27T17:18:56.0266667+00:00

I have the below error after trying to connect to brevo smtp (formerly sendinblue)...

An unhandled exception occurred while processing the request.

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.

System.Net.Sockets.Socket+AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)

SmtpException: Failure sending mail.

WebApp.Services.EmailService.SendAsync(string from, string to, string subject, string body) in EmailService.cs, line 31...

Below is the code from EmailService.cs

using System.Net.Mail;
using System.Net;
using Microsoft.Extensions.Options;
using WebApp.Settings;

namespace WebApp.Services
{
    public class EmailService : IEmailService
    {
        private readonly IOptions<SmtpSetting> smtpSetting;

        public EmailService(IOptions<SmtpSetting> smtpSetting)
        {
            this.smtpSetting = smtpSetting;
        }
        public async Task SendAsync(string from, string to, string subject, string body)
        {
            var message = new MailMessage(from,
                    to,
                    subject,
                    body);


            using (var emailClient = new SmtpClient(smtpSetting.Value.Host, smtpSetting.Value.Port))
            {
                emailClient.Credentials = new NetworkCredential(
                    smtpSetting.Value.User,
                    smtpSetting.Value.Password);


                await emailClient.SendMailAsync(message);
            }
        }
    }
}

Developer technologies | ASP.NET | ASP.NET Core
Microsoft Security | Intune | Configuration Manager | Other
{count} vote

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.