Email confirmation link using office 365 in ASP.NET MVC [duplicate] - c#

We are testing the new Office 365 beta, and i have a mail account on the Exchange Online service. Now I'm trying to connect a LOB application that can send smtp emails from my test account.
However the Exchange 365 platform requires TLS encryption on port 587, and there is a 'feature' of System.Net.Mail that does not permit Implicit SSL encryption.
Has anyone managed to get C# sending mails via this platform?
I have the following basic code that should send the mail - any advice would be appreciated.
SmtpClient server = new SmtpClient("ServerAddress");
server.Port = 587;
server.EnableSsl = true;
server.Credentials = new System.Net.NetworkCredential("username#mydomain.com", "password");
server.Timeout = 5000;
server.UseDefaultCredentials = false;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("recipent#anyaddress");
mail.To.Add("username#mydomain.com");
mail.Subject = "test out message sending";
mail.Body = "this is my message body";
mail.IsBodyHtml = true;
server.Send(mail);

Fixed a few typos in the working code above:
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("someone#somedomain.com", "SomeOne"));
msg.From = new MailAddress("you#yourdomain.com", "You");
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("your user name", "your password");
client.Port = 587; // You can use Port 25 if 587 is blocked (mine is!)
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
lblText.Text = "Message Sent Succesfully";
}
catch (Exception ex)
{
lblText.Text = ex.ToString();
}
I have two web applications using the above code and both work fine without any trouble.

