Pergunta

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!

Foi útil?

Solução

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);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top