Sending email using Smtp.mail.microsoftonline.com - c#

The context:
We’re a small company that does not have an Exchange Server (or anyone dedicated to it) yet we still need to have/send emails.
We’ve decided to use Microsoft Online Services (MOS)
The Objective:
We have a web server (Windows Server 2003 R2 with IIS 6.0) and have deployed a C# ASP.Net MCV application.
The web application needs to send emails each time a user creates an account.
According to the documentation we need to use port (587) and make sure Transport Layer Security (TLS) enable. In addition, the FROM address being used must be of type “Authoritative” which it is when I double check via the Microsoft Online Administration Center
The code:
The C# code I have should be trivial and is the following:
SmtpClient server = new SmtpClient("Smtp.mail.microsoftonline.com");
server.Port = 587;
server.EnableSsl = true;
server.Credentials = new System.Net.NetworkCredential("xxx#domain.com", "123abc");
server.UseDefaultCredentials = false;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("xxx#domain.com");
mail.To.Add("johndoe#domain.com");
mail.Subject = "test subject";
mail.Body = "this is my message body";
mail.IsBodyHtml = true;
try
{
server.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
The error:
I’ve created a simple winform application with the above code to test the sending of emails…
I’ve tested the winform application locally on my computer (Windows XP) and on the Server.
In both attempt, I keep receiving the following error message:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated.
After Googling for a while I still haven’t found the reason why…In addition, most of the answers I’ve found are making a reference to the Exchange Management Console which we don’t seem to have (or installed) hence why we are using Microsoft Online Services…
Questions:
1) As a paying customer of MOS, my initial understanding is that I shouldn’t have to install (or have) an Exchange Management Console on our server…in fact, this should be completely irrelevant in order to achieve my task.
2) I’ve also tried enabling TLS inside our IIS 6.0 but to no avail…
3) We are grasping at straws here because what we seem to do looks like something amazingly trivial…
4) Should we simply abandon the idea of using MOS’s SMTP server and use another one? Such as Gmail’s ? If so…then why bother paying a monthly fee for MOS?
If any one has any help/advice that can help me shed some light on this, that would be great!
Sincerely
Vince
WOW…I believe we’ve found the culprit!!!
By commenting this line of code:
//server.UseDefaultCredentials = false;
Everything started to work!
I’m now able to send emails inside and outside our domain…
What puzzles me the most is that, according to the documentation, the default value of this UseDefaultCredentials property is set to false
So…when I manually set it to false it doesn’t work but when I comment the line (which also set’s it to false because of its default value) it works!
If this is a known issue or if anyone has an answer for that, I’d be curious to know!

looking in Reflector on UseDefaultCredentials property, you can see that it also changes the trasnport.Credentials value, so when you called this property with a false value, it changed the transport credentials to null.
the problem is that you called this property after setting the credentials in the line before that,
it nullified the credentials.
so bottom line, you shouldn't set the credentials and call this property afterwise.

