Cannot send email with SMTP in Windows Forms - c#

So, I am working on windows Forms and trying so send email with smtp.
Here is a Code:
MailMessage mail = new MailMessage(from, to, subject, text);
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 465;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(from, password);
try
{
client.Send(mail);
MessageBox.Show("Mesage has benn sant");
}
catch (Exception ex)
{
MessageBox.Show("Failure while sending message");
MessageBox.Show(ex.Message);
}
When I run this Code I am getting Following Error:
"Failure sending email".
When I changed port to 587 I have got following:
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication REquired".
So why I cannot send email ? Can someone explain me that ?
I have changed port to 25 and have sent mail from hotmail( I have replaced "smtp.gmail.com" with "smtp.live.com"), not from gmail. And it works. Seems it's something wrong with gmail.

I was able to make your code work by adding the following three lines and making change in the gmail account setting:
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential (from, password);
In addition to the above changes, it turns out, you also need to update your google account settings and allow less secure apps.
I learned about this on this thread: Sending email in .NET through Gmail
Hope this helps.

Firstly change the port to 25.
Also, the arguments for client.Credentials are supposed to be your username and password to login with. For example...
client.Credentials = new System.Net.NetworkCredential("abc#gmail.com", "mypassword");

I had the same problem. Was able to fix it by disabling this security setting:
going to this link and turning on "access for less secure apps"
https://www.google.com/settings/security/lesssecureapps
enter image description here

Related

Why can't I send e-mail from a C# app when I can send e-mail from a mail client just fine?

I have a task to troubleshoot why a C# app is failing to send automated e-mail messages. I carefully checked the source code, and could find absolutely nothing wrong.
Therefore, I tried to send e-mail from Thunderbird, the e-mail client I normally use. I specified the same SMTP relay, the same UID and password, and everything worked fine.
Trying to isolate the problem, I tried writing a very short C# console app to see what might be going wrong. I wrote the following:
using System.Net;
using System.Net.Mail;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
var client = new SmtpClient("my.server.with.ssl", 465);
client.EnableSsl = true;
client.Credentials = new NetworkCredential("uid", "pwd");
var message = new MailMessage("me#example.com", "myemail#mydomain", "Test Message Subject", "Test Message Body");
client.Send(message);
}
}
}
I entered the same credentials that I used in Thunderbird. When I run the above, I get the following error:
Unhandled Exception: System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
How can it be that e-mail is sent just fine from Thunderbird, but the simple programming above fails to work when I try to send an e-mail from a basic C# app?
Edit I tried changing the port number to 587 as suggested in the Question that #stuartd linked to, and in that case, I get an error that says The operation timed out.
Edit I've tried using other e-mail servers and adjusting the settings, but nothing works so far. I've tried connecting to the same SMTP server that I use for my personal e-mail and it shows an error that the connection times out.
Edit I can't say why, but everything seems to be working now in spite of the fact that I didn't change any code. It seems as if something odd happened with my connection.
try using the default constructor and specify the host only.
Also some servers require that the client be authenticated before the server sends e-mail on its behalf. Try changing the value of UseDefaultCredentials
var mail = new MailMessage();
mail.From = new MailAddress("xxx#gmx.net");
mail.To.Add("yyy#gmail.com");
mail.IsBodyHtml = true;
mail.Subject = "subject";
mail.Body = "content";
var client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Host = "mail.gmx.net";
client.EnableSsl = true;
client.Credentials = new NetworkCredential("user", "pass");
client.Send(mail);
if that doesn't help than tell us the server name if its the public one
Try using:
SmtpClient smtpClient = new SmtpClient("mail.mymailhost.com");
smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

Unable to send Email through GoDaddy SMTP

