Send SMTP email testing Microsoft Office 365 in .net
Asked Answered
S

8

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 = "[email protected]"              
foreach (string strID in strToList)
{
    if (strID != null)
    {
        mail.To.Add(new MailAddress(strID));
    }
}

mail.From = "[email protected]";
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("[email protected]", "mypassword");
client.Credentials = cred;
client.Send(mail);

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

Sharecropper answered 9/4, 2013 at 10:13 Comment(2)
possible duplicate of Sending email using Smtp.mail.microsoftonline.comMillman
softdeveloperszone.com/2013/04/… . Have a crack at this one. Worked for meHarry
D
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("[email protected]", "password");
                MailAddress from = new MailAddress("[email protected]", String.Empty, System.Text.Encoding.UTF8);
                MailAddress to = new MailAddress("[email protected]");
                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();
        }
Doeskin answered 23/12, 2013 at 11:46 Comment(3)
Does anyone know if it is possible to do this without putting in a plain text password?Hengist
I get in the callback no error, but it doesn't send a mail? Can u help me?Pangolin
u have e.Error = null ? e.Cancelled = true/false? try client.EnableSsl = false;Doeskin
B
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

Baudelaire answered 12/6, 2014 at 5:16 Comment(1)
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!!Vernitavernoleninsk
O
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("[email protected]", "sdsd@12345");
        MailAddress from = new MailAddress("From Address Ex [email protected]", String.Empty, System.Text.Encoding.UTF8);
        MailAddress to = new MailAddress("From Address Ex [email protected]");
        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);
Orndorff answered 10/5, 2017 at 8:59 Comment(0)
F
3

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

Fetid answered 2/3, 2014 at 22:6 Comment(0)
M
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!

Magnanimous answered 9/4, 2013 at 10:16 Comment(3)
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"Sharecropper
@RowlandShaw did you check #20906577 ?Magnanimous
It should be noted this is a bad practice, and should only used for testing purposes. It's a major security risk.Homemaker
W
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.

Whenever answered 9/4, 2013 at 10:13 Comment(1)
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!Joke
H
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.

Homemaker answered 14/8, 2018 at 8:10 Comment(0)
F
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

Funny answered 26/6, 2020 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.