In year of 2020, these code seems to return exception as
System.Net.Mail.SmtpStatusCode.MustIssueStartTlsFirst or 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
This code is working for me.
using (SmtpClient client = new SmtpClient()
{
Host = "smtp.office365.com",
Port = 587,
UseDefaultCredentials = false, // This require to be before setting Credentials property
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("alias#fulldomain.com", "password"), // you must give a full email address for authentication
TargetName = "STARTTLS/smtp.office365.com", // Set to avoid MustIssueStartTlsFirst exception
EnableSsl = true // Set to avoid secure connection exception
})
{
MailMessage message = new MailMessage()
{
From = new MailAddress("alias#fulldomain.com"), // sender must be a full email address
Subject = subject,
IsBodyHtml = true,
Body = "<h1>Hello World</h1>",
BodyEncoding = System.Text.Encoding.UTF8,
SubjectEncoding = System.Text.Encoding.UTF8,
};
var toAddresses = recipients.Split(',');
foreach (var to in toAddresses)
{
message.To.Add(to.Trim());
}
try
{
client.Send(message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}

Quick answer: the FROM address must exactly match the account you are sending from, or you will get a error 5.7.1 Client does not have permissions to send as this sender.
My guess is that prevents email spoofing with your Office 365 account, otherwise you might be able to send as sballmer#microsoft.com.
Another thing to try is in the authentication, fill in the third field with the domain, like
Dim smtpAuth = New System.Net.NetworkCredential(
"TheDude", "hunter2password", "MicrosoftOffice365Domain.com")
If that doesn't work, double check that you can log into the account at: https://portal.microsoftonline.com
Yet another thing to note is your Antivirus solution may be blocking programmatic access to ports 25 and 587 as a anti-spamming solution. Norton and McAfee may silently block access to these ports. Only enabling Mail and Socket debugging will allow you to notice it (see below).
One last thing to note, the Send method is Asynchronous. If you call Dispose immediately after you call send, your are more than likely closing your connection before the mail is sent. Have your smtpClient instance listen for the OnSendCompleted event, and call dispose from there. You must use SendAsync method instead, the Send method does not raise this event.
Detailed Answer: With Visual Studio (VB.NET or C# doesn't matter), I made a simple form with a button that created the Mail Message, similar to that above. Then I added this to the application.exe.config (in the bin/debug directory of my project). This enables the Output tab to have detailed debug info.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net">
<listeners>
<add name="System.Net" />
</listeners>
</source>
<source name="System.Net.Sockets">
<listeners>
<add name="System.Net" />
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose" />
<add name="System.Net.Sockets" value="Verbose" />
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="System.Net.log"
/>
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
</configuration>

Office 365 use two servers, smtp server and protect extended sever.
First server is smtp.office365.com (property Host of smtp client) and second server is STARTTLS/smtp.office365.com (property TargetName of smtp client). Another thing is must put Usedefaultcredential =false before set networkcredentials.
client.UseDefaultCredentials = False
client.Credentials = New NetworkCredential("user#domain.com", "Password")
client.Host = "smtp.office365.com"
client.EnableSsl = true
client.TargetName = "STARTTLS/smtp.office365.com"
client.Port = 587
client.Send(mail)

Have you seen this?
Sending email using Smtp.mail.microsoftonline.com
Setting the UseDefaultCredentials after setting the Credentials would be resetting your Credentials property.

Here is a side note for some that may be searching this thread for an answer to this problem. (Be sure to read cautions at the bottom before implementing this solution.) I was having trouble sending emails for a client to which my MS Office 365 subscription did not have a user or domain for. I was trying to SMTP through my Me#MyDomain.com 365 account but the .NET mail message was addressed from Client#ClientDomain.com. This is when the "5.7.1 Client does not have permissions" error popped up for me. To remedy, the MailMessage class needed to have the Sender property set to an email address that my supplied SMTP credentials had permission in O365 to "Send As". I chose to use my main account email (Me#MyDomain.com) as seen in the code below. Keep in mind I could have used ANY email address my O365 account had permission to "send as" (i.e. Support#MyDomain.com, no-reply#MyDomain.com, etc.)
using System;
using System.Net.Mail;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (
MailMessage message = new MailMessage
{
To = { new MailAddress("Recipient1#Recipient1Domain.com", "Recipient 1") },
Sender = new MailAddress("Me#MyDomain.com", "Me"),
From = new MailAddress("Client#ClientDomain.com", "Client"),
Subject=".net Testing"
Body="Testing .net emailing",
IsBodyHtml=true,
}
)
{
using (
SmtpClient smtp = new SmtpClient
{
Host = "smtp.office365.com",
Port = 587,
Credentials = new System.Net.NetworkCredential("Me#MyDomain.com", "Pa55w0rd"),
EnableSsl = true
}
)
{
try { smtp.Send(message); }
catch (Exception excp)
{
Console.Write(excp.Message);
Console.ReadKey();
}
}
}
}
}
}
Please note SmtpClient is only disposable and able to use the Using block in .NET Framework 4
Users of .NET Framework 2 through 3.5 should use SmtpClient as such...
SmtpClient smtp = new SmtpClient
{
Host = "smtp.office365.com",
Port = 587,
Credentials = new System.Net.NetworkCredential("Me#MyDomain.com", "Pa55w0rd"),
EnableSsl = true
};
try { smtp.Send(message); }
catch (Exception excp)
{
Console.Write(excp.Message);
Console.ReadKey();
}
The resulting email's header will look something like this:
Authentication-Results: spf=none (sender IP is )
smtp.mailfrom=Me#MyDomain.com;
Received: from MyPC (192.168.1.1) by
BLUPR13MB0036.namprd13.prod.outlook.com (10.161.123.150) with Microsoft SMTP
Server (TLS) id 15.1.318.9; Mon, 9 Nov 2015 16:06:58 +0000
MIME-Version: 1.0
From: Client <Client#ClientDomain.com>
Sender: Me <Me#MyDomain.com>
To: Recipient 1 <Recipient1#Recipient1Domain.com>
-- Be Cautious --
Be aware some mail clients may display the Sender address as a note. For example Outlook will display something along these lines in the Reading Pane's header:
Me <Me#MyDomain.com> on behalf of Client <Client#ClientDomain.com>
However, so long as the email client the recipient uses isn't total garbage, this shouldn't effect the Reply To address. Reply To should still use the From address. To cover all your bases, you can also utilize the MailMessage.ReplyToList property to afford every opportunity to the client to use the correct reply address.
Also, be aware that some email servers may flat out reject any emails that are Sent On Behalf of another company siting Domain Owner Policy Restrictions. Be sure to test thoroughly and look for any bounce backs. I can tell you that my personal Hotmail (mail.live.com) email account is one that will reject messages I send on behalf of a certain client of mine but others clients go through fine. Although I suspect that it has something to do with my client's domain TXT "spf1" records, I do not have an answer as to why it will reject emails sent on behalf of one domain versus another. Maybe someone who knows can shed some light on the subject?

