Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to connect to remote server

Tags:

c#

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...

like image 447
thesma Avatar asked Dec 16 '22 08:12

thesma


2 Answers

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");
like image 111
BigBadOwl Avatar answered Dec 23 '22 08:12

BigBadOwl


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>
like image 21
Brad Christie Avatar answered Dec 23 '22 08:12

Brad Christie