you can try this sample
private void Button1_Click(System.Object sender, System.EventArgs e)
{
try
{
MailMessage myMessage = new MailMessage();
SmtpClient myClient = new SmtpClient("yourserver");
myClient.Port = "587";
myClient.Host = "your server";
myClient.UseDefaultCredentials = false;
myClient.Credentials = new System.Net.NetworkCredential("username", "password");
myMessage.From = new MailAddress("sender");
myMessage.To.Add("recipient");
myMessage.Subject = "Subject email";
myMessage.Body = "body email";
myClient.EnableSsl = true;
myClient.Send(myMessage);
}
catch (Exepiton ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
Bye

5.7.1 is not an authentication issue, but a relay issue. In order to prevent anyone from using your server (or account, as the case may be) the smtp server is configured to only allow mail to users outside your domain if it is comming from an authoritive address. Verify that the address you have listed here
mail.From = new MailAddress("xxx#domain.com");
is the same as the one you are authenticating as. Also, make sure that the domain of the address listed is in the authoritive domains list.

What worked for me was what the-dude suggested Send SMTP email using System.Net.Mail via Exchange Online (Office 365) , on changing the email "from" address to be the same as the login for the stmp address
AND
doing what Vince suggested at the end Sending email using Smtp.mail.microsoftonline.com for commenting out "smtpClient.UseDefaultCredentials = false;"

Be sure to double check that your username is correct. It is not necessarily the same as your from email address. For example the from address may be "no-reply#yourdomain.com" but the username could be "mail-svc#yourdomain.onmicrosoft.com" depending no your setup and integration with Azure Active Directory etc.

Related

Trying to send a mail from a .NET 5 console application using SMTP

Context
I'm developing an application using WPF and .NET 5 for a research institute. The client would like to receive an email when something goes wrong during an experience because it can last several days.
Before adding this feature to the software, I made a simple test program to send an email from a console application and it worked... mostly.
Disclaimer : I know there are tons of threads about this subject, and I have read nearly a hundred. The code itself doesn't seem to be the problem and I did setup the google account with two factor authentication (I also tried the "Less secure app" option).
The problem
I said the problem doesn't seem to be the code because I actually managed to send emails that way, using my personal gmail address. Problem is, I don't want to use my own address to send mail to the client... So I created an new gmail address and enabled 2FA. And when I try to send an email with the new address I get this in the emitter inbox :
What I already tried
I've tried various recipient and port with the same result. I've looked for this issue on google support, on forums and on youtube but I didn't find anything similar to my problem. I even waited 2 weeks to make sure it wasn't because the address was too recent and judged as "untrustworthy" or something like that.
The code I used
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
MailAddress to = new MailAddress("recipient#gmail.com");
MailAddress from = new MailAddress("emitter#gmail.com");
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = "Using this new feature, you can send an e-mail message from an application very easily.";
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
SmtpClient client = new SmtpClient
{
EnableSsl = true,
Port = 587,
Host = "smtp.gmail.com",
Timeout = 10000,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("emitter#gmail.com", "app-specific-password")
};
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in Main(): {0}",
ex.ToString());
}
message.Dispose();
}
What I would like
I just need to be able to send a few emails per day, to one or two contacts, from a WPF application. Nothing fancy. It seems that the two options I got are :
to find how to create a neutral email address that can use gmail smtp
or
to find another (easy and free) solution to send emails.
Can you help me with that, please ?

SMTP 5.7.57 error when trying to send email via Office 365

