Today we learn how to send an email through C# application. It could be windows form application or web forms application. You need to use few classes and methods to send an email.
Where we need to send an email
Sometimes we need to add module to send an email during sign-in and forget password. There we use this code and get benefit.
Requirement
You need a server, for demo you may use your gmail server. For using gmail server you need to perform below steps before using it.
1. Go to Account
2. Select Sign In & Security
3. Drag the page and at the end you find Allow less secure apps: OFF
Turn this to ON
Now in your application add below code and attach an event with button or link (depends on which application you work on)
private void Send_btn_Click(object sender, EventArgs e)
{
try
{
// Check to is not empty
if(!string.IsNullOrWhiteSpace(to_tb.Text))
{
string emailFrom = "sender@gmail.com";
string emailTo = to_tb.Text;
// Now create instance of Mail
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(emailFrom, emailTo);
// Make a body --> Subject, body message etc
message.Subject = "Send Email Demo Application by Salman Mushtaq";
message.Body = message_tb.Text;
// Set periority
message.Priority = System.Net.Mail.MailPriority.High;
// Another instance we need to create for SmtpClient
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true; // Gmail require SSL
// Set credentials for email
client.Credentials = new System.Net.NetworkCredential(emailFrom, "sender_password");
//Finally send an email
client.Send(message);
MessageBox.Show("Email sent successfully");
}
else
{
MessageBox.Show("Please write email address you need to send an email!", "Email Address", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Exception",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
For this BLOG I develop Windows Desktop Application. Kindly edit sender email and password.
Happy coding :-)
This comment has been removed by a blog administrator.
ReplyDelete