I am new to C# and I am trying to send an email from a desktop program I am developing. Here is the code I am using but I keep getting the error below :
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("[email protected]");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("[email protected]");
message.Body = "This is the message body";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com",578);
smtp.EnableSsl = true;
smtp.Send(message);
I can't seem to find out what the problem is...
You need to set the credentials for Gmail
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("[email protected]", "mypwd"),
EnableSsl = true
};
client.Send("[email protected]", "[email protected]", "test", "testbody");
Missing credentials most likely:
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
So:
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "Password");
smtp.EnableSsl = true;
smtp.Send(message);
Alternatively, you can store (almost all) this stuff in the app.config
, though I'm not sure how secure you need it to be since the user/pass would be plainly visible to any user that opens the application's directory (and that file). For completion's sake:
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network host="smtp.gmail.com"
enableSsl="true"
userName="[email protected]"
password="password"
port="587" />
</smtp>
</mailSettings>
</system.net>
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