0
votes

The code I currently have is:

    public void SendEmail(string to, string cc, string bcc, string subject, string body, string attachmentPath = "", System.Net.Mail.MailPriority emailPriority = MailPriority.Normal, BodyType bodyType = BodyType.HTML)
    {
        try
        {
            var client = new System.Net.Mail.SmtpClient();
            {
                client.Host = "smtp-mail.outlook.com";
                client.Port = 587;
                client.UseDefaultCredentials = false;
                client.EnableSsl = true;

                client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                client.Credentials = new NetworkCredential("[my company email]", "[my password]");
                client.Timeout = 600000;
            }

            MailMessage mail = new MailMessage("[insert my email here]", to);
            mail.Subject = subject;
            mail.Body = body;

            client.Send(mail);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

The email address I'm trying to send to is hosted on Office 365's Outlook. We might have to change the specific address later, but they'd likely be configured the same.

However, whenever I try to run the client.Send(mail); command, I receive the same error. The full text of the error is:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM 

I've tried a few different things, like switching the port between 25 and 587, changing the host to Office365's, or toggling UseDefaultCredentials and EnableSssl to true or false. But I always see the same error. Is there something else I'm missing?

1

1 Answers

0
votes

I found an example code block elsewhere on this site and replacing everything I had with it made the difference.

The function name and parameters were the same, but here's what I replaced the body of it with.

 var _mailServer = new SmtpClient();
 _mailServer.UseDefaultCredentials = false;
 _mailServer.Credentials = new NetworkCredential("my email", "my password");
 _mailServer.Host = "smtp.office365.com";
 _mailServer.TargetName = "STARTTLS/smtp.office365.com"; 
 _mailServer.Port = 587;
 _mailServer.EnableSsl = true;

var eml = new MailMessage();
eml.Sender = new MailAddress("my email");
eml.From = eml.Sender;
eml.To.Add(new MailAddress(to));
eml.Subject = subject;
eml.IsBodyHtml = (bodyType == BodyType.HTML);
eml.Body = body;

_mailServer.Send(eml);

I don't know for certain but I think that replacing the Host value with the smtp Office 365 link rather than an outlook one, as well as remembering to add a Target Name which I did not have before, both did the trick and solved the authorization issue (I had previously confirmed it wasn't a credentials issue with our tech support).