A OTP porgram getting error (Failure sending mail) [duplicate] - c#

I am using the SmtpClient library to send emails using the following:
SmtpClient client = new SmtpClient();
client.Host = "hostname";
client.Port = 465;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("User", "Pass);
client.Send("from#hostname", "to#hostname", "Subject", "Body");
The code works fine in my test environment, but when I use production SMTP servers, the code fails with an SmtpException "Failure sending mail." with an inner IOException "Unable to read data from the transport connection: net_io_connectionclosed".
I've confirmed that firewalls are not an issue. The port opens just fine between the client and the server. I'm not sure what else could throw this error.

EDIT: Super Redux Version
Try port 587 instead of 465. Port 465 is technically deprecated.
After a bunch of packet sniffing I figured it out. First, here's the short answer:
The .NET SmtpClient only supports encryption via STARTTLS. If the EnableSsl flag is set, the server must respond to EHLO with a STARTTLS, otherwise it will throw an exception. See the MSDN documentation for more details.
Second, a quick SMTP history lesson for those who stumble upon this problem in the future:
Back in the day, when services wanted to also offer encryption they were assigned a different port number, and on that port number they immediately initiated an SSL connection. As time went on they realized it was silly to waste two port numbers for one service and they devised a way for services to allow plaintext and encryption on the same port using STARTTLS. Communication would start using plaintext, then use the STARTTLS command to upgrade to an encrypted connection. STARTTLS became the standard for SMTP encryption. Unfortunately, as it always happens when a new standard is implemented, there is a hodgepodge of compatibility with all the clients and servers out there.
In my case, my user was trying to connect the software to a server that was forcing an immediate SSL connection, which is the legacy method that is not supported by Microsoft in .NET.

Putting this at the beginning of my method fixed this for me
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12

For anyone who stumbles across this post looking for a solution and you've set up SMTP sendgrid via Azure.
The username is not the username you set up when you've created the sendgrid object in azure. To find your username;
Click on your sendgrid object in azure and click manage. You will be redirected to the SendGrid site.
Confirm your email and then copy down the username displayed there.. it's an automatically generated username.
Add the username from SendGrid into your SMTP settings in the web.config file.
Hope this helps!

Change port from 465 to 587 and it will work.

I've tried all the answers above but still get this error with Office 365 account. The code seems to work fine with Google account and smtp.gmail.com when allowing less secure apps.
Any other suggestions that I could try?
Here is the code that I'm using
int port = 587;
string host = "smtp.office365.com";
string username = "smtp.out#mail.com";
string password = "password";
string mailFrom = "noreply#mail.com";
string mailTo = "to#mail.com";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";
using (SmtpClient client = new SmtpClient())
{
MailAddress from = new MailAddress(mailFrom);
MailMessage message = new MailMessage
{
From = from
};
message.To.Add(mailTo);
message.Subject = mailTitle;
message.Body = mailMessage;
message.IsBodyHtml = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = host;
client.Port = port;
client.EnableSsl = true;
client.Credentials = new NetworkCredential
{
UserName = username,
Password = password
};
client.Send(message);
}
UPDATE AND HOW I SOLVED IT:
Solved problem by changing Smtp Client to Mailkit. The System.Net.Mail Smtp Client is now not recommended to use by Microsoft because of security issues and you should instead be using MailKit. Using Mailkit gave me clearer error messages that I could understand finding the root cause of the problem (license issue). You can get Mailkit by downloading it as a Nuget Package.
Read documentation about Smtp Client for more information:
https://learn.microsoft.com/es-es/dotnet/api/system.net.mail.smtpclient?redirectedfrom=MSDN&view=netframework-4.7.2
Here is how I implemented SmtpClient with MailKit
int port = 587;
string host = "smtp.office365.com";
string username = "smtp.out#mail.com";
string password = "password";
string mailFrom = "noreply#mail.com";
string mailTo = "mailto#mail.com";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";
var message = new MimeMessage();
message.From.Add(new MailboxAddress(mailFrom));
message.To.Add(new MailboxAddress(mailTo));
message.Subject = mailTitle;
message.Body = new TextPart("plain") { Text = mailMessage };
using (var client = new SmtpClient())
{
client.Connect(host , port, SecureSocketOptions.StartTls);
client.Authenticate(username, password);
client.Send(message);
client.Disconnect(true);
}

You may also have to change the "less secure apps" setting on your Gmail account. EnableSsl, use port 587 and enable "less secure apps". If you google the less secure apps part there are google help pages that will link you right to the page for your account. That was my problem but everything is working now thanks to all the answers above.

Answer Specific to Outlook Mailer
var SmtpClient = new SmtpClient{
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential("email", "password"),
Port = 587,
Host = "smtp.office365.com",
EnableSsl = true }
https://admin.exchange.microsoft.com/#/settings
-> Click on Mail Flow
-> Check - Turn on use of legacy TLS clients
-> Save

removing
client.UseDefaultCredentials = false;
seemed to solve it for me.

Does your SMTP library supports encrypted connection ? The mail server might be expecting secure TLS connection and hence closing the connection in absence of a TLS handshake

If you are using an SMTP server on the same box and your SMTP is bound to an IP address instead of "Any Assigned" it may fail because it is trying to use an IP address (like 127.0.0.1) that SMTP is not currently working on.

To elevate what jocull mentioned in a comment, I was doing everything mention in this thread and striking out... because mine was in a loop to be run over and over; after the first time through the loop, it would sometimes fail. Always worked the first time through the loop.
To be clear: the loop includes the creation of SmtpClient, and then doing .Send with the right data. The SmtpClient was created inside a try/catch block, to catch errors and to be sure the object got destroyed before the bottom of the loop.
In my case, the solution was to make sure that SmtpClient was disposed after each time in the loop (either via using() statement or by doing a manual dispose). Even if the SmtpClient object is being implicitly destroyed in the loop, .NET appears to be leaving stuff lying around to conflict with the next attempt.

Change your port number to 587 from 465

I got the same problem with the .NET smtp client + office 365 mail server: sometimes mails were sent successfully, sometimes not (intermittent sending failures).
The problem was fixed by setting the desired TLS version to 1.2 only. The original code (which started to fail in the middle of the year 2021 - BTW) was allowing TLS 1.0, TLS 1.1 and TLS 1.2.
Code (CLI/C++)
int tls12 = 3072; // Tls12 is not defined in the SecurityProtocolType enum in CLI/C++ / ToolsVersion="4.0"
System::Net::ServicePointManager::SecurityProtocol = (SecurityProtocolType) tls12;
(note: the problem was reproduced and fixed on a Win 8.1 machine)

First Use Port = 587
Generally STARTTLS is required to send mail, Adding the Security Protocol Tls12 will help to resolve this issue.
Secondly test the stmp connection using powershell
$userName = 'username_here'
$password = 'xxxxxxxxx'
$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $pwdSecureString
$sendMailParams = #{
From = 'abc.com'
To = 'xyz#gmail.com'
Subject = 'Test SMTP'
Body = 'Test SMTP'
SMTPServer = 'smtp.server.com'
Port = 587
UseSsl = $true
Credential = $credential
}
Send-MailMessage #sendMailParams
Thirdly If this send out the email, Add below code inside SmtpClient function:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Since Jan 22 2022, Google has increased the TLS version requirements Also Microsoft has revoked the support for TLS 1.0 and TLS 1.1 for the earlier versions of the .NET framework than 4.6.
So we can fix the issue one of the below 2 solutions.
1.By Adding some other Protocols before creating the smtp client >> ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
2.You just need to update the .NET framework version to 4.6 or higher to fix the issue.

