Can't auth to Gmail smtp via MailMessage & smtpClient - c#

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

Related

C#. SMTP The server response was: 5.7.0 Authentication Required

Error: The SMTP server requires a secure connecton or the client was not authenticated. The server
response was: 5.7.0 Authentication Required. Learn more at.
private void SendMail(string email, string firstname)
{
MailAddress from = new MailAddress($"{email}", $"{firstname}");
MailAddress to = new MailAddress($"{email}");
MailMessage m = new MailMessage(from, to);
m.Subject = "TEST";
m.Body = "<h2>TEST</h2>";
m.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new NetworkCredential("jewralyapp#mail.ru", "password");
smtp.EnableSsl = true;
smtp.Send(m);
}
I want to send a letter to the mail, but the error that I indicated above comes out, here is the code, can you tell me what is wrong?
I see that your email is #mail.ru and the server is gmail, is that correct? I think you need to use your gmail account.
You also need enable weaker credentials on your gmail account. Forgot what they actually call it but it's on gmail security setting.
I had also faced the same problem.
Your SmtpClient is gmail, but you are using "jewralyapp#mail.ru"!!!
Make sure to set "Less secure app access" to ON in your Gmail security setting.
In my case, the problem was solved.

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

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();

Send mail to outlook account ASP.Net C#

So far this is what i've tried, I want to send an email to our school email account with format of jcvborlagdan#mymail.mapua.edu.ph or something like jcborlagdan#mapua.edu.ph. I'm sure that this is an outlook account so I took the smtp settings for outlook, but when I do this I keep on encountering the following error:
Failure sending mail.
What am I doing wrong here? I already search for the error but all of the answers are showing same syntax with mine except for the smtp settings. So there must be something wrong with my smtp settings for outlook.
SmtpClient smtpClient = new SmtpClient("smtp-mail.outlook.com", 25); //587
smtpClient.Credentials = new System.Net.NetworkCredential("mymail#mapua.edu.ph", "myPassword");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#mapua.edu.ph", "CTMIS-no-reply");
mail.To.Add(new MailAddress("carlo.borlagdan#the-v.net"));
mail.CC.Add(new MailAddress("jcborlagdan#ymail.com"));
smtpClient.Send(mail);
Some small changes were required to get your code working.
UseDefaultCredentials need to be set to False since you want to use custom credentials
UseDefaultCredentials need to be set to False before setting the credentials.
SSL port is 587 for Outlook.
Thats all.
Here is the code fixed.
SmtpClient smtpClient = new SmtpClient("smtp-mail.outlook.com", 587); //587
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("mymail#mapua.edu.ph", "myPassword");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#mapua.edu.ph", "CTMIS-no-reply");
mail.To.Add(new MailAddress("carlo.borlagdan#the-v.net"));
mail.CC.Add(new MailAddress("jcborlagdan#ymail.com"));
smtpClient.Send(mail);
Concerning UseDefaultCredentials
From MSDN:
Some SMTP servers require that the client be authenticated before the server sends e-mail on its behalf. Set this property to true when this SmtpClient object should, if requested by the server, authenticate using the default credentials of the currently logged on user.
--
Since you don't want to authenticate using your Windows credentials, the
property is set to False. As for the fact you need to put it before, I have no official source but it simply does not work if you set your credentials before setting that property to false.

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);

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