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