Sending emails using Gmail in C#

On February 01, 2024
8min read
Dzenana Kajtaz Technical Content Writer @Mailtrap

Described by its creators at Google as “a secure, smart, and easy to use email”, Gmail is today the most used email service worldwide.

In Gmail, users can send and receive messages, as well as organize, label, categorize, and do much more with their emails.

The sending and receiving in Gmail are made possible by the service’s SMTP server, and in this article, we will teach you how to use C# to send emails with Gmail SMTP.

We’ll also touch upon any possible limitations and issues that come with using Gmail SMTP,  a reliable alternative, as well as email testing. 

How to send email using Gmail SMTP server in C#

C# can do a lot of things. But on its own, it can’t establish communication with an SMTP server, be it Gmail’s server or one from a different service. 

To overcome this obstacle, developers use a combination of the .NET framework and the MailKit library, as recommended by Microsoft’s documentation.

MailKit, a third-party open-source library suited for modern development standards, provides an easy way to interact with email services using various protocols such as IMAP, POP3, and SMTP.

What’s more, as it’s built on top of the MimeKit library, with MailKit, you also get a set of classes for parsing and creating MIME messages – the format used for email messages.

Other MailKit features include searching, saving to/loading from disks, and handling attachments. Pretty impressive, right?

To start sending with .NET and MailKit, first install the library via NuGet in the Package Manager Console of Visual Studio by running the following command:

Install-Package MailKit

After the installation, retrieve your Gmail SMTP server credentials which should look something like this:

  • Server: smtp.gmail.com
  • Port: 587 (or 465 for SSL/TLS)
  • Username: Your full Gmail email address
  • Password: Your Gmail account password

Lastly, to initiate the actual email sending, modify the code snippet below by adding your credentials, to and from address, etc. and run the code with your project:

using System;

using MailKit.Net.Smtp;
using MailKit;
using MimeKit;

namespace TestClient {
  class Program
  {
    public static void Main (string[] args)
    {
      var email = new MimeMessage();

      email.From.Add(new MailboxAddress("Sender Name", "sender@email.com"));
      email.To.Add(new MailboxAddress("Receiver Name", "receiver@email.com"));

      email.Subject = "Testing out email sending";
      email.Body = new TextPart(MimeKit.Text.TextFormat.Html) { 
        Text = "<b>Hello all the way from the land of C#</b>"
      };

      using (var smtp = new SmtpClient())
      {
        smtp.Connect("smtp.gmail.com", 587, false);

        // Note: only needed if the SMTP server requires authentication
        smtp.Authenticate("smtp_username", "smtp_password");

        smtp.Send(email);
        smtp.Disconnect(true);
      }
    }
  }
}

In the snippet above, we didn’t “cc” or “bcc” any recipients.

If you need to, simply use this code:

email.Cc.Add(new MailboxAddress("CC Recipient Name", "ccrecipient@example.com"));
email.Bcc.Add(new MailboxAddress("BCC Recipient Name", "bccrecipient@example.com"));

How to send an HTML email using Gmail SMTP server in C# 

A common question when it comes to email sending is, “How can I send HTML emails?” In C#, doing this is quite simple.

When sending plain text emails, the following few lines of code are all you need to define the message body:

message.Body = new TextPart("plain")
{
  Text = @"Hey, Just wanted to say hi all the way from the land of C#. -- Code guy"
};

Now, to send this same email just in HTML format, the code will be a bit different and consist of a few more lines, but it will still remain quite simple:

var bodyBuilder = new BodyBuilder();

bodyBuilder.HtmlBody = "<p>Hey,<br>Just wanted to say hi all the way from the land of C#.<br>-- Code guy</p>";

bodyBuilder.TextBody = @"Hey,
Just wanted to say hi all the way from the land of C#.
-- Code guy"; 

message.Body = bodyBuilder.ToMessageBody();

How to send an email with an attachment using Gmail SMTP server in C# 

Earlier in this article, we mentioned MailKit’s ability to handle attachments. And now, to save you from having to do your own research, we are going to demonstrate how it all works in practice!

The handling of attachments by Mailkit is done using the MimeKit.MimePart class- a single part of a MIME message. And to add an instance of it to a MIME message instance, you have to use the MimeKit.BodyBuilder class. More specifically, its Attachments property.

