0
votes

I am trying to send an email using default credentials and the SMTPClient.

The exception I get is:

The SMTP Server requires a secured connection, or the client was not authenticated. The serverresponse was: 5.7.1 Client was not authenticated.

The code I am trying to use:

public void SendEmail(List<string> recipients, string subject, string body)
{
    if (recipients.Count == 0)
        return;

    MailMessage mail = new MailMessage();
    SmtpClient client = new SmtpClient();
    foreach (string to in recipients)
    {
        mail.To.Add(to);                
    }

    mail.From = new MailAddress("[email protected]");
    client.Port = 25;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = true;
    client.Host = "smtprelay.email.com";

    //client.Credentials = new System.Net.NetworkCredential("[email protected]", password);
    ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

    client.EnableSsl = true;
    mail.Subject = subject;
    mail.Body = body;
    mail.IsBodyHtml = true;

    try
    {
        client.Send(mail);
    }
    catch(Exception e)
    {
        Console.Write(e.Message);
    }
    mail.Dispose();
}

I tested with EnableSsl = true and false, neither worked. If I set UseDefaultCredentials to false, and give them via NetworkCredential, then it works.

Is there some setting in exchange or such that needs to be set?

Edit: int the ServerCertificateCallback, I get: '((System.Net.Mail.SmtpClient)s).ServicePoint.Address' threw an exception of type 'System.NotSupportedException'

and sslPolicyErrors was System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch

Does that mean the group policies do not allow this?

2

2 Answers

0
votes

Exchange requires either a valid domain account (login/pw) or an IP address that your postmaster has configured as allowable.

0
votes

you can try this code below

public static void logMail(string err)
        {
            SmtpClient smtp = new SmtpClient();
            smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
            smtp.Port = 25;
            smtp.Host = "mail.email.com";

            MailAddress from = new MailAddress("[email protected]", "test");
            MailAddress to = new MailAddress("[email protected]"); 
            MailMessage mail = new MailMessage(from, to);
            mail.IsBodyHtml = true;
            mail.Subject = "Error";
            mail.Body = "<b>Error Message:</b> " + err;
            smtp.Send(mail);
        }