In my case, the customer forgot to add new IP address in their SMTP settings. Open IIS 6.0 in the server which sets up the smtp, right click Smtp virtual server, choose Properties, Access tab, click Connections, add IP address of the new server. Then click Relay, also add IP address of the new server. This solved my issue.

If your mail server is Gmail (smtp.google.com), you will get this error when you hit the message limit. Gmail allows sending over SMTP up to only 2000 messages per 24 hours.

I ran into this when using smtp.office365.com, using port 587 with SSL. I was able to log in to the account using portal.office.com and I could confirm the account had a license. But when I fired the code to send emails, I kept getting the net_io_connectionclosed error.
Took me some time to figure it out, but the Exchange admin found the culprit. We're using O365 but the Exchange server was in a hybrid environment. Although the account we were trying to use was synced to Azure AD and had a valid O365 license, for some reason the mailbox was still residing on the hybrid Exchange server - not Exchange online. After the exchange admin used the "Move-Mailbox" command to move the mailbox from the hybrid exchange server to O365 we could use the code to send emails using o365.

If you are using Sendgrid and if you receive this error, it is because Basic authentication is no more allowed by sendgrid.We need to create API key and use them as NetworkCredential. username="apikey" password will be your API key
Reference - https://docs.sendgrid.com/for-developers/sending-email/integrating-with-the-smtp-api

I recently had to set new mail settings on all our applications and encountered this error on multiple projects.
The solution for me was to update the target framework to a newer version on some of my projects.
I also had an ASP.net website project where updating the target framework wasn't enough I also had to add the following code to the web.config <httpRuntime targetFramework="4.8"/>

After trying all sorts of TLS/SSL/port/etc things, for me the issue was this: the username and password I was using for Credentials were not correct, apparently.
Normally our websites use a different set of credentials but this one's were different. I had assumed they were correct but apparently not.
So I'd double check my credentials if nothing else is working for you. What a precise error message!

Try this : Here is the code which i'm using to send emails to multiple user.
public string gmail_send()
{
using (MailMessage mailMessage =
new MailMessage(new MailAddress(toemail),
new MailAddress(toemail)))
{
mailMessage.Body = body;
mailMessage.Subject = subject;
try
{
SmtpClient SmtpServer = new SmtpClient();
SmtpServer.Credentials =
new System.Net.NetworkCredential(email, password);
SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
mail = new MailMessage();
String[] addr = toemail.Split(','); // toemail is a string which contains many email address separated by comma
mail.From = new MailAddress(email);
Byte i;
for (i = 0; i < addr.Length; i++)
mail.To.Add(addr[i]);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
mail.DeliveryNotificationOptions =
DeliveryNotificationOptions.OnFailure;
// mail.ReplyTo = new MailAddress(toemail);
mail.ReplyToList.Add(toemail);
SmtpServer.Send(mail);
return "Mail Sent";
}
catch (Exception ex)
{
string exp = ex.ToString();
return "Mail Not Sent ... and ther error is " + exp;
}
}
}

In case if all above solutions don't work for you then try to update following file to your server (by publish i mean, and a build before that would be helpful).
bin-> projectname.dll
After updating you will see this error.
as i have solved with this solution.

For outlook use following setting that is not giving error to me
SMTP server name smtp-mail.outlook.com
SMTP port 587

This error is very generic .It can be due to many reason such as
The mail server is incorrect.
Some hosting company uses mail.domainname format.
If you just use domain name it will not work.
check credentials
host name
username password if needed
Check with hosting company.
<smtp from="info#india.uu.com">
<!-- Uncomment to specify SMTP settings -->
<network host="domain.com" port="25" password="Jin#" userName="info#india.xx.com"/>
</smtp>
</mailSettings>

In my case the web server IP was blocked on the mail server, it needs to be unblocked by your hosting company and make it whitelisted. Also, use port port 587.