I am working on an ASP .Net MVC website and I've to send email through Godaddy smtp, Previously my site was developed in classic ASP and it was hosted on godaddy's web hosting (then it was working fine) but now I am hosting this site on IIS,
I am using following code to send email but it is not working
MailMessage msg = new MailMessage();
msg.From = new MailAddress(model.From);
msg.To.Add(model.To);
msg.Body = model.Body;
msg.Subject = model.Subject;
SmtpClient smtp = new SmtpClient("relay-hosting.secureserver.net",25);
smtp.Credentials = new NetworkCredentials("support#{myCompanyName}.com",{password});
smtp.EnableSsl = False;
smtp.Send(msg);
I have also used dedrelay.secureserver.net instead of relay-hosting.secureserver.net host (as mentioned at https://pk.godaddy.com/help/what-is-my-servers-email-relay-server-16601) but both are not working
GoDaddy does not allow relaying through their server unless you are on one of their hosting plans that includes SMTP.
You can set your credentials in webconfig like (for godaddy)
<system.net>
<mailSettings>
<smtp from="your email address">
<network host="relay-hosting.secureserver.net" port="25" />
</smtp>
</mailSettings>
</system.net>
and in c# you can use like
MailMessage message = new MailMessage();
message.From = new MailAddress("your email address");
message.To.Add(new MailAddress("your recipient"));
message.Subject = "your subject";
message.Body = "content of your email";
SmtpClient client = new SmtpClient();
client.Send(message);
It will work
Most SMTP servers are quite restrictive nowadays when it comes to outbound email. I recommend testing the parameters with an email client (or telnet, if you're into that kinda thing) before assuming that there is something wrong with the code. That might also give you an error message that helps debugging.
Some things that come to mind:
The server may check the FROM address against it's database, specifically the user account you use to authenticate. While you can put whatever you want in the header of the email, this field must be your the real address of the authenticated account and only that (no descriptive name).
The server may require the use of TLS encryption, regardless of the port.
Port 25 is quite common, but according to the official RFC mail submission should use port 587. Maybe try that.
It is possible that GoDaddy only allows connections from their own (hosting) servers to these SMTP relays.
Unless the connection fails completely (which would point to no. 4) the server should send some kind of error message at some point. As I wrote above, I would recommend testing/logging the communication, that should provide some insight.
Perhaps you should call up to your ISP, here in th Netherlands they mostly block port 25 because of malware and worms that used to send out email. It can be as simple as this. Have you tried telnetting from your local machine to the email server (telnet mailserver.io 25)? If this ends up in a time out you have your answer and the port is either filtered out at your ISP or from their end.
You can try this code
smtp.Host = "relay-hosting.secureserver.net"; smtp.EnableSsl = false; smtp.UseDefaultCredentials = false; smtp.Port = 25;
string From = "[MyGodaddyEMailAddress]"; //eg.info#mango.com
string FromPassword = "[MyGodaddyMailPassword]";
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(From);
msg.To.Add("[RecipientEmailAddress]");
msg.Subject = "[MailSubject]";
msg.Body = "[MailBody]";
msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("mail.[domain].com", 587); //eg. mail.mango.com
smtp.Credentials = new System.Net.NetworkCredential(From, FromPassword);
smtp.EnableSsl = false;
// Sending the email
smtp.Send(msg);
// destroy the message after sent
msg.Dispose();
Console.WriteLine("Message Sent Successfully");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();

SMTP email client is throwing errors "Timeout" or "requires secure connection" even with correct credential

I was new to SMTP client in C#. So I decided to test it with my credentials. I built an ASP.NET Web forms application that has a Contact Us page on which I am trying to send an email to whoever person fills the form.
I tried sample code after going through this article - https://www.c-sharpcorner.com/UploadFile/87b416/sending-a-simple-email-using-smtpclient-in-C-Sharp/
I have one account in Yahoo so I used its SMTP domain "smtp.mail.yahoo.com" with port number: 465, then my app always threw Timeout exception. So I decided to try with Google's server "smtp.gmail.com" with "587" port and now it raised different exception with message:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
I don't understand what are the prerequisites for working with SMTP on secure servers like Google and Yahoo. Please someone explain.
Also note that I didn't have 2 step verification enabled for my Google account, just to make it clear since some questions on SO have mentioned that this might be the problem.
I also read this question but I am testing directly on my machine - Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
In case if it helps, here is the sample code:
try
{
MailMessage m = new MailMessage();
m.From = new MailAddress("dummy123#gmail.com");
m.To.Add(new MailAddress("dummyreceiver123#gmail.com"));
m.Subject = TBSub.Text;
m.Body = TBBody.Text;
m.IsBodyHtml = true;
NetworkCredential nc = new NetworkCredential();
nc.UserName = "dummy123"
nc.Password = "dummy#123";
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = nc;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(m);
}
catch (Exception ex)
{
//Log this error
}
I just tested out your code it works fine you just need to modify this section:
nc.UserName = "test"
nc.Password = "password";
This has to be a valid gmail or google app email along with the password for the smtp connection to work properly. I would recommend that you put in your own for testing purposes, and then modify this to have your email as well:
m.From = new MailAddress("yourEmail#gmail.com");
m.To.Add(new MailAddress("yourEmail#gmail.com"));
Just so that you can validate that your message is being passed from your function.

How do I use Gmail's SMTP client to send an email to myself in C# without enabling access for less secure apps in Gmail settings?

I'm working on an ASP.NET Web Forms app and I'm trying to programmatically send an email to myself. I'm using Gmail's SMTP client, and all is well except that when I send my message, I get this error:
"System.Net.Mail.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"
If I go into my gmail account settings and enable an option that allows me to allow access for "less secure apps", everything works fine. I'm wondering how I can send my email with having this option enabled.
protected void sendEmail(object sender, EventArgs e)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new System.Net.NetworkCredential("myusername#gmail.com", "mypassword"),
DeliveryMethod = SmtpDeliveryMethod.Network,
EnableSsl = true
};
MailAddress from = new MailAddress("myusername#gmail.com", "Torchedmuffinz");
MailAddress to = new MailAddress("myusername#gmail.com", "Torchedmuffinz");
MailMessage message = new MailMessage(from, to);
message.Subject = "test";
message.Body = "test";
Attachment attachFile = new Attachment(#"pathtofile");
message.Attachments.Add(attachFile);
try { client.Send(message); }
catch (Exception email_exception)
{
System.Diagnostics.Debug.WriteLine(email_exception);
}
}
Gmail port 587 does not support SSL.
I think the following code should work for you.
MailMessage msg = new MailMessage();
msg.From=new MailAddress("yourmail#gmail.com");
msg.To.Add("receiver#receiverdomain.com");
msg.Subject="Your Subject";
msg.Body="Message content is going to be here";
msg.IsBodyHtml=false; //if you are going to send an html content, you have to make this true
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port=587;
NetworkCredential credential=new NetworkCredential("yourmail#gmail.com","your gmail password");
client.UseDefaultCredentials=false;
client.Credentials=credential;
client.Send(msg);
There is a possibility to use Google SMTP servers without 'Allow less secure apps' option, but you cannot use your standard google username and password. See my instructions on other post:
Is there a way to use ASP.NET to send email through a Google Apps acccount without selecting the 'Allow less secure apps' option?

Server does not support secure connections

I'm getting the error "Server does not support secure connections" with my code below.
SmtpClient client = new SmtpClient(exchangeServer);
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new NetworkCredential(user, password);
MailAddress from = new MailAddress(fromAddress);
MailAddress to = new MailAddress(to);
MailMessage mail = new MailMessage(from, to);
// ...
client.Send(mail);
How can I fix this issue?
Your server does not support SSL on the default port; Most won't.
When you set SSL off, you get the message, "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated"
That tells you that you are not authenticated. Further, you said in a comment, "Because if I set UseDefaultCredentials = true and use my own user address in the "from" address, I am able to send an email successfully."
This is apparently an issue with how the SMTP server is configured. You will need to get appropriate credentials, or have the SMTP server set to allow mail to be sent from the web server.
What port are you using? You may find that you need to specify the port in your SmtpClient object.
write
client.EnableSsl = false;

Categories

Resources