var builder = new BodyBuilder();

// Set the plain-text version of the message text
builder.TextBody = @"Hey,
  Just wanted to say hi all the way from the land of C#. Also, here's a cool PDF tutorial for you!
  -- Code guy
";

// The part where we include the new attachment...
builder.Attachments.Add(@"C:\Users\CodeGuy\Documents\tutorial.pdf");

message.Body = builder.ToMessageBody();

Adding multiple attachments is also possible by calling the Add()method as many times as necessary.

builder.Attachments.Add(@"C:\Users\CodeGuy\Documents\first-tutorial.pdf");
builder.Attachments.Add(@"C:\Users\CodeGuy\Documents\second-tutorial.pdf");

And in case you want to add attachments with different encodings and file names, you can do so with the overload method:

bodyBuilder.Attachments.Add(@"C:\Users\CodeGuy\Documents\first-tutorial.pdf", "first-tutorial.pdf", ContentEncoding.Default);

Possible limitations and issues when sending emails using Gmail SMTP server in C#

Like any SMTP provider, Gmail also has its own limitations, which might lead to issues during the email-sending process. To help you understand those limitations and stay ahead of potential issues that might arise, keep in mind the following points:

Imposed sending limit

Free Gmail accounts have a sending limit of 500 emails per day. For a higher sending limit, upgrading to a business account is required.

These imposed sending limits are Google’s attempt at keeping its systems healthy and accounts safe, which are often targeted by exploitative individuals and businesses.

Less secure apps feature 

Although it is a feature being deprecated in favor of OAuth 2.0, “Less secure apps” will still need to be enabled in your Gmail settings in order for you to connect your C# application to Gmail SMTP. 

Through this feature, Gmail controls which third-party apps/devices with basic authentication can connect to your Gmail account. Yet, it is important to note that enabling it will make your Gmail account an easier target for hacking or phishing attacks, and for that reason, the same should be done only if an app/device is trusted and the risks are clear to the account owner.

Implemented spam filters 

Gmail uses spam filters equipped with a variety of techniques, including content analysis, sender reputation analysis, and insight into recipient interaction with previous emails. These spam filters can potentially mark the emails sent from your app as spam and thus prevent them from ever reaching recipients if you don’t do proper testing beforehand (more on that a bit later).

Enabled two-factor authentication 

Having two-factor authentication enabled for a Gmail account is a common practice nowadays, but it does create an obstacle when wanting to connect the account to a C# application. 

To go past this obstacle, you will need to create an “App Password” for the application by going to the security settings of your Google account and then to “Signing in to Google” -> “App Passwords” -> “C#” -> “Other” -> “Generate”.

This password will need to be used in your C# code through hardcoding, which does pose a security risk, so do bear this in mind.

Imposed email size limit 

For both incoming and outgoing messages, Gmail imposes a size limit (message and attachment(s) size combined) – 25MB for free accounts and 35MB for business accounts. 

If a message exceeds the size limit, it will not be delivered, and the sender will receive an error message.

Imposed content restrictions 

To help protect its users from malicious content and spam, Gmail imposes certain content restrictions. But, due to the restrictions being automated, legitimate messages with legitimate content can sometimes get blocked. 

This again highlights the importance of doing email testing, covered in detail later in this article.

What is the best alternative to using Gmail SMTP?

After learning about the possible limitations and issues that come with using Gmail SMTP, it’s only natural that some of you might want to consider using an alternative to it.

When picking an alternative, make sure you carefully consider your needs and requirements, such as delivery speed, deliverability rates, the volume of emails you want to send, desired monitoring features, customer support, etc.

If you are looking for something reliable that provides just-in-time delivery, then our recommendation would be Mailtrap Email Sending – a sending solution that provides a stable working email infrastructure with high deliverability rates by design.

To ensure effortless maintenance and troubleshooting, Mailtrap Email Sending also comes with unique monitoring capabilities facilitated by helicopter-view dashboards, in-depth analytics, and alerts.

Other benefits of this sending solution include an email delivery time of ≈ 1 sec, straightforward onboarding, up to 60 days of email logs, drill-down reports, and more.

To get started with Mailtrap Email Sending, you first need to sign up for a Mailtrap account.

Then, add and verify your domain, as explained in this Mailtrap knowledgebase article.

