I have been trying to send an email via C# from a gmail account for account registration for my website.
I have tried several ways however the same exception continues to pop up: System.Net.Mail.Smtp Exception - Connection has timed out.
This is what I inluded in my Web.config file:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network"
from="Writely <[email protected]>">
<network host="smtp.gmail.com"
port="465"
enableSsl="true"
defaultCredentials="false"
userName="[email protected]"
password="******" />
</smtp>
</mailSettings>
</system.net>
where writely is the name of my website, and [email protected] is the account I wish to send an email from.
Then in my Account Controller when I connect with my database and save the user in my table, I am creating my MailMessage object and attempting to same the mail by:
using (DBConnection conn = new DBConnection())
{
conn.UserInfoes.Add(userInfo);
conn.SaveChanges();
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Welcome to Writely";
mail.Body = "Test content";
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
}
Am I missing something or doing something wrong? I read that this is the good way to do this in some other question on stack overflow so I really don't know what's the problem here.
Thanks for your help :)
gmail requires authentication:
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for TLS/STARTTLS: 587
Port for SSL: 465
so what i did is
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("[email protected]", "mypwd"),
EnableSsl = true
};
client.Send("[email protected]", "[email protected]", "Welcome to Writely", "Test content");
You need to tell the SmtpClient what settings to use. It does not automatically read this information from the Web.Config file.
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 465);
smtp.Credentials = new NetworkCredential("[email protected]", "***");
smtp.EnableSsl = true;
smtp.Send(mail);
I had the exact same problem and it's resolved after switching the port number from 465 to 587.
I had the problem on "email confirmation", "password recovery", and "sending email" and now all 3 problems are resolved :).
I know it's a pretty old post, but I usually use the existing posts to find answers instead of asking for new questions.
Thank you all for all your helps.
As I have already answered here.
This problem can also be caused by a security configuration in you gmail account.
The correct port is 587, but to authenticate you need to allow access from less secure apps in your gmail account. Try it here
It worked for me, hope it helps..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With