I've ported c# code used to work against smtp.google.com:587 to work via office365 without success. Tried all combinations of Credential before/after using Ssl and almost every recommendation made on the Internet - w/o success (got 5.7.1 .... error).
Finally got this line from somewhere as last resort, just before .Send(message)
smtpClient.TargetName = "STARTTLS/smtp.office365.com";
Since then - every send() is big success.

I got mine working with:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

FEB/2023:
It is the second time in two years that I have to review all Q&A regarding this topic and it is the second time that for me the solution is to disable Security Defaults in AD in order to enable SMTP auth.
If you still have these problems:
Go to Azure and switch to your directory
Select Active Directory --> Properties
At the bottom, click on "Manage security defaults"
Disable it and save.
Give it a couple of minutes and try your code again, if you followed the instructions and all SO questions then it should work now... And, please, take care about your security configuration.
I hope it helps

Finally, Works!
Put smtpClient.UseDefaultCredentials = false;
after smtpClient.Credentials = credentials;
then problem resolved!
SmtpClient smtpClient = new SmtpClient(smtpServerName);
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpUName, smtpUNamePwd);
smtpClient.Credentials = credentials;
smtpClient.UseDefaultCredentials = false; <-- Set This Line After Credentials
smtpClient.Send(mailMsg);
smtpClient = null;
mailMsg.Dispose();

Related

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

Exception using default SMTP credentials on Office365 - Client was not authenticated to send anonymous mail during MAIL FROM

I'm using NLog to send logs as email with a custom mail target. I am sending from my office365 account set up as the default in my web.config (of my main project) as follows:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="myusername#mydomain.com">
<network defaultCredentials="false" host="smtp.office365.com" port="587" userName="myusername#mydomain.com" password="mypassword" enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
I override the Write method with my log target (in my NLog implementation package) as follows:
protected override void Write(LogEventInfo logEvent)
{
try
{
using (var mail = new MailMessage())
{
this.SetupMailMessage(mail, logEvent, this.Layout.Render(logEvent));
using (SmtpClient smtpClient = new SmtpClient())
{
smtpClient.UseDefaultCredentials = true;
smtpClient.Send(mail);
}
}
}
catch (Exception exception)
{
throw new NLogRuntimeException("An error occurred when sending a log mail message.", exception);
}
}
When the system tries to send a mail from this account, the following System.Net.Mail.SmtpException is thrown:
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 have quadruple checked the credentials and they are correct. Does anyone know what else could be causing this exception?
UPDATE: It turns out the CredentialCache.DefaultCredentials property is full of empty strings. Yet, when I extract the settings manually using the below code I can get the settings from the web.config.
SmtpSection settings = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
smtpClient.Credentials = new NetworkCredential(settings.Network.UserName, settings.Network.Password);
smtpClient.Host = settings.Network.Host;
smtpClient.Port = settings.Network.Port;
smtpClient.EnableSsl = settings.Network.EnableSsl;
var creds = CredentialCache.DefaultCredentials; // Is empty
I can use this as a workaround. But what gives? Why would the default credentials be empty?
Thanks to this post, I was able to resolve our issues. We migrated mailboxes to O365 from a hybrid setup at Rackspace. The mailbox being used to send was not previously an Exchange account but became one after the migration.
mySmtpClient = New SmtpClient("smtp.office365.com")
mySmtpClient.Port = 587
mySmtpClient.EnableSsl = True
mySmtpClient.Credentials = New System.Net.NetworkCredential("email#domain.com", "password", "domain.com")
mySmtpClient.Send(Msg)
Previous setup did not require us to provide port or enable ssl or even put the domain in the credential parameters. Hope this helps with folks who have to work with VB scripts automating emails via SMTP with Office 365.
Although the workaround I mentioned in the answer update did work, I was not happy about manually fetching those values. The solution for me was to remove the line
smtpClient.UseDefaultCredentials = true;
from the original code I posted. It turns out that smtpClient is initialized with the default credentials I set up in the web.config, and the above removed line was overwriting them with empty strings from CredentialCache.DefaultCredentials. I still don't know why CredentialCache.DefaultCredentials is empty or when this is supposed to be populated from the web.config, but this was the source of my problem.
If anyone has any further insight into this please post a better answer!
When doing this integration on a third party hosting provider, you also need provide the domain name.
SmtpClient client = new SmtpClient(SMTPSettings.Url, SMTPSettings.Port);
client.Credentials = new System.Net.NetworkCredential(SMTPSettings.UserName, SMTPSettings.Password, SMTPSettings.Domain);
I had the same issue, what it worked for me was to use the System.Security.SecureString to put the password instead of string, example:
System.Security.SecureString psw = new System.Security.SecureString();
string PasswordGmail = "XXXXXX";
foreach (char item in PasswordGmail.ToCharArray())
{
psw.AppendChar(item);
}
client.Credentials = new System.Net.NetworkCredential("XXXX#xxx.com", psw);

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