I'm trying to set up some code to send email via Office 365's authenticated SMTP service:
var _mailServer = new SmtpClient();
_mailServer.UseDefaultCredentials = false;
_mailServer.Credentials = new NetworkCredential("test.user#mydomain.com", "password");
_mailServer.Host = "smtp.office365.com";
_mailServer.TargetName = "STARTTLS/smtp.office365.com"; // same behaviour if this lien is removed
_mailServer.Port = 587;
_mailServer.EnableSsl = true;
var eml = new MailMessage();
eml.Sender = new MailAddress("test.user#mydomain.com");
eml.From = eml.Sender;
eml.to = new MailAddress("test.recipient#anotherdomain.com");
eml.Subject = "Test message";
eml.Body = "Test message body";
_mailServer.Send(eml);
This doesn't appear to be working, and I'm seeing an exception:
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
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
I've tried enabling network tracing and it appears that secure communications are established (for example, I see a line in the log for the "STARTTLS" command, and later there's a line in the log "Remote certificate was verified as valid by the user.", and the following Send() and Receive() data is not readable as plain text, and doesn't appear to contain any TLS/SSH panics)
I can use the very same email address and password to log on to http://portal.office.com/ and use the Outlook email web mail to send and read email, so what might be causing the authentication to fail when sending email programmatically?
Is there any way to additionally debug the encrypted stream?
In my case after I tried all this suggestion without luck, I contacted Microsoft support, and their suggestion was to simply change the password.
This fixed my issue.
Note that the password wasn't expired, because I logged on office365 with success, however the reset solved the issue.
Lesson learned: don't trust the Office 365 password expiration date, in my case the password would be expired after 1-2 months, but it wasn't working.
This leaded me to investigate in my code and only after a lot of time I realized that the problem was in the Office365 password that was "corrupted" or "prematurely expired".
Don't forget every 3 months to "refresh" the password.
To aid in debugging, try temporarily switching to MailKit and using a code snippet such as the following:
using System;
using MailKit.Net.Smtp;
using MailKit.Security;
using MailKit;
using MimeKit;
namespace TestClient {
class Program
{
public static void Main (string[] args)
{
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("", "test.user#mydomain.com"));
message.To.Add (new MailboxAddress ("", "test.recipient#anotherdomain.com"));
message.Subject = "Test message";
message.Body = new TextPart ("plain") { Text = "This is the message body." };
using (var client = new SmtpClient (new ProtocolLogger ("smtp.log"))) {
client.Connect ("smtp.office365.com", 587, SecureSocketOptions.StartTls);
client.Authenticate ("test.user#mydomain.com", "password");
client.Send (message);
client.Disconnect (true);
}
}
}
}
This will log the entire transaction to a file called "smtp.log" which you can then read through and see where things might be going wrong.
Note that smtp.log will likely contain an AUTH LOGIN command followed by a few commands that are base64 encoded (these are your user/pass), so if you share the log, be sure to scrub those lines.
I would expect this to have the same error as you are seeing with System.Net.Mail, but it will help you see what is going on.
Assuming it fails (and I expect it will), try changing to SecureSocketOptions.None and/or try commenting out the Authenticate().
See how that changes the error you are seeing.
Be sure you're using the actual office365 email address for the account. You can find it by clicking on the profile button in Outlook365. I wrestled with authentication until I realized the email address I was trying to use for authentication wasn't the actual mailbox email account. The actual account email may have the form of: account#company.onmicrosoft.com.
We got ours working by converting the mailboxes (from address) from "shared" to "regular". Before this change, my application quit sending email when we migrated from Gmail to Office 365. No other code changes were required, besides setting the host to smtp.office365.com.
Please check below code I have tested to send email using Exchange Online:
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("YourEmail#hotmail.com", "XXXX"));
msg.From = new MailAddress("XXX#msdnofficedev.onmicrosoft.com", "XXX");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message using Exchange OnLine";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("XXX#msdnofficedev.onmicrosoft.com", "YourPassword");
client.Port = 587; // You can use Port 25 if 587 is blocked
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (Exception ex)
{
}
Port (587) was defined for message submission. Although port 587 doesn't mandate requiring STARTTLS, the use of port 587 became popular around the same time as the realisation that SSL/TLS encryption of communications between clients and servers was an important security and privacy issue.
In my case my problem was not related to the code but something to do with the Exchange mailbox. Not sure why but this solved my problem:
Go to the exchange settings for that user's mailbox and access Mail Delegation
Under Send As, remove NT AUTHORITY\SELF and then add the user's account.
This gives permissions to the user to send emails on behalf of himself. In theory NT AUTHORITY\SELF should be doing the same thing but for some reason that did not work.
Source: http://edudotnet.blogspot.com.mt/2014/02/smtp-microsoft-office-365-net-smtp.html
I got this same error while testing, using my own domain email account during development. The issue for me seemed related to the MFA (Multi Factor Authentication) that's enabled on my account. Switching to an account without MFA resolved the issue.
I had this issue since someone had enabled Security defaults in Azure.
This disables SMTP/Basic authentication. It's clearly stated in the documentation, but it's not evident by the error message, and you have to have access to the account to find out.
https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/concept-fundamentals-security-defaults
It's possible to enable it per account.
https://learn.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission
You need change the credentials function. Here is the substitution you need to make:
change
-*_mailServer.Credentials = new NetworkCredential("test.user#mydomain.com", "password");*
for this
-*_mailServer.Credentials = new NetworkCredential("test.user#mydomain.com", "password", "domain");*
In my case, password was expired.I just reset password and its started working again

Office 365 Exchange SMTP intermittent authentication failure in .NET application