My original problem is about intermittent sending failures. E.g. First Send() succeeds, 2nd Send() fails, 3rd Send() succeeds. Initially I thought I wasn't disposing properly. So I resorted to using().
Anyways, later I added the UseDefaultCredentials = false, and the Send() finally became stable.
Not sure why though.

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed
There are two solutions. First solution is for app level (deployment required) and second one is for machine level (especially if you use an out-of-the-box / off-the-shelf app)
When we checked the exception, we saw that the protocol is "ssl|tls" depriciated pair.
Since we don't want to deploy, we prefer machine level change (Solution 2).
On August 18, Microsoft announced that they will disable Transport Layer Security (TLS) 1.0 and 1.1 connections to Exchange Online β€œin 2022.”
https://office365itpros.com/2021/08/19/exchange-online-to-introduce-legacy-smtp-endpoint-in-2022/
Firstly let's check the network (Anything prevents your email sent request? firewall, IDS, etc.)
By using PowerShell check Transport Layer Security protocols
[Net.ServicePointManager]::SecurityProtocol
My Output: Tls, Tls11, Tls12
Test SMTP Authentication over TLS
$HostName = [System.Net.DNS]::GetHostByName($Null).HostName
$Message = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("smtp.office365.com", 587)
$smtp.Credentials = New-Object System.Net.NetworkCredential("me#me.com", "PassMeme");
$smtp.EnableSsl = $true
$smtp.Timeout = 400000
$Message.From = "sender#me.com"
$Message.Subject = $HostName + " PowerShell Email Test"
$Message.Body = "Email Body Message"
$Message.To.Add("receiver#me.com")
#$Message.Attachments.Add("C:\foo\attach.txt")
$smtp.Send($Message)
My output:
There is no error message
If there is any message on your output something prevents your email sent request.
If everything is ok there should be two solutions.
Solution 1:
Application Level TLS 1.2 Configuration (Optional)
Application deployment required.
Explicitly choose TLS in C# or VB code:
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12
Solution 2:
Machine level TLS 1.2 .NET Framework configuration
Application deployment NOT required.
Set the SchUseStrongCrypto registry setting to DWORD:00000001. You should restart the server.
For 32-bit applications on 32-bit systems or 64-bit applications on 64-bit systems), update the following subkey value:
HKEY_LOCAL_MACHINE\SOFTWARE\
\Microsoft\.NETFramework\\<version>
SchUseStrongCrypto = (DWORD): 00000001
For 32-bit applications that are running on x64-based systems, update the following subkey value:
HKEY_LOCAL_MACHINE\SOFTWARE\
Wow6432Node\Microsoft\\.NETFramework\\<version>
SchUseStrongCrypto = (DWORD): 00000001
For details "How to enable TLS 1.2 on clients" on
https://learn.microsoft.com/en-us/mem/configmgr/core/plan-design/security/enable-tls-1-2-client

Our email service is Azure SendGrid.
Our application stopped sending emails one day, and the error message was "SmtpException: Unable to receive data from the transport connection: net io connectionclosed." We discovered the problem was caused by the fact that our Pro 300K subscription had run out. Emails began to be sent when we upped our subscription.

I was facing the same issue with my .NET application.
ISSUE: The .NET version that I was using is 4.0 which was creating the whole mess.
REASON: The whole reason behind the issue is that Microsoft has revoked the support for TLS 1.0 and TLS 1.1 for the earlier versions of the .NET framework than 4.6.
FIX: You just need to update the .NET framework version to 4.6 or higher to fix the issue.

Related

c# sending email 2022 [duplicate]