With your domain verified, from the API and SMTP Integration page of your Mailtrap account, copy the Mailtrap Email Sending email API integration code and paste it into your C# application:

var client = new RestClient("https://send.api.mailtrap.io/api/send");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <YOUR_API_TOKEN>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\"from\":{\"email\":\"mailtrap@mailtrap.io\",\"name\":\"Mailtrap Test\"},\"to\":[{\"email\":\"ToMailAddress\"}],\"subject\":\"You are awesome!\",\"text\":\"Congrats for sending test email with Mailtrap!\",\"category\":\"Integration Test\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Alternatively, you can also just replace the Gmail SMTP credentials used in the email-sending code from the “How to send email using C# and Gmail SMTP server” section of this article with the ones provided by Mailtrap Email Sending and thus use Mailtrap as your SMTP server.

Once you have everything set up, you can start sending with the confidence that your emails will reach recipients’ inboxes just in time.

How to test emails in C#

Regardless of what SMTP server you choose for delivering your emails, testing those emails beforehand should be on your to-do list. Why? Well, because through the email testing process, you get to complete a number of important checks, such as:

  • Checking if your emails are going to be displayed as intended in various email clients/devices
  • Checking if your emails trigger any spam filters 
  • Checking if your sender IP/domain is on any common blacklist
  • And more 

Without a feature-packed solution, doing the checks listed above might require the use of more than one tool. That is why we recommend Mailtrap Email Testing to developers, QAs, and managers looking to test their emails thoroughly.

Mailtrap Email Testing is a solution that enables inspecting and debugging emails in a safe environment that comes with no risk of spamming recipients in the process. How? Thanks to the use of virtual inboxes, which can be created for each project or even project stage you are working on!

This testing solution comes with plenty of features that help solve a range of email testing challenges. These features include:

  • Email preview – displays how your message will be rendered by a web browser and how it looks on different screen sizes
  • HTML/CSS check – scans through your email in search of problematic elements, displays the list of email clients that don’t support or support a specific element only partially, and estimates the support for your email code across popular email clients
  • Manual and automatic email forwarding to whitelisted recipients – allows you to view your testing emails in real inboxes of recipients you’ve whitelisted
  • Spam analysis – provides you with an overall spam score and a detailed description of each rule that can be treated as suspicious by email clients
  • Blacklist reporting – checks whether the sender’s IP or domain has been listed on any of the commonly used blacklists
  • Tech info insights – provides the original values of email headers and SMTP transaction information

So, how do you start using Mailtrap Email Testing? The process is quite simple!

First, you create a Mailtrap account in case you don’t already have one.

Then, in your account, under Email Testing -> Inboxes -> SMTP Settings -> Integrations, pick “Plain C#” and copy the configuration code provided:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new SmtpClient("smtp.mailtrap.io", 2525)
            {
                Credentials = new NetworkCredential("username", "password"),
                EnableSsl = true
            };
            client.Send("from@example.com", "to@example.com", "Hello world", "testbody");
            Console.WriteLine("Sent");
            Console.ReadLine();
        }
    }
}

Paste the code into your C# application, run it, and the test email should arrive shortly, allowing you to use the mentioned tool features.

With Mailtrap Email Testing, you do have the option to use SMTP credentials in your email-sending script, MTA settings, email client settings, or any system that supports SMTP credentials and send your test emails that way.

But, if using more code or credentials is not what you are looking to do, you can also simply use the dedicated email address of your virtual inbox as the recipient address for your test email. The choice is yours!

To wrap things up

The enormous popularity of Gmail can’t be overlooked, even by those who aren’t big fans of Google’s services/products. That is why anyone dealing with email sending and delivery should know how to use Gmail’s SMTP server without many hiccups.

We hope that this article provided you with enough information on how to use C# to send emails with Gmail SMTP and that you will take our advice on email testing seriously to avoid giving your recipients any unpleasant surprises in the form of poorly rendered spammy emails.

For more C#-related articles, have a look at our posts covering email address validation and sending with ASP.NET C#

Article by Dzenana Kajtaz Technical Content Writer @Mailtrap

I’m a Technical Content Writer with an educational background in software engineering and 4 years of experience as a writer, editor, and content marketer. Currently, I mainly focus on writing about email infrastructure, sending, testing, and so on, but I do love creating fun and engaging content on email marketing topics as well.