We have a number of C# (.net 4) apps that send email via our Office 365 Exchange account. This works absolutely fine 90% of the time. But sporadically we get the following error:
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.
Here is the code:
private void SendEmail(string strTo, string strFrom, string strMessage, string strSubject, bool htmlFormat = true)
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
System.Net.Mail.MailAddress mto = new System.Net.Mail.MailAddress(strTo);
System.Net.Mail.MailAddress mfrom = new System.Net.Mail.MailAddress(strFrom);
mail.Subject = strSubject;
mail.From = mfrom;
mail.To.Add(mto);
mail.Body = strMessage;
mail.IsBodyHtml = htmlFormat;
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.office365.com", 587);
mailClient.Timeout = 1000000;
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = new System.Net.NetworkCredential("my#emailaddress.com", "mypassword");
mailClient.Send(mail);
}
I've seen questions asked about this error message on here before, but I have not yet found any explanations as to why it might be happening only intermittently. The error message is confusing since I am not trying to send anonymously, and I am already using EnableSsl. (Note: if I remove the Credentials line or the EnableSSL line, then I get this error every time)
EDIT: As a test, I made a simple app that emails me 1 time per minute. I typically get between 12 and 25 successful emails before one blows up. Then it will go right back to normal for another 12-25, before blowing up again.
EDIT: Since the issue is so sporadic, and involves an error message returned from the 365 SMTP server, I don't really think its a problem with the code itself. Given that, I'm not sure if I've tagged the question properly, or if SO is even the best community for it. If any of you Stack Exchange veterans think this would be better placed in a different community, I am all ears. I'm a bit new here myself.
Any thoughts are appreciated!
I opened a case with Microsoft 365 support on this, and they told me I was not the only one experiencing the issue. They had me try capturing SMTP logs when the issue occurs, but we never found much of anything very helpful. The MS tech also stated that he was going to try upgrading something on our mail server on the back end (not sure what exactly). After he did that the problem was still occurring but seemed less frequent.
Eventually it became less and less frequent and now I have not seen it occur in about 5 days. So, I don't know that this is from anything specific that my MS tech did, or just a larger problem eventually getting solved. But for now, the problem seems to have gone away, and not by changing anything on our end.
public static void SendEmail(string sTo, string subject, string body)
{
var Port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]);
using (var client = new SmtpClient(Your EmailHost, Port))
using (var message = new MailMessage()
{
From = new MailAddress(FromEmail),
Subject = subject,
Body = body
})
{
message.To.Add(sTo);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailCredential"],
ConfigurationManager.AppSettings["EmailPassword"]);
client.EnableSsl = true;
client.Send(message);
};
}
After adding SMTP details properly in your email application
You need to go to on the > Microsoft 365 admin center (https://admin.microsoft.com) > Active users
Select a user you wish to authenticate with the SMTP server
Select the Mail Tab (See Image 1)
Under Email apps, Select> Manage email apps
Make sure that "Authenticated SMTP" checkbox is selected (See Image 2)
And save
Your email should work after that.
IMAGES EXAMPLES HERE
Image 1
Image 2

Can't send email using implicit SSL smtp server

I wrote up a sample program by copying the code in this KB article with some little edit as far as user's info. It uses the deprecate .NET library System.Web.Mail to do it because the new System.Net.Mail does not support implicit SSL. I went and tested it with Google smtp server on port 465 which is their implicit email port and everything works. However, when I gave this to a client to test it at his network, nothing get sent/receive, here is the error:
2013-03-07 15:33:43 - The transport failed to connect to the server.
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.CdoSysHelper.Send(MailMessage message)
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.Send(MailMessage message)
I'm not very well versed when it comes to email SSL so here is my possible theory to the root cause:
Assume he is using the right smtp server and right port (SSL port), I wonder if if any of the following could be the cause:
They are using SSL on the mail server and yet he does not have the certificate installed on the machine where he runs my program from even though he is on the same domain and use the same email domain as a sender.
They are using SSL but they maybe using NTLM or Anonymous authentication while my program uses basic authentication.
Sorry if I provide little information because I myself is quite foreign in this area so I'm still researching more.
Do you know of any steps I can do at my end to ensure my little test program can send using the smtp server of an implicit SSL email server?
Edit: I did add the following line in my code to indicates I'm using SSL.
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
Maybe this is to late to answer but have a look on https://sourceforge.net/p/netimplicitssl/wiki/Home/
You can send mail to port 465
Without the need of modifying your code, that much.
From the wiki page of project :
var mailMessage = new MimeMailMessage();
mailMessage.Subject = "test mail";
mailMessage.Body = "hi dude!";
mailMessage.Sender = new MimeMailAddress("you#gmail.com", "your name");
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MimeMailAddress("yourfriend#gmail.com", "your friendd's name"));
mailMessage.Attachments.Add(new MimeAttachment("your file address"));
var emailer = new SmtpSocketClient();
emailer.Host = "your mail server address";
emailer.Port = 465;
emailer.EnableSsl = true;
emailer.User = "mail sever user name";
emailer.Password = "mail sever password" ;
emailer.AuthenticationMode = AuthenticationType.PlainText;
emailer.MailMessage = mailMessage;
emailer.OnMailSent += new SendCompletedEventHandler(OnMailSent);
//Send email
emailer.SendMessageAsync();
// A simple call back function:
private void OnMailSent(object sender, AsyncCompletedEventArgs asynccompletedeventargs)
{
Console.Out.WriteLine(asynccompletedeventargs.UserState.ToString());
}
Here I am using gmail smtp to send mail using c#. See the code below. It will give you an insight, How the stuffs are working. Replace gmail settings with your email server settings. Dont worry about the security certificates, they will be taken care of by the framework itself.
public static bool SendMail(string to, string subject, string body)
{
bool result;
try
{
var mailMessage = new MailMessage
{
From = new MailAddress("your email address")
};
mailMessage.To.Add(new MailAddress(to));
mailMessage.IsBodyHtml = true;
mailMessage.Subject = subject;
mailMessage.Body = body;
var userName = "your gmail username";
var password = "your gmail password here";
var smtpClient = new SmtpClient
{
Credentials = new NetworkCredential(userName, password),
Host = smtp.gmail.com,
Port = 587,
EnableSsl = true
};
smtpClient.Send(mailMessage);
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
The piece of code you were referencing was pretty old and obselete too. CDO was used in ASP apps to send mails. I think you havent scroll down to see
Article ID: 555287 - Last Review: April 7, 2005 - Revision: 1.0
APPLIES TO
Microsoft .NET Framework 1.1
You are refering a code that is pretty old... anyways follow the code shown up, everything will be FINE...
UPDATE
My bad, I have'nt read it carefully. But
I am leaving the above code as it is, as it might be a help for you
or any other guy, who need the mailing functionality via SSL over
gmail or any other server later.
. Then in such case you need some third party app.I found you a library See here

Trying to send mail via SMTP. No mails arrives and no exception error

Problem: Have made a small mail program which works perfectly on my developer pc but when put into production it fails.
protected void Page_Load(object sender, EventArgs e)
{
string smtpHost = ConfigurationManager.AppSettings["SmtpAddress"];
MailMessage mail = new MailMessage();
mail.From = new MailAddress(ConfigurationManager.AppSettings["FromMailAddress"]);
mail.Sender = new MailAddress(ConfigurationManager.AppSettings["FromMailAddress"]);
mail.To.Add(new MailAddress("zzz#xxx.yy"));
mail.Subject = "Test mail";
mail.Body = string.Format("Is this mail sent via {0} ?", smtpHost);
lblMsg2.Text = string.Format("SmtpHost: {0}", smtpHost); ;
SmtpClient client = new SmtpClient(smtpHost);
try
{
client.Send(mail);
}
catch (Exception exception)
{
lblMsg3.Text = exception.Message.ToString();
lblMsg4.Text = exception.InnerException.ToString();
}
}
I do get the correct mail address and everything on the production server, but nothing ends in my email inbox :-(. I do not receive any exceptions.
I have tried using telnet on the same server and from there I am able to send mails.
I have tried installing WireShark which is looking at the network card on the server and when using telnet I do get the reponse I suspected, but from my program I do not receive anything.
Edited 2012-03-12 # 09:46 danish time
Have now updated the code to look like this
protected void Page_Load(object sender, EventArgs e)
{
string smtpHost = ConfigurationManager.AppSettings["SmtpAddress"];
MailMessage mail = new MailMessage();
mail.From = new MailAddress(ConfigurationManager.AppSettings["FromMailAddress"]);
mail.Sender = new MailAddress(ConfigurationManager.AppSettings["FromMailAddress"]);
mail.To.Add(new MailAddress("zzz#xxx.yy"));
mail.Subject = "Test mail";
mail.Body = string.Format("Is this mail sent via {0} ?", smtpHost);
lblMsg2.Text = string.Format("SmtpHost: {0}", smtpHost); ;
SmtpClient client = new SmtpClient(smtpHost);
client.Send(mail);
}
And quite interesting: Even when inserting an SMTP-server that does definately not exist, I still do not get any errors on my production environment. I do get an exception on my developer pc which basically means that the smtp-server does not exist (which I also expected to get a message about).
Case solved :-)
And I learned more about IIS!
The IIS was set up to "Store e-mail in Pickup directory" instead of "Deliver e-mail to SMTP server". Unfortunately I am not that good at IIS and I did not know that there was a setting like that... I am now!
The "double check you configuration settings" from #GarryM was unfortunately not enough for me or my mail-administrator to make us look at the IIS. I am too much a programmer and my mail-adm is too much a network guy :-)
Thank you everyone for your answers. It was partly because of all your good hints and ideas that I could leave out more and more parts.
Double-check the configuration of your mail server. If it isn't throwing an exception then the issue is most likely that the mail has been accepted, but it's not relaying it or potentially treating it as spam.
Some hosting providers also silently block some of the larger free mail hosts due to spam issues, if you are using a shared hosting provider it's worth asking them too.
Also have you tried running the same code locally but pointing at the live mail host? (Providing you can access it externally) That way you can step-through the code and ensure that an exception isn't getting thrown.
It would help if you removed the try/catch as this will allow any exception to propagate up.
Another thing to try is client.EnableSSL if you are using a secure connection, which many mail servers require.

Categories