Can't auth to Gmail smtp via MailMessage & smtpClient

I cannot figure out for the life of my why this isn't working
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
UseDefaultCredentials = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("myemail#gmail.com", "myGmailPasswordHere"),
EnableSsl = true,
Timeout = 10000
};
smtp.Send(mail);
I get:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
I just specified EnableSsl to true so that shouldn't be the issue in terms of secure connection.
I'm running this from localhost. And yes, my username and password I'm entering to auth (my gmail account credentials) is 100% right.
I know this is an old topic, BUT... Google has changed something on their security settings.
Was struggling with all the answers until I checked my email with a mail from Google stating that "we've recently blocked a sign-in attempt on your Google account".
That led me to this page:
Google Account Security
Under the "Access for less secure apps" section, you can enable access to your account from other devices/applications... like your C# application.
Note, there is no longer an "application specific" section.
Hope this helps someone... I just lost 30 minutes of my life...
If login info is 100% right, you need to set UseDefaultCredentials = false first and then set the credentials you want to use Credentials = new NetworkCredential("myemail#gmail.com", "myGmailPasswordHere").
If you set the credentials first, when you set UseDefaultCredentials = false this will make the Credentials property to null.
This is wired, but it happened to me.
Debug your code and check if the Credentials property is null before you call smtp.Send(message);. If so, then try inverting the order. It seems you have it in the right order, but if it's null, don't use the inline initialization.
Hope it helps.
EDIT: If you are using two-step verification, be sure you are using an App Specific password
It looks like Gmail requires Application-specific password(not your main password).
Please, look into this: http://support.google.com/mail/bin/answer.py?hl=en&answer=1173270
I had the same problem recently.
This worked just fine for me
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
UseDefaultCredentials = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("myid#gmail.com", "mypassword"),
EnableSsl = true,
Timeout = 10000
};
MailMessage message = new MailMessage();
message.Body = "hello there";
message.Subject = "hi!!";
message.To.Add("myid#gmail.com");
message.From = new MailAddress("myid#gmail.com");
smtp.Send(message);
I had this problem before and fixed it by following these steps:
Go to "My Account" settings.
Click "Sign-in & Security" category.
Scroll down to "Connected apps & sites" section.
turn off the "Allow less secure apps" option.
I just turned this option off and my code ran successfully.
For me the solution required 2 "steps":
set UseDefaultCredentials = false first, then set the credentials I want to use Credentials = new NetworkCredential("myemail#gmail.com", "myGmailPasswordHere"). Setting the credentials first, when I set UseDefaultCredentials = false will make the Credentials property null.
Allow less secure apps on my Google profile.
Have a callback as follows. Tell System.Net to ignore the error!
Add this before call to Send()
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
smtp.Send(mail);
<mailSettings>
<smtp from="youremail#gmail.com">
<network host="smtp.gmail.com" password="yourpassword" port="587" userName="username"/>
</smtp>
</mailSettings>
Edit: try adding this line smtp.Credentials = Credentials after this
Credentials = new NetworkCredential("myemail#gmail.com", "myGmailPasswordHere"),
Had the same issue accessing smtp.gmail.com from an ASP.NET application running on Amazon AWS hosting. It turned out that my configuration was right - it was also working fine from another computer - but gmail would deny my login attempt, because I try logging in from an unusual location.
I logged on to gmail over the web interface (www.gmail.com), and had to answer a captcha. After that it worked.
My problem was that the domain-owner for our gmail-account had disabled both "Access for less secure apps" and two step authentication. There was no way to enable it, I couldn't even see the setting. So I tested with my personal account instead, and it worked fine.
Very simple just follow this for C# WPF Application:
private void SendByGmail(string subject, string body, string recepientEmail, string MailMsgFrom, string MailMsgPass)
{
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress(MailMsgFrom);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
mailMessage.Priority = System.Net.Mail.MailPriority.High;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.Timeout = 200000;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = MailMsgFrom;
NetworkCred.Password = MailMsgPass;
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mailMessage);
}
}
After that you should get like this Error
smtpException {"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at"} System.Net.Mail.SmtpException
To Solve this problem, at first login your email account to your google account in web browser. Then just follow this link Google Account Activity. Then you'll get recent Devices & activity by your account. If show block your current activity from your current device. Just Unblock this. Then try again to send email. Thanks

