Sending Email Using .NET

One thing that many applications need to do is to send email.

.NET has quite a robust set of classes available that allow you to do this very easily. The best part about it is that not only can it be used to send email by using a standard email/smtp server, but you also can use it to send email by using a Gmail account as well.

Setting Up Gmail to Allow External Access

To allow your .NET application to send email via your Gmail account, you'll need to do two things:

  1. You need to turn on 2 factor authentication. You can enable SMTP access without it, but the settings are global and not secured.
  2. Create an app-specific password.

Turning on 2 factor authentication is fairly straightforward. Open your Gmail inbox, click your avatar, and then click "Account", just under your name. Scroll down until you see "2 factor authentication"; click it and follow the instructions.

Once 2 step verification is enabled, you'll see that your security settings page now has an "App Specific Passwords" tab, as shown in Figure 1:

Email1
Figure 1: You have a new security settings tab

Click this tab, and then click the button marked "Manage App Specific Passwords". On the next screen that appears, select "Mail" on my "Windows Computer" and click generate.

You'll be shown the password that has been generated. At this point make sure you either add the password into your code, or write it down until you're ready to add it. Either way, once you dismiss the dialog, you'll be unable to get the password back, so you'll need to delete and then re-create it.

Once you've generated a password, you should see something like this:

Email2
Figure 2: The password has been generated

You can revoke the access any time you like and regenerate it to get new passwords.

Once you have this set up, you then can start to use the SMTP client classes in your applications.

The Simplest Email Is Always the First

To start using the SMTP classes, you need to first import 'System.Net' and 'System.Net.Mail'. This is as simple as adding:

using System.Net;
using System.Net.Mail;

to your application using clause.

To use your Gmail account from .NET, you need to use the following settings:

Server Address: smtp.gmail.com SSL: Enabled Port: 587 User Name: gmail email address Password: password generated by app specific passwords

Pay particular attention to the port number here. In ALL the guides available, they tell you that the SSL/TLS port number is 465. That's correct for most applications. For .NET, however, you MUST use the alternative port; otherwise, your program will fail to connect and give you time out errors.

To send your first email, try the following:

SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.EnableSsl = true;
smtp.Port = 587;
smtp.Credentials = new NetworkCredential("email@gmail.com",
   "appspecificpassword");
smtp.Send("email@gmail.com","toaddress@somwhere.com",
   "Email Subject", "Email message");

Using the simple method of doing this, you quickly can send plain text emails in five lines of code (two if you don't have to enable Gmail settings).

However, there are a few more things you can do.

You can, for example, use the 'MailMessage' object to give you more control over your outgoing email such as adding multiple recipients and making the body of the email a HTML one. The following code shows how you might do this:

string myGmailAddress = "xxxxx";
string appSpecificPassword = "xxxxx";

SmtpClient smtp =
   new SmtpClient("smtp.gmail.com");

smtp.EnableSsl = true;
smtp.Port = 587;
smtp.Credentials = new
   NetworkCredential(myGmailAddress,
   appSpecificPassword);

MailMessage message = new MailMessage();
message.Sender = new MailAddress(myGmailAddress,
   "Peter Shaw");
message.From = new MailAddress(myGmailAddress,
   "Peter Shaw");

message.To.Add(new MailAddress("aperson1@example.com",
   "Recipient Number 1"));
message.To.Add(new MailAddress("aperson2@example.com",
   "Recipient Number 2"));
message.CC.Add(new MailAddress("accaddress@example.com",
   "A CC Person"));
message.Bcc.Add(new MailAddress("abccperson@example.com",
   "A BCC Person"));

message.Subject = "My HTML Formatted Email";
message.Body = "<h1>HTML Formatted EMail</h1>
   <p>DO you like this <strong>EMail</strong>
   with HTML formatting contained in its body.</p>";

message.IsBodyHtml = true;
smtp.Send(message);

You can also attach files to the email by using the following:

Attachment attachment = new Attachment("mypdffile.pdf",
   MediaTypeNames.Application.Pdf);
message.Attachments.Add(attachment);

This is just the basics. There are lots of other options you have too, such as being able to support multiple body types. Have a read through the property lists on MSDN; you might be surprised at what's available.

If you have an idea or subject you'd like to see covered in this column, please feel free to hunt me down on Twitter as @shawty_ds, or come and find me on Linked-in where I help run one of the Larger .NET user groups called Lidnug, I'm always open to new suggestions.



Related Articles

Comments

  • Company

    Posted by FORCE AND RAKUBA BOOKSELLERS on 08/20/2016 11:30pm

    wanna create my business email address

    Reply
  • Explained in very effective manner .. !! Thank you

    Posted by Gursimran Kaur on 07/15/2016 12:39pm

    Can u please help me with design layout.. i want to add a button with title "email" . After clicking on button.. i want to get the layout for my email so that there can i easy fill the field according to the requirement . just like you "Leave A Comment" potion of this page.

    Reply
  • How send by not using appspecificpassword?

    Posted by (L)user on 04/10/2015 12:12pm

    How can I send email by not using the AppSpecificPassword? Without secure code?

    • RE: How send by not using appspecificpassword?

      Posted by Peter Shaw on 04/22/2015 09:49am

      If your using GMail, you can't. Well actually you can, BUT... it means you have to turn off 2 factor authentication, and hunt down and change a number of different settings in your GMail account. All the things you have to change, Google don't want you to change, and have openly admitted that at some time in the future they will remove these un-secure settings. If you don't want to use GMail and it's secure settings, then the only other way is to set up and run your own Email server, which is what I do.

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date