17

i have a mail account on the Exchange Online service. Now i'm trying to test if i am able to send mails to customers ( on varoius domains and on Microsoft Office 365) through c# application

I tried implementing the below code but i am getting the error

"The remote certificate is invalid according to the validation procedure."

MailMessage mail = null;                
mail = new MailMessage();

string[] strToList = "abc@gmail.com"              
foreach (string strID in strToList)
{
    if (strID != null)
    {
        mail.To.Add(new MailAddress(strID));
    }
}

mail.From = "demo@onmicrosoft.com";
mail.Subject = "testing"
mail.IsBodyHtml = true;
mail.Body = "mail body";

SmtpClient client = new SmtpClient("smtp.outlook.office365.com");
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
NetworkCredential cred = new System.Net.NetworkCredential("demo@onmicrosoft.com", "mypassword");
client.Credentials = cred;
client.Send(mail);

Please advice if i am doing anything wrong. Thanks a lot in advance.

Joakim Johansson
  • 3,196
  • 1
  • 27
  • 43
user166013
  • 1,411
  • 4
  • 21
  • 37
  • possible duplicate of [Sending email using Smtp.mail.microsoftonline.com](http://stackoverflow.com/questions/6656039/sending-email-using-smtp-mail-microsoftonline-com) – bubbassauro Aug 05 '13 at 16:16
  • http://www.softdeveloperszone.com/2013/04/send-email-through-office-365-outlook.html . Have a crack at this one. Worked for me – chamara Nov 13 '16 at 09:04

8 Answers8

15

this works for me ( edited from source )


   ThreadPool.QueueUserWorkItem(t =>
            {
                SmtpClient client = new SmtpClient("smtp.office365.com",587);
                client.EnableSsl = true;
                client.Credentials = new System.Net.NetworkCredential("xxx@yyy.com", "password");
                MailAddress from = new MailAddress("xxx@yyy.com", String.Empty, System.Text.Encoding.UTF8);
                MailAddress to = new MailAddress("xxx@yyy.com");
                MailMessage message = new MailMessage(from, to);
                message.Body = "The message I want to send.";
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = "The subject of the email";
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                // Set the method that is called back when the send operation ends.
                client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                // The userState can be any object that allows your callback 
                // method to identify this send operation.
                // For this example, I am passing the message itself
                client.SendAsync(message, message);
            });

        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the message we sent
            MailMessage msg = (MailMessage)e.UserState;

            if (e.Cancelled)
            {
                // prompt user with "send cancelled" message 
            }
            if (e.Error != null)
            {
                // prompt user with error message 
            }
            else
            {
                // prompt user with message sent!
                // as we have the message object we can also display who the message
                // was sent to etc 
            }

            // finally dispose of the message
            if (msg != null)
                msg.Dispose();
        }
Community
  • 1
  • 1
Zakos
  • 1,492
  • 2
  • 22
  • 41
6

In some cases the TLS authentication may cause problems in using smtp.office365.com as SMTP from c#. Try the following line before the Send(msg) statement (overriding .TargetName):

client.TargetName = "STARTTLS/smtp.office365.com";

This one works for me

Joe Frank
  • 761
  • 7
  • 6
  • This fixed the issue for me - I've had the regular code from this question working at many places, but then at one site I just couldn't get things going without adding this TargetName value. Thanks!! – Ian Yates Jul 23 '20 at 05:20
6

This is also best way to send Mail. I have tried it in my project and working fine.

 SmtpClient client = new SmtpClient("smtp.office365.com", 587);
        client.EnableSsl = true;
        client.Credentials = new System.Net.NetworkCredential("From@mail.com", "sdsd@12345");
        MailAddress from = new MailAddress("From Address Ex From@mail.com", String.Empty, System.Text.Encoding.UTF8);
        MailAddress to = new MailAddress("From Address Ex To@mail.com");
        MailMessage message = new MailMessage(from, to);
        message.Body = "This is your body message";
        message.BodyEncoding = System.Text.Encoding.UTF8;
        message.Subject = "Subject";
        message.SubjectEncoding = System.Text.Encoding.UTF8;

        client.Send(message);
Shashi Keshar
  • 61
  • 1
  • 3
3

Try smtp.office365.com instead of smtp.outlook.office365.com

Benjamin Talmard
  • 1,773
  • 11
  • 21
2

Try to use:

ServicePointManager.ServerCertificateValidationCallback = 
    (sender, certificate, chain, sslPolicyErrors) => true;

This code will allow you to accept invalid certificates.

As Ori Nachum mention in the comment: this is a very BAD practice, and should only use for testing purposes. It is a security risk!

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
  • when i tried the above i am getting another exception "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated" – user166013 Apr 09 '13 at 10:28
  • @RowlandShaw did you check http://stackoverflow.com/questions/20906077/gmail-error-the-smtp-server-requires-a-secure-connection-or-the-client-was-not ? – Piotr Stapp Mar 02 '16 at 19:48
  • It should be noted this is a bad practice, and should only used for testing purposes. It's a major security risk. – Ori Nachum Aug 14 '18 at 08:04
1

The Error

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated

often happens when associated user account password is expired or account is locked. Try set "Never expire user password" in Active Directory, if it does not breach your company password policy :) This happened to me while testing with o365 Exchange Online A/c.

hiFI
  • 1,887
  • 3
  • 28
  • 57
  • I set up a new user specifically to log in via SMTP. I got this error because during first login, the user was required to change their password. Had me confused for a while! – johnnycardy Aug 13 '14 at 14:16
1

Try setting:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

It will ensure the Service's SecurityPoint is TLS.
Please notice an answer here offered setting

ServicePointManager.ServerCertificateValidationCallback = 
    (sender, certificate, chain, sslPolicyErrors) => true;

May be good for testing purposes - but it's a major security risk!
Do not use with a prod account or in prod environment.

Ori Nachum
  • 588
  • 3
  • 19
1
var Client = new SmtpClient("smtp.office365.com", 587);
Client.EnableSsl = true;
Client.Credentials = new System.Net.NetworkCredential("mail", "pass");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

I successfully send mail with code