In this article I will show you how to send an email to gmail with the help of SMTP in windows application using C#.
Initial chamber
Step 1: Open Your Visual Studio 2010 and Go to File, New, then Projects and under Visual C# select Windows.
You can change the name of the project and you can browse your project to different location too. And then press – OK.
Design chamber
Step 2: Now open your Form1.cs file, where we will create our design for sending an email to gmail. We will drag 3 labels, 3 textboxes and one button from toolbox to Form1.cs. You will see your form look like the following:
Code chamber
Right click on the blank part of Form1.cs and View Code. You will see you are entered in the code part of the form. Write the following code and then Press F5 to run the project.
Add some of the namespaces for sending Gmail.
If you can’t find these namespaces in the IntelliSense, then in the Solution Explorer - Right Click and Add References. In Add References, .NET, find “System.Net”and Press Ok.Now IntelliSense will surely show you.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Net;
- using System.Net.Mail;
-
- namespace wingmailapplication
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- try
- {
-
- MailMessage msg = new MailMessage();
- msg.From = new MailAddress("[email protected]");
- msg.To.Add(textBox1.Text);
- msg.Subject = textBox3.Text;
- msg.Body = textBox2.Text;
-
- SmtpClient smt = new SmtpClient();
- smt.Host = "smtp.gmail.com";
- System.Net.NetworkCredential ntcd = new NetworkCredential();
- ntcd.UserName = "[email protected]";
- ntcd.Password = "";
- smt.Credentials = ntcd;
- smt.EnableSsl = true;
- smt.Port = 587;
- smt.Send(msg);
-
- MessageBox.Show("Your Mail is sended");
-
- }
- catch (Exception ex)
- {
-
- MessageBox.Show(ex.Message);
- }
-
-
- }
- }
- }
Output chamber It will show an error if you are not having internet connection or if you haven't fill all the textboxes or any other.
Lets check Gmail and you can see our email there. If you will find it, that means email is sent properly.
Hope you liked it. Have a good day. Thank you for reading.