How to Send Email via Yandex SMTP (C# ASP.NET)

Formerly, I used my server as mail host and was sending emails via my own host. Now, I use Yandex as my mail server. I'm trying to send emails via Yandex SMTP. However, I could not achieve it. I get "the operation has timed out" message every time. I'm able to send & receive email with the same settings when I use Thunderbird. Hence, there is no issue with the account. I appreciate your guidance. You can see my code below:
EmailCredentials credentials = new EmailCredentials();
credentials.Domain = "domain.com";
credentials.SMTPUser = "email#domain.com";
credentials.SMTPPassword = "password";
int SmtpPort = 465;
string SmtpServer = "smtp.yandex.com";
System.Net.Mail.MailAddress sender = new System.Net.Mail.MailAddress(senderMail, senderName, System.Text.Encoding.UTF8);
System.Net.Mail.MailAddress recipient = new System.Net.Mail.MailAddress(recipientEmail, recipientName, System.Text.Encoding.UTF8);
System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage(sender, recipient);
email.BodyEncoding = System.Text.Encoding.UTF8;
email.SubjectEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(mailBody, #"<(.|\n)*?>", string.Empty), null, MediaTypeNames.Text.Plain);
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailBody, null, MediaTypeNames.Text.Html);
email.AlternateViews.Clear();
email.AlternateViews.Add(plainView);
email.AlternateViews.Add(htmlView);
email.Subject = mailTitle;
System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient();
SMTP.Host = SmtpServer;
SMTP.Port = SmtpPort;
SMTP.EnableSsl = true;
SMTP.Credentials = new System.Net.NetworkCredential(credentials.SMTPUser, credentials.SMTPPassword);
SMTP.Send(email);
After so many trials & errors, I have found how to make it work. I have made the following changes on the code posted in the question:
Set SmtpPort = 587
Added the following 2 lines of code:
SMTP.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
SMTP.UseDefaultCredentials = false;
Additional note:
I use Azure server. I realized later that I did not configure the smtp endpoint for port 465. That being said, I had to add the 2 lines of code above in order to make email delivery work, just changing the port was not enough. My point is it is worth to check the defined ports on Azure and firewall before doing anything further.
I was able to make my code work by getting help from #Uwe and also #Dima-Babich, #Rail who posted on the following page Yandex smtp settings with ssl
. Hence, I think credits to answer this question should go to them.
Try using port 25 instead of 465 specified in Yandex help. I found this info on https://habrahabr.ru/post/237899/. They mentioned that it might be due to the fact that explicit SSL mode was implemented in the SmtpClient. Then port 25 is used for establishing connection in unencrypted mode and after that, protected mode is switched on.
I had the same problem.
I solved it by going to the Yandex mail, and then change some settings.
Go to:
1- Settings.
2- Email clients.
3- Set selected POP3 setting that is all.

Categories