0
votes

In C# I try to send email using Gmail. This is my code:

MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";

SmtpServer.Port = 465;
SmtpServer.Credentials = new System.Net.NetworkCredential("[email protected]", "mypsw");
SmtpServer.UseDefaultCredentials = false;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);

And I get error:

{System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: The connection was closed.
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)

2
This answer stackoverflow.com/questions/13506623/… suggests port 587Neil

2 Answers

1
votes

There is answer somewhere but i do not recall where so i will write you code below. If someone find answer please put in comment and i will point it there.

var smtpClient = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587, // Port 
    EnableSsl = true,
    Credentials = new NetworkCredential("[email protected]", "yourpw")
};

MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.Subject = "Subject";

msg.From = new MailAddress("[email protected]");


msg.Body = "Body here";
msg.Bcc.Add(li[i].Value);
smtpClient.Send(msg);
0
votes

From the docs on EnableSsl Property:

The SmtpClient class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information. An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported.

And long story short from other web sources is that port 465 expects SSL to be negotiated at connection setup (not supported by SmtpClient) whereas 587 uses STARTTLS after initial non secure dialog (supported by SmtpClient)