How to fix 'Failure sending mail' in C#
By FoxLearn 11/27/2024 1:13:59 PM 8.63K
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 }; // send email through c# 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.
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#
- Dictionary with multiple values per key in C#