How to fix 'Failure sending mail' in C#

By FoxLearn 7/13/2024 4:07:18 AM   8.39K
Fixing "Failure sending mail" issues in C# when using Office 365 for sending emails typically involves ensuring that your SMTP settings and authentication credentials are correctly configured.

If you are facing problem sending mail with office365 in c#. You spend a lot of time to solve, the following article will guide you how to handle it.

How to fix 'Failure sending mail' in C#

If you're using Visual Studio to programmatically send an email from an Office 365 mailbox in C# using SMTP, ensure your code resembles the following structure.

//failure sending mail c# smtpclient
public void SendMail(string subject, string to, string displayName, string message)
{
    var credentials = new NetworkCredential(account.Email, account.Password);
    var mail = new MailMessage()
    {
        From = new MailAddress(account.Email, displayName),
        Subject = subject,
        Body = message,
    };
    mail.IsBodyHtml = true;//If you want to send mail in html format
    mail.To.Add(new MailAddress(to));
    var client = new SmtpClient() { Port = account.Port ?? 0, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Host = account.Server, EnableSsl = true, Credentials = credentials };
    client.Send(mail);
}

If you try to send mail via office365 smtp server but it prompts with "Failure sending mail". You are unable to send mail via office 365 smtp.

Ensure you are using the correct SMTP server and port for Office 365. These settings are

office 365 smtp settings

account.Email: [your email account]

account.Password: [your email password]

Port: 587

Host: smtp.office365.com

Office 365 requires a secure connection using SSL/TLS. Make sure your SMTP client is configured accordingly:

If using port 587, set EnableSsl to true.

If using port 465, use EnableSsl with true and ensure UseDefaultCredentials is set to false.

Office 365 SMTP requires authentication with your Office 365 account credentials by setting UseDefaultCredentials to false.

If you get the problem "Unable to read data from the transport connection: net_io_connectionclosed" you need to enable Tls.

//Unable to send email from Office 365 using c# SmtpClient
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

Just add the code above at the start of your function. Because TLS 1.0/1.1 is deprecated in 2022, you need to switch to TLS 1.2

Finally, Ensure that your firewall or network configuration allows outbound traffic on the SMTP port (587, 465, or 25) to smtp.office365.com.