Sending Emails using MailKit and Gmail

MailKit is an open-source NuGet package used for sending emails. It has over 80 million downloads on the NuGet store.

Benefits of Using MailKit Library

Here are some key benefits of using this library:

  • Cross-platform
  • Open-source
  • High performance
  • Improved security by supporting SSL/TLS

How to Implement It in .NET 6

Step 1: Install the MailKit NuGet Package
MailKit Installation

Step 2: Set Up Your SMTP Server Details
In my appSettings, I’ve created an EmailConfiguration section and added all necessary information. Since I’m using Gmail to send emails, the host is set to smtp.gmail.com.

SMTP Setup

Note: The password mentioned in the configuration is not your Gmail account password. Instead, it’s a password generated specifically for sending emails.

To generate this password, follow these steps:

  1. Open Gmail → Click on Manage Google Account
  2. In the Search Google Account section, type App Passwords → This window will show up: App Passwords Setup
  3. For App, select Mail. For Device, select Windows Computer. Then, click Generate. The generated password should be added to your appSettings.

Step 3: Create a New Service for Email
Create Email Service

Step 4: Register Dependencies
Register the dependencies of your EmailService and EmailConfiguration.

Register Dependencies

Now, inject IEmailService wherever you need it, and you’re good to go!

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place