How to Send email using C# and Gmail
hey everyone! Today we are going to be writing a simple application in CSharp that can send emails!
This application is going to be a simple little SMTP Client that will interface with Gmail’s Servers using your username and password. Since this is a pretty simple task, there isn’t a whole lot of code, so it’s a great project to start learning with!
Alright! Let’s get right into building the application!
In this tutorial, I’m going to be using the Devexpress components. They work just like the default windows components, they just look a little better.
The code behind is what is important and it will look almost identical regardless of the form controls.
Once you create your new windows forms project follow these steps to build out the UI
- Rename the form and change it’s text property
Rename the form by hitting f4 to access the properties window
- Grab a groupbox and rename it to “Mail”
Drag a group box over from the toolbox window. Change it’s text property (or caption) to Mail
- Drag over another group box and rename it to “Settings”
Drag a second group box over from the toolbox window and change it’s text property to Settings.
- Add a splitter panel
Drag a splitter panel over and put the Mail group box in the first half and the Settings group box in the second half.
- Dock the splitter panel to fill
Have the new splitter panel fill the form out. Set Horizontal to false, so we have a Mail section at the top and Settings section at the bottom.
- Add a layout control to the bottom
Drag and drop a layout control into the Settings group box. Have it dock to fill and we will use this to add our controls.
- Add textboxes to the Settings Layout control
Add a Username textbox to the Settings layout control.
Add a Password textbox to the Settings layout control.
Both of those should be full width.
Add a Port textbox to the Settings layout control, this should be half width.
Add an SMTP textbox to the Settings layout control, this should be half width as well. - Add a button to the Settings Layout Control
Add a button to the right of the Port and SMTP text boxes. Rename this button to Send and this will be the button that sends our mail!
- Set default values
Change the text property of the Username textbox to your Gmail address. Change the text property of the Port textbox to “587”. Finally, update the SMTP textbox text to be “smtp.gmail.com”
- Add textboxes to the Mail section
Add a textbox to the Mail section and label it “To:”
Add a second textbox to the mail section and label it “Subject:”
Lastly, add a multi-line text edit to the mail section and label it “Body” (This can be a regular textbox)
Your form should look like this:
Alright!! Now we have our form completed! It’s time to write some code!
First, we are gonna double-click on the send button, this will generate an event handler which we will put the code to send the email inside of.
The first line of code we are going to write will create a new NetworkCredential object called login. This will be used to pass the username/password to Gmail.
workCredential login = new NetworkCredential(txtUsername.Text, txtPassword.Text);
Next we will need to create an SMTPClient object which will actually send the message. This line looks like the following:
mtpClient client = new SmtpClient(txtSMTP.Text);
After writing that line, you will get an error and have to import System.Net.Mail. That line looks like this:
using System.Net.Mail;
After you have that setup, it is time to set our client up so it can send the message. The first setting we are going to set is the Port number. This needs to match google’s port number which is 587. This line converts our textbox’s text to an integer (variable type for numbers) and sets the client’s port to the number stored in our port textbox.
Client.Port = Convert.ToInt32(txtPort.Text);
Our next thing will be to enable SSL. Google requires SSL be enabled to use Gmail. So that code looks like this:
client.EnableSSL = true;
The last thing we are going to do is pass the credentials to the new client object and thanks to previously creating the login variable, that line looks like this:
client.Credentials = login;
Now that our client is setup, we just need to create the mail addresses and we will be ready to form our message! The code to create our mail addresses is listed below.
MailAddress sendAddr = new MailAddress(txtUsername.Text);
MailAddress recAddr = new MailAddress(txtSendTo.Text);
Next, we will need to create a new Mail Message, this is the actual content of the message.
I’m going to explain each line in paragraph form and then show the block of code after so it will be easier to copy/paste.
First, we create the object, passing it the sender and receiver addresses. After that, we pass the subject textbox’s text property as the subject. Then we pass the memo edit’s (or textbox if you used that instead) text property as the body. After that, we set the BodyEncoding to UTF8, I wouldn’t worry about this, it’s just a character encoding type. IsBodyHTML is just used to tell if the email contains HTML markup or not, I used true for this and it worked fine. Priority seems like a silly property but normal makes the most sense. Lastly, DeliveryNotificationOptions will notify you if the message fails to send.
MailMessage msg = MailMessage(sendAddr, recAddr);
msg.Subject = txtSubject.Text;
msg.Body = memBody.Text;
msg.BodyEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.Normal;
msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
Alright! That was a huge block of code and we are almost there! Your code should look something like this now!
Now we need to set up the Send Completed event handler. This isn’t totally necessary but it is nice that our application will be able to display an error if the send fails.
Below DeliveryNotificationOptions, we need to add the following code:
client.SendCompleted += new SendCompletedEventHandler(sendCallback);
This line will call the sendCallback function with a result. Now we just need to write that function!
private static void sendCallback(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled || e.Error != null)
{
MessageBox.Show("Error sending Email!");
}
else
{
MessageBox.Show("Sent Successfully!");
}
}
This will show an error message or success message depending on the result!
Our very last lines will be the lines to send the email! This will be added back inside of our click event handler below the SendCompleted line!
string userToken = "sending"
client.SendAsync(msg, userToken);
The resulting code will look like this, sorry the box cuts off a little bit of the sendCallback code.
Once you have the code in place it is time to give it a test run! We have to change one setting in google to make this work. Google “Low Security Applications”, the top link should be a support.google.com link.
After that, you need to click Less Secure App Access and allow Less secure Apps.
Without this option turned on, Google will not send your emails!
Once that is all set up, build your application and fill it out, this is what my application looked like all filled out!
Once I hit the send button, the email sent! This is my test email that worked. Thanks for reading, I really hope this helped you out! If you have any questions, let me know in the comments below!!