codeLearner codeLearner - 10 months ago 57
C# Question

How to authenticate the password in an email application built on windows forms?

Yesterday, i had a task assigned by my senior to build a windows forms application in .net which looked like the image i attached. I did all the stuff regarding the sending process of the email application, but i stuck at one place, i couldn't figure out how to authenticate the password in the email form. The password must be of the same email, which was provided in the "From :" fields. This image displays the form which i designed

Here is the code behind of my form,

public partial class Form1 : Form
MailMessage message;
SmtpClient smtp;
public Form1()

lbl_Error.Visible = false;

private void chk_Show_Password_CheckedChanged(object sender, EventArgs e)

if (chk_Show_Password.Checked == true)
txt_Password.PasswordChar= '\0';


private void btn_Send_Click(object sender, EventArgs e)
btn_Send.Enabled = false;
txt_Password.Text = "";

message = new MailMessage();
message.From = new MailAddress(txt_From.Text);

if (isValidEmail(txt_To.Text))

message.Body = txt_Details.Text;

//attributes for smtp
smtp = new SmtpClient("");
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("", "mypassword");


catch(Exception ex)
btn_Send.Enabled = true;


public bool isValidEmail(string email)
bool flagFalse = false; ;
if (!email.Contains('@'))
lbl_Error.Visible = true;
lbl_Error.ForeColor = System.Drawing.Color.Red;
lbl_Error.Text = "Email address must contain @";
return flagFalse;

return true;


Answer Source

Assuming you're using Gmail like the screenshot you posted shows, you can't check the password without trying to send the email.

My advice would be to attempt to send the email and catch an Exception if it fails. You can then show some indication that there has been an error, like a MessageBox or a Label on your form.

See the documentation for SmtpClient. The Send methods will throw an SmtpException if authentication fails.


Well, after seeing the additional code you posted, you are already handling any exceptions that are thrown, including an authentication failure. The user will see a MessageBox if the password is incorrect.