I am developing a application to send Email from windows application using c#. I have written the following code.
try
{
btnSend.Enabled = false;
btnCancel.Visible = true;
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
message.From = new MailAddress(txtFrom.Text);
message.To.Add(txtTo.Text);
message.CC.Add(txtCC.Text);
message.Subject = txtSubject.Text;
message.Body = txtMessage.Text;
if (txtAttachment.Text.Length > 0)
{
if (System.IO.File.Exists(txtAttachment.Text))
{
Attachment attach = new Attachment(txtAttachment.Text);
message.Attachments.Add(attach);
}
}
smtp.Port = 465;
smtp.Credentials = new NetworkCredential(txtFrom.Text, txtPasskey.Text);
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
MessageBox.Show("Mail Sent.", "Email");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
btnCancel.Visible = false;
btnSend.Enabled = true;
}
Now the problem here is :-
If I use port 465 then it gives exception as Failure sending mail.
If I use port 25 or 587 then it gives exception as 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.
Note:- I used my gmail ID as sender, (I have two steps verification enabled on my gmail account)
How can I solve this??