For some reason neither the accepted answer nor any others work for me for "Sending email in .NET through Gmail". Why would they not work?
UPDATE: I have tried all the answers (accepted and otherwise) in the other question, but none of them work.
I would just like to know if it works for anyone else, otherwise Google may have changed something (which has happened before).
When I try the piece of code that uses SmtpDeliveryMethod.Network, I quickly receive an SmtpException on Send(message). The message is
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" <-- seriously, it ends there.
UPDATE:
This is a question that I asked a long time ago, and the accepted answer is code that I've used many, many times on different projects.
I've taken some of the ideas in this post and other EmailSender projects to create an EmailSender project at Codeplex. It's designed for testability and supports my favourite SMTP services such as GoDaddy and Gmail.
CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.
Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername#gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername#gmail.com", "myusername#gmail.com", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
}
}
}
I also got it working using a combination of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx and code (because there is no matching EnableSsl in the configuration file :( ).
2021 Update
By default you will also need to enable access for "less secure apps" in your gmail settings page: google.com/settings/security/lesssecureapps. This is necessary if you are getting the exception "`The server response was: 5.5.1 Authentication Required. – thanks to #Ravendarksky
In addition to the other troubleshooting steps above, I would also like to add that if you have enabled two-factor authentication (also known as two-step verification) on your GMail account, you must generate an application-specific password and use that newly generated password to authenticate via SMTP.
To create one, visit: https://www.google.com/settings/ and choose Authorizing applications & sites to generate the password.
THE FOLLOWING WILL ALMOST CERTAINLY BE THE ANSWER TO YOUR QUESTION IF ALL ELSE HAS FAILED:
I got the exact same error, it turns out Google's new password strength measuring algorithm has changed deeming my current password as too weak, and not telling me a thing about it (not even a message or warning)... How did I discover this? Well, I chose to change my password to see if it would help (tried everything else to no avail) and when I changed my password, it worked!
Then, for an experiment, I tried changing my password back to my previous password to see what would happen, and Gmail didn't actually allow me to do this, citing the reason "sorry we cannot allow you to save this change as your chosen password is too weak" and wouldn't let me go back to my old password. I figured from this that it was erroring out because either a) you need to change your password once every x amount of months or b). As I said before, their password strength algorithms changed and therefore the weak password I had was not accepted, even though they did not say anything about this when trying to login ANYWHERE! This (number 2) is the most likely scenario, as my weak password was about 4 months old, and it let me use it in Gmail.
It's pretty bad that they said nothing about this, but it makes sense. Because most hijacked emails are logged into using software outside of gmail, and I'm guessing you are required to have a stronger password if you want to use Gmail outside of the Gmail environment.
Turn On Access For Less Secure Apps and it will work for all no need
to change password.
Link to Gmail Setting
I've had some problems sending emails from my gmail account too, which were due to several of the aforementioned situations.
Here's a summary of how I got it working, and keeping it flexible at the same time:
First of all setup your GMail account:
Enable IMAP and assert the right maximum number of messages (you can do so here)
Make sure your password is at least 7 characters and is strong (according to Google)
Make sure you don't have to enter a captcha code first. You can do so by sending a test email from your browser.
Make changes in web.config (or app.config, I haven't tried that yet but I assume it's just as easy to make it work in a windows application):
<configuration>
<appSettings>
<add key="EnableSSLOnMail" value="True"/>
</appSettings>
<!-- other settings -->
...
<!-- system.net settings -->
<system.net>
<mailSettings>
<smtp from="yourusername#gmail.com" deliveryMethod="Network">
<network
defaultCredentials="false"
host="smtp.gmail.com"
port="587"
password="stR0ngPassW0rd"
userName="yourusername#gmail.com"
/>
<!-- When using .Net 4.0 (or later) add attribute: enableSsl="true" and you're all set-->
</smtp>
</mailSettings>
</system.net>
</configuration>
Add a Class to your project:
Imports System.Net.Mail
Public Class SSLMail
Public Shared Sub SendMail(ByVal e As System.Web.UI.WebControls.MailMessageEventArgs)
GetSmtpClient.Send(e.Message)
'Since the message is sent here, set cancel=true so the original SmtpClient will not try to send the message too:
e.Cancel = True
End Sub
Public Shared Sub SendMail(ByVal Msg As MailMessage)
GetSmtpClient.Send(Msg)
End Sub
Public Shared Function GetSmtpClient() As SmtpClient
Dim smtp As New Net.Mail.SmtpClient
'Read EnableSSL setting from web.config
smtp.EnableSsl = CBool(ConfigurationManager.AppSettings("EnableSSLOnMail"))
Return smtp
End Function
End Class
And now whenever you want to send emails all you need to do is call SSLMail.SendMail:
e.g. in a Page with a PasswordRecovery control:
Partial Class RecoverPassword
Inherits System.Web.UI.Page
Protected Sub RecoverPwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles RecoverPwd.SendingMail
e.Message.Bcc.Add("webmaster#example.com")
SSLMail.SendMail(e)
End Sub
End Class
Or anywhere in your code you can call:
SSLMail.SendMail(New system.Net.Mail.MailMessage("from#from.com","to#to.com", "Subject", "Body"})
I hope this helps anyone who runs into this post! (I used VB.NET but I think it's trivial to convert it to any .NET language.)
Oh...It's amazing...
First I Couldn't send an email for any reasons.
But after I changed the sequence of these two lines as below, it works perfectly.
//(1)
client.UseDefaultCredentials = true;
//(2)
client.Credentials = new System.Net.NetworkCredential("username#gmail.com", "password");
Dim SMTPClientObj As New Net.Mail.SmtpClient
SMTPClientObj.UseDefaultCredentials = False
SMTPClientObj.Credentials = New System.Net.NetworkCredential("myusername#gmail.com", "mypwd")
SMTPClientObj.Host = "smtp.gmail.com"
SMTPClientObj.Port = 587
SMTPClientObj.EnableSsl = True
SMTPClientObj.Send("myusername#gmail.com","yourusername#gmail.com","test","testbody")
If you get an error like "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" as I get before this, make sure the line SMTPClientObj.UseDefaultCredentials = False included and this line should before the SMTPClientObj.Credentials.
I did try to switch these 2 lines the opposite way and the 5.5.1 Authentication Required error returned.
The problem is not one of technical ability to send through gmail. That works for most situations. If you can't get a machine to send, it is usually due to the machine not having been authenticated with a human at the controls at least once.
The problem that most users face is that Google decides to change the outbound limits all the time. You should always add defensive code to your solution. If you start seeing errors, step off your send speed and just stop sending for a while. If you keep trying to send Google will sometimes add extra time to your delay period before you can send again.
What I have done in my current system is to send with a 1.5 second delay between each message. Then if I get any errors, stop for 5 minutes and then start again. This usually works and will allow you to send up to the limits of the account (last I checked it was 2,000 for premier customer logins per day).
I had the same problem, but it turned out to be my virus protection was blocking outgoing "spam" email. Turning this off allowed me to use port 587 to send SMTP email via GMail
Simple steps to fix this:
1)Sign in to your Gmail
2)Navigate to this page https://www.google.com/settings/security/lesssecureapps & set to "Turn On"
If nothing else has worked here for you you may need to allow access to your gmail account from third party applications. This was my problem. To allow access do the following:
Sign in to your gmail account.
Visit this page https://accounts.google.com/DisplayUnlockCaptcha and click on button to allow access.
Visit this page https://www.google.com/settings/security/lesssecureapps and enable access for less secure apps.
This worked for me hope it works for someone else!
I'm not sure which .NET version is required for this because eglasius mentioned there is no matching enableSsl setting (I'm using .NET 4.0, but I suspect it to work in .NET 2.0 or later), but this configuration justed worked for me (and doesn't require you to use any programmatic configuration):
<system.net>
<mailSettings>
<smtp from="myusername#gmail.com" deliveryMethod="Network">
<network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" port="587" password="password" userName="myusername#gmail.com"/>
</smtp>
</mailSettings>
</system.net>
You might have to enable POP or IMAP on your Gmail account first:
https://mail.google.com/mail/?shva=1#settings/fwdandpop
I recommend trying it with a normal mail client first...
I was using corporate VPN connection. It was the reason why I couldn't send email from my application. It works if I disconnect from VPN.
I also found that the account I used to log in was de-activated by google for some reason. Once I reset my password (to the same as it used to be), then I was able to send emails just fine. I was getting 5.5.1 message also.
I had also try to many solution but make some changes it will work
host = smtp.gmail.com
port = 587
username = email#gmail.com
password = password
enabledssl = true
with smtpclient above parameters are work in gmail
#Andres Pompiglio: Yes that's right you must change your password at least once..
this codes works just fine:
//Satrt Send Email Function
public string SendMail(string toList, string from, string ccList,
string subject, string body)
{
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
try
{
MailAddress fromAddress = new MailAddress(from);
message.From = fromAddress;
message.To.Add(toList);
if (ccList != null && ccList != string.Empty)
message.CC.Add(ccList);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
// We use gmail as our smtp client
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential(
"Your Gmail User Name", "Your Gmail Password");
smtpClient.Send(message);
msg = "Successful<BR>";
}
catch (Exception ex)
{
msg = ex.Message;
}
return msg;
}
//End Send Email Function
AND you can make a call to the function by using:
Response.Write(SendMail(recipient Address, "UserName#gmail.com", "ccList if any", "subject", "body"))
I was getting the same error and none of the above solutions helped.
My problem was that I was running the code from a remote server, which had never been used to log into the gmail account.
I opened a browser on the remote server and logged into gmail from there. It asked a security question to verify it was me since this was a new location. After doing the security check I was able to authenticate through code.
Turn on less secure apps for your account: https://www.google.com/settings/security/lesssecureapps
First check your gmail account setting & turn On from "Access for less secure apps"
We strongly recommend that you use a secure app, like Gmail, to access your account. All apps made by Google meet these security standards. Using a less secure app, on the other hand, could leave your account vulnerable. Learn more.
Set
smtp.UseDefaultCredentials = false;
before
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
I ran into this same error ( "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" ) and found out that I was using the wrong password. I fixed the login credentials, and it sent correctly.
I know this is late, but maybe this will help someone else.
Another thing that I've found is that you must change your password at least once.
And try to use a secure level password (do not use the same user as password, 123456, etc.)
Yet another possible solution for you. I was having similar problems connecting to gmail via IMAP. After trying all the solutions that I came across that you will read about here and elsewhere on SO (eg. enable IMAP, enable less secure access to your mail, using https://accounts.google.com/b/0/displayunlockcaptcha and so on), I actually set up a new gmail account once more.
In my original test, the first gmail account I had created, I had connected to my main gmail account. This resulted in erratic behaviour where the wrong account was being referenced by google. For example, running https://accounts.google.com/b/0/displayunlockcaptcha opened up my main account rather than the one I had created for the purpose.
So when I created a new account and did not connect it to my main account, after following all the appropriate steps as above, I found that it worked fine!
I haven't yet confirmed this (ie. reproduced), but it apparently did it for me...hope it helps.
One or more reasons are there for these error.
Log in with your Gmail( or any other if ) in your local system.
Also check for Less Secure App and Set it to "Turn On" here is the Link for GMAIL.
https://www.google.com/settings/security/lesssecureapps
check for EnableSsl in your Email code, and also set it to true.
smtp.EnableSsl = true;
Also check which port are you using currently. 25 is Global, but you can check it for others too like 587.
check here. Does all SMTP communication happen over 25?
IF YOU ARE ON REMOTE : Check the answer of Vlad Tamas above.
If you have 2-Step Verification step up on your Gmail account, you will need to generate an App password.
https://support.google.com/accounts/answer/185833?p=app_passwords_sa&hl=en&visit_id=636903322072234863-1319515789&rd=1
Select How to generate an App password option and follow the steps provided. Copy and paste the generated App password somewhere as you will not be able to recover it after you click DONE.
You can also connect via port 465, but due to some limitations of the System.Net.Mail namespace you may have to alter your code. This is because the namespace does not offer the ability to make implicit SSL connections. This is discussed at http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx, and I have supplied an example of how to use the CDO (Collaborative Data Object) in another discussion (GMail SMTP via C# .Net errors on all ports).
I had this problem resolved. Aparently that message is used in multiple error types.
My problem was that i had reached my maximum of 500 sent mails.
log into the account and manually try to send a mail. If the limit has been reached it will inform you
smtp.Host = "smtp.gmail.com"; //host name
smtp.Port = 587; //port number
smtp.EnableSsl = true; //whether your smtp server requires SSL
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
Google no longer allows "less secure apps", so this is not possible for normal Gmail users.
Changes by Google after May 2022.
For these changes, we have to do the following changes to our code.
First go to Gmail account security.
Enable two-factor authentication.
Configure the App password in the google account.
Use the App password in the application.
MailMessage mail = new MailMessage();
mail.To.Add(email.Text.ToString().Trim());
mail.From = new MailAddress("your_Gmail_address");
mail.Subject = "Hello test email";
mail.Body = "<p>hello user<br/> How are you?</p>";
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Port = 587; // 25 465
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Host = "smtp.gmail.com";
smtp.Credentials = new System.Net.NetworkCredential("your_Gmail_address", "Your_gmail_app_password");
smtp.Send(mail);
Change your gmail password and try again, it should work after that.
Don't know why, but every time you change your hosting you have to change your password.
This code works for me, and also allows in gmail access from unsecure apps, and removing authentication in 2 steps:
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(MailAddress, Password)

net_io_connectionclosed error trying to send via office365 in c#

I have looked at the other threads and have so far found no solution.
I get the net_io_connectionclosed error whenever I try to connect via the method below.
I am trying to use an Office 365 smtp relay. I do not have access to the main account or ability to change anything about this email so I cannot check settings or even reset the password.
Any and all help gratefully received.
uname: email address of the relay account (no-reply#[x].com)
I am waiting on a reply to my email to get the onmicrosoft.com address, but it is not mentioned in any of the tutorials at all. As such the uname here is also in the msg as the 'from' address.
pwd: password.
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(uname, pwd);
client.TargetName = "STARTTLS/smtp.office365.com";
client.Timeout = 10000;
client.Send(msg);
Ok, it turns out that using a relay for this is not possible unless you own the IPs (not supplied by Azure, netregistry etc.)
You have to buy a new mailbox from O365 and use that. Thus defeating the purpose of having a realy unless you run your own server (in which case I wouldn't need a relay as I would use my own smtp services.)
This means if you are running Azure, probably best to avoid O365 for email, other suppliers are far more flexible.
Link to the forum at MS:
https://answers.microsoft.com/en-us/msoffice/forum/msoffice_o365admin-mso_other/how-to-setup-an-smtp-relay-for-use-from-an-azure/5d997c38-bd67-4dbd-ad0d-62488addf9ae

WebMatrix Not sending mail now that it is moved to the server

I am trying to get WebMatrix running on a local server (simply for testing within our intranet), but it is having trouble sending mail where it never did before on my local (work) machine.
I am getting a simple, the operation has timed out message. The account for this is setup through gmail, so I wouldn't think that there would be too many problems, but as I have never set up WebMatrix on a server before, I don't really know how to attack this issue.
When I had the Email working in construction of this website, I used these settings and everything worked fine:
WebMail.SmtpServer = "smtp.gmail.com";
WebMail.SmtpPort = 25;
WebMail.EnableSsl = false;
Then when I ran it with these settings on the server I got this error:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first.
With that, we tried to enable SSL, but get a simple response timed out request after that (using these settings):
WebMail.SmtpServer = "smtp.gmail.com";
WebMail.SmtpPort = 465;
WebMail.EnableSsl = true;
The "Username" and "From" fields are set the same (name#somecity.net) this is an example of our email that is managed by gmail. Also the password is set and correct.
Am I chasing the wrong thing here, by looking into SSL?
You'll have to forgive me in that I have never implemented SSL before. I know what SSL is, but I have never set it up before, so I apologize if I am a kind of a noob when it comes to setting this up.
Also, just so you know for sure, the server error does, in fact, error on the WebMail.Send method.
You should change your SMTP port for the Gmail one. Right now, gmail is working with 587 instead of 465.
You can check it using telnet smtp.gmail.com 587. Then you should get something like this:
220 test.auto.mySMTPserver.com ESMTP Service (Lotus Domino Release 8.5.3FP2 HF95) ready at Tue, 30 Oct 2012 08:27:31 -0700
Your new code:
WebMail.SmtpServer = "smtp.gmail.com";
WebMail.SmtpPort = 587;
WebMail.EnableSsl = true;
And that's it.
I would say that the message tells you you are not authenticated, so you are likely to need to send a username / password for a valid user on the server. See this question for an example of authenticating to a mail server to send.

Unable to send SMTP mail with .NET, network issue?

I am trying to send an smtp email through gmail's smtp server using the code below:
MailMessage message = new MailMessage("myEmail#gmail.com", "myEmail#purdue.edu", "Testing SMTP", "Test, yo");
SmtpClient client = new SmtpClient();
client.EnableSsl = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.Credentials = new NetworkCredential("myEmail#gmail.com", "myPassword");
client.Send(message);
Using the same code my friend successfully sent me an email from another network, but .NET throws the error "No connection could be made because the target machine actively refused it 74.125.91.109:587". This has to be a network issue right?
My network admin claims there are no blocked outbound ports and my firewall is entirely off, what else could be causing this? I have tried Purdue's smtp server as well (smtp.purdue.edu), and it fails with the same message.
Turn off any antivirus program.
Regarding the test to Purdue, are you sure that they use port 587?
You should use port 465 for SSL according to this
Change the port to 465. It worked for me.
This may caused by McAfee Virus Blocks the Mass Mailing Worms. you can do the following:
1.Open the VirusScan Console by right clicking the VirusScan shield in the system tray and select VirusScan Console...
2.Double click the Access Protection item and open it.
3.Uncheck the Prevent Mass Mailing Worms from Sending Mail rule.
4.Click OK and close the VirusScan Console.
Hope this is helpless.

Sending email through Gmail SMTP server with C#

For some reason neither the accepted answer nor any others work for me for "Sending email in .NET through Gmail". Why would they not work?
UPDATE: I have tried all the answers (accepted and otherwise) in the other question, but none of them work.
I would just like to know if it works for anyone else, otherwise Google may have changed something (which has happened before).
When I try the piece of code that uses SmtpDeliveryMethod.Network, I quickly receive an SmtpException on Send(message). The message is
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" <-- seriously, it ends there.
UPDATE:
This is a question that I asked a long time ago, and the accepted answer is code that I've used many, many times on different projects.
I've taken some of the ideas in this post and other EmailSender projects to create an EmailSender project at Codeplex. It's designed for testability and supports my favourite SMTP services such as GoDaddy and Gmail.
CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.
Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername#gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername#gmail.com", "myusername#gmail.com", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
}
}
}
I also got it working using a combination of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx and code (because there is no matching EnableSsl in the configuration file :( ).
2021 Update
By default you will also need to enable access for "less secure apps" in your gmail settings page: google.com/settings/security/lesssecureapps. This is necessary if you are getting the exception "`The server response was: 5.5.1 Authentication Required. – thanks to #Ravendarksky
In addition to the other troubleshooting steps above, I would also like to add that if you have enabled two-factor authentication (also known as two-step verification) on your GMail account, you must generate an application-specific password and use that newly generated password to authenticate via SMTP.
To create one, visit: https://www.google.com/settings/ and choose Authorizing applications & sites to generate the password.
THE FOLLOWING WILL ALMOST CERTAINLY BE THE ANSWER TO YOUR QUESTION IF ALL ELSE HAS FAILED:
I got the exact same error, it turns out Google's new password strength measuring algorithm has changed deeming my current password as too weak, and not telling me a thing about it (not even a message or warning)... How did I discover this? Well, I chose to change my password to see if it would help (tried everything else to no avail) and when I changed my password, it worked!
Then, for an experiment, I tried changing my password back to my previous password to see what would happen, and Gmail didn't actually allow me to do this, citing the reason "sorry we cannot allow you to save this change as your chosen password is too weak" and wouldn't let me go back to my old password. I figured from this that it was erroring out because either a) you need to change your password once every x amount of months or b). As I said before, their password strength algorithms changed and therefore the weak password I had was not accepted, even though they did not say anything about this when trying to login ANYWHERE! This (number 2) is the most likely scenario, as my weak password was about 4 months old, and it let me use it in Gmail.
It's pretty bad that they said nothing about this, but it makes sense. Because most hijacked emails are logged into using software outside of gmail, and I'm guessing you are required to have a stronger password if you want to use Gmail outside of the Gmail environment.
Turn On Access For Less Secure Apps and it will work for all no need
to change password.
Link to Gmail Setting
I've had some problems sending emails from my gmail account too, which were due to several of the aforementioned situations.
Here's a summary of how I got it working, and keeping it flexible at the same time:
First of all setup your GMail account:
Enable IMAP and assert the right maximum number of messages (you can do so here)
Make sure your password is at least 7 characters and is strong (according to Google)
Make sure you don't have to enter a captcha code first. You can do so by sending a test email from your browser.
Make changes in web.config (or app.config, I haven't tried that yet but I assume it's just as easy to make it work in a windows application):
<configuration>
<appSettings>
<add key="EnableSSLOnMail" value="True"/>
</appSettings>
<!-- other settings -->
...
<!-- system.net settings -->
<system.net>
<mailSettings>
<smtp from="yourusername#gmail.com" deliveryMethod="Network">
<network
defaultCredentials="false"
host="smtp.gmail.com"
port="587"
password="stR0ngPassW0rd"
userName="yourusername#gmail.com"
/>
<!-- When using .Net 4.0 (or later) add attribute: enableSsl="true" and you're all set-->
</smtp>
</mailSettings>
</system.net>
</configuration>
Add a Class to your project:
Imports System.Net.Mail
Public Class SSLMail
Public Shared Sub SendMail(ByVal e As System.Web.UI.WebControls.MailMessageEventArgs)
GetSmtpClient.Send(e.Message)
'Since the message is sent here, set cancel=true so the original SmtpClient will not try to send the message too:
e.Cancel = True
End Sub
Public Shared Sub SendMail(ByVal Msg As MailMessage)
GetSmtpClient.Send(Msg)
End Sub
Public Shared Function GetSmtpClient() As SmtpClient
Dim smtp As New Net.Mail.SmtpClient
'Read EnableSSL setting from web.config
smtp.EnableSsl = CBool(ConfigurationManager.AppSettings("EnableSSLOnMail"))
Return smtp
End Function
End Class
And now whenever you want to send emails all you need to do is call SSLMail.SendMail:
e.g. in a Page with a PasswordRecovery control:
Partial Class RecoverPassword
Inherits System.Web.UI.Page
Protected Sub RecoverPwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles RecoverPwd.SendingMail
e.Message.Bcc.Add("webmaster#example.com")
SSLMail.SendMail(e)
End Sub
End Class
Or anywhere in your code you can call:
SSLMail.SendMail(New system.Net.Mail.MailMessage("from#from.com","to#to.com", "Subject", "Body"})
I hope this helps anyone who runs into this post! (I used VB.NET but I think it's trivial to convert it to any .NET language.)
Oh...It's amazing...
First I Couldn't send an email for any reasons.
But after I changed the sequence of these two lines as below, it works perfectly.
//(1)
client.UseDefaultCredentials = true;
//(2)
client.Credentials = new System.Net.NetworkCredential("username#gmail.com", "password");
Dim SMTPClientObj As New Net.Mail.SmtpClient
SMTPClientObj.UseDefaultCredentials = False
SMTPClientObj.Credentials = New System.Net.NetworkCredential("myusername#gmail.com", "mypwd")
SMTPClientObj.Host = "smtp.gmail.com"
SMTPClientObj.Port = 587
SMTPClientObj.EnableSsl = True
SMTPClientObj.Send("myusername#gmail.com","yourusername#gmail.com","test","testbody")
If you get an error like "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" as I get before this, make sure the line SMTPClientObj.UseDefaultCredentials = False included and this line should before the SMTPClientObj.Credentials.
I did try to switch these 2 lines the opposite way and the 5.5.1 Authentication Required error returned.
The problem is not one of technical ability to send through gmail. That works for most situations. If you can't get a machine to send, it is usually due to the machine not having been authenticated with a human at the controls at least once.
The problem that most users face is that Google decides to change the outbound limits all the time. You should always add defensive code to your solution. If you start seeing errors, step off your send speed and just stop sending for a while. If you keep trying to send Google will sometimes add extra time to your delay period before you can send again.
What I have done in my current system is to send with a 1.5 second delay between each message. Then if I get any errors, stop for 5 minutes and then start again. This usually works and will allow you to send up to the limits of the account (last I checked it was 2,000 for premier customer logins per day).
I had the same problem, but it turned out to be my virus protection was blocking outgoing "spam" email. Turning this off allowed me to use port 587 to send SMTP email via GMail
Simple steps to fix this:
1)Sign in to your Gmail
2)Navigate to this page https://www.google.com/settings/security/lesssecureapps & set to "Turn On"
If nothing else has worked here for you you may need to allow access to your gmail account from third party applications. This was my problem. To allow access do the following:
Sign in to your gmail account.
Visit this page https://accounts.google.com/DisplayUnlockCaptcha and click on button to allow access.
Visit this page https://www.google.com/settings/security/lesssecureapps and enable access for less secure apps.
This worked for me hope it works for someone else!
I'm not sure which .NET version is required for this because eglasius mentioned there is no matching enableSsl setting (I'm using .NET 4.0, but I suspect it to work in .NET 2.0 or later), but this configuration justed worked for me (and doesn't require you to use any programmatic configuration):
<system.net>
<mailSettings>
<smtp from="myusername#gmail.com" deliveryMethod="Network">
<network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" port="587" password="password" userName="myusername#gmail.com"/>
</smtp>
</mailSettings>
</system.net>
You might have to enable POP or IMAP on your Gmail account first:
https://mail.google.com/mail/?shva=1#settings/fwdandpop
I recommend trying it with a normal mail client first...
I was using corporate VPN connection. It was the reason why I couldn't send email from my application. It works if I disconnect from VPN.
I also found that the account I used to log in was de-activated by google for some reason. Once I reset my password (to the same as it used to be), then I was able to send emails just fine. I was getting 5.5.1 message also.
I had also try to many solution but make some changes it will work
host = smtp.gmail.com
port = 587
username = email#gmail.com
password = password
enabledssl = true
with smtpclient above parameters are work in gmail
#Andres Pompiglio: Yes that's right you must change your password at least once..
this codes works just fine:
//Satrt Send Email Function
public string SendMail(string toList, string from, string ccList,
string subject, string body)
{
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
try
{
MailAddress fromAddress = new MailAddress(from);
message.From = fromAddress;
message.To.Add(toList);
if (ccList != null && ccList != string.Empty)
message.CC.Add(ccList);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
// We use gmail as our smtp client
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential(
"Your Gmail User Name", "Your Gmail Password");
smtpClient.Send(message);
msg = "Successful<BR>";
}
catch (Exception ex)
{
msg = ex.Message;
}
return msg;
}
//End Send Email Function
AND you can make a call to the function by using:
Response.Write(SendMail(recipient Address, "UserName#gmail.com", "ccList if any", "subject", "body"))
I was getting the same error and none of the above solutions helped.
My problem was that I was running the code from a remote server, which had never been used to log into the gmail account.
I opened a browser on the remote server and logged into gmail from there. It asked a security question to verify it was me since this was a new location. After doing the security check I was able to authenticate through code.
Turn on less secure apps for your account: https://www.google.com/settings/security/lesssecureapps
First check your gmail account setting & turn On from "Access for less secure apps"
We strongly recommend that you use a secure app, like Gmail, to access your account. All apps made by Google meet these security standards. Using a less secure app, on the other hand, could leave your account vulnerable. Learn more.
Set
smtp.UseDefaultCredentials = false;
before
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
I ran into this same error ( "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" ) and found out that I was using the wrong password. I fixed the login credentials, and it sent correctly.
I know this is late, but maybe this will help someone else.
Another thing that I've found is that you must change your password at least once.
And try to use a secure level password (do not use the same user as password, 123456, etc.)
Yet another possible solution for you. I was having similar problems connecting to gmail via IMAP. After trying all the solutions that I came across that you will read about here and elsewhere on SO (eg. enable IMAP, enable less secure access to your mail, using https://accounts.google.com/b/0/displayunlockcaptcha and so on), I actually set up a new gmail account once more.
In my original test, the first gmail account I had created, I had connected to my main gmail account. This resulted in erratic behaviour where the wrong account was being referenced by google. For example, running https://accounts.google.com/b/0/displayunlockcaptcha opened up my main account rather than the one I had created for the purpose.
So when I created a new account and did not connect it to my main account, after following all the appropriate steps as above, I found that it worked fine!
I haven't yet confirmed this (ie. reproduced), but it apparently did it for me...hope it helps.
One or more reasons are there for these error.
Log in with your Gmail( or any other if ) in your local system.
Also check for Less Secure App and Set it to "Turn On" here is the Link for GMAIL.
https://www.google.com/settings/security/lesssecureapps
check for EnableSsl in your Email code, and also set it to true.
smtp.EnableSsl = true;
Also check which port are you using currently. 25 is Global, but you can check it for others too like 587.
check here. Does all SMTP communication happen over 25?
IF YOU ARE ON REMOTE : Check the answer of Vlad Tamas above.
If you have 2-Step Verification step up on your Gmail account, you will need to generate an App password.
https://support.google.com/accounts/answer/185833?p=app_passwords_sa&hl=en&visit_id=636903322072234863-1319515789&rd=1
Select How to generate an App password option and follow the steps provided. Copy and paste the generated App password somewhere as you will not be able to recover it after you click DONE.
You can also connect via port 465, but due to some limitations of the System.Net.Mail namespace you may have to alter your code. This is because the namespace does not offer the ability to make implicit SSL connections. This is discussed at http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx, and I have supplied an example of how to use the CDO (Collaborative Data Object) in another discussion (GMail SMTP via C# .Net errors on all ports).
I had this problem resolved. Aparently that message is used in multiple error types.
My problem was that i had reached my maximum of 500 sent mails.
log into the account and manually try to send a mail. If the limit has been reached it will inform you
smtp.Host = "smtp.gmail.com"; //host name
smtp.Port = 587; //port number
smtp.EnableSsl = true; //whether your smtp server requires SSL
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
Google no longer allows "less secure apps", so this is not possible for normal Gmail users.
Changes by Google after May 2022.
For these changes, we have to do the following changes to our code.
First go to Gmail account security.
Enable two-factor authentication.
Configure the App password in the google account.
Use the App password in the application.
MailMessage mail = new MailMessage();
mail.To.Add(email.Text.ToString().Trim());
mail.From = new MailAddress("your_Gmail_address");
mail.Subject = "Hello test email";
mail.Body = "<p>hello user<br/> How are you?</p>";
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Port = 587; // 25 465
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Host = "smtp.gmail.com";
smtp.Credentials = new System.Net.NetworkCredential("your_Gmail_address", "Your_gmail_app_password");
smtp.Send(mail);
Change your gmail password and try again, it should work after that.
Don't know why, but every time you change your hosting you have to change your password.
This code works for me, and also allows in gmail access from unsecure apps, and removing authentication in 2 steps:
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(MailAddress, Password)

Categories

Resources