0
votes

I am trying to code software in C# to send email via using gmail account with help of the gmail SMTP server. It does not produce any compile errors, but throws an exception at runtime even though code is correct and fine.

Here is my code:

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

private void button1_Click(object sender, EventArgs e)
{
    if (from.Text != "" && password.Text != "" && to.Text != "" && subject.Text != "" && receive.Text != "")
    {
        try
        {
            MailMessage mail = new MailMessage(from.Text, to.Text, subject.Text, receive.Text);

            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            SmtpServer.Port = 465;
            SmtpServer.Credentials = new System.Net.NetworkCredential(from.Text, password.Text);
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);

            MessageBox.Show("Mail Sent");
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.ToString());
            textBox6.Text = ex.ToString();
        }
    }
    else
    { 
        MessageBox.Show("Fill all fields, then press Send button"); 
    }

Here is the exception I get:

System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Gmail_Sender.Form1.button1_Click(Object sender, EventArgs e) in C:\Users\junaid

1
Does the Gmail account require two-factor authentication? If so, you'll need to create an app password instead.howcheng

1 Answers

1
votes

GMail does not support port 465 for SMTP submission.

You need to use port 587.

That said, they probably won't talk to you anyway, since they're very fussy about IP addresses. If you're on a dynamic range, it's probably not going to work even if you do it correctly.

IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.

The error message indicates that Google didn't want to talk to you and closed the connection.