0

I'm trying to send an email through SmtpClient using this code

var client = new SmtpClient("smtp.gmail.com", 465)
        {
            Credentials = new NetworkCredential("***@gmail.com", "password"),
            EnableSsl = true,
        };
        client.Send("***@gmail.com", "***@gmail.com", "test", "testbody");

What I'm getting is smtpException "Message could not be sent".

System.Net.Mail.SmtpException: Message could not be sent. ---> System.Exception:Connectionclosed at System.Net.Mail.SmtpClient.Read () [0x000f9] in /private/tmp/source/bockbuild-mono-

I'm using Mono on Mac (OSX 10.9.2)

My credentials and host/port are correct. Maybe I need to enable it through my gmail account somehow? Thanks!

Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
Niv Navick
  • 192
  • 1
  • 4
  • 13
  • 1
    Are you sure about the port ? I'm using gmail for sending emails and I use port 587. – Ondrej Svejdar Apr 04 '14 at 08:19
  • same smtpException using port 587 – Niv Navick Apr 04 '14 at 08:26
  • Your code looks fine; it might be worth checking your firewall isn't preventing the connection. You say your credentials are definitely correct, but you've probably checked that by logging into gmail via the web; that obviously doesn't use the same port as connecting via SMTP in this way. – Chris Apr 04 '14 at 08:43

1 Answers1

0

Use:

using System.Net;
using System.Net.Mail;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
           {
               Host = "smtp.gmail.com",
               Port = 587,
               EnableSsl = true,
               DeliveryMethod = SmtpDeliveryMethod.Network,
               UseDefaultCredentials = false,
               Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
           };
using (var message = new MailMessage(fromAddress, toAddress)
                     {
                         Subject = subject,
                         Body = body
                     })
{
    smtp.Send(message);
}
Community
  • 1
  • 1