Send an Email with an Attachment from Gmail in C#

To send email through a Gmail account from C#, connect to smtp.gmail.com on port 587, upgrade the connection with STARTTLS and sign in. Gmail no longer accepts your normal account password for this. You need either an app password or an OAuth 2.0 access token.

The example uses MailKit. Microsoft marks the built-in System.Net.Mail.SmtpClient as not recommended for new development and points to MailKit instead.

dotnet add package MailKit

Create an app password

App passwords are only available once 2-Step Verification is turned on for the Google account. Then open your Google Account, search for “App passwords”, create one and copy the 16-character value. It works only for the mail protocols and you can revoke it at any time without changing your real password. Work and school accounts may have app passwords disabled by their administrator; in that case you need OAuth (see below).

Store the address and app password outside your code. The example reads them from environment variables; in a real project, use user secrets during development and a secret store in production.

Send the email

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

string sender = GetRequired("GMAIL_ADDRESS");
string appPassword = GetRequired("GMAIL_APP_PASSWORD");

var message = new MimeMessage();
message.From.Add(new MailboxAddress("Report Bot", sender));
message.To.Add(MailboxAddress.Parse("receiver@example.com"));
message.Subject = "Monthly report";

var body = new BodyBuilder
{
    TextBody = "The monthly report is attached.",
    HtmlBody = "<p>The monthly report is <b>attached</b>.</p>"
};
body.Attachments.Add(@"C:\reports\report.pdf");
message.Body = body.ToMessageBody();

using var smtp = new SmtpClient();
await smtp.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
await smtp.AuthenticateAsync(sender, appPassword);
await smtp.SendAsync(message);
await smtp.DisconnectAsync(true);

Console.WriteLine("Sent.");

static string GetRequired(string name) =>
    Environment.GetEnvironmentVariable(name)
    ?? throw new InvalidOperationException($"Environment variable {name} is not set.");

SmtpClient here is MailKit.Net.Smtp.SmtpClient. If a file also has using System.Net.Mail;, the two names clash, so drop the old namespace or use an alias.

Notes on the message

BodyBuilder produces a proper multipart message: a plain-text part, an HTML part, and the attachments. Supplying both text and HTML is worth the extra line, because spam filters treat HTML-only mail with suspicion and some clients show only text.

Attachments.Add reads the file and picks the MIME type from its extension. To attach data that is already in memory, use the overload that takes a file name and a byte[] or Stream. Gmail rejects messages larger than 25 MB, and base64 encoding makes attachments about a third larger than the file on disk, so the practical limit for files is closer to 18 MB.

Port 465 also works, with SecureSocketOptions.SslOnConnect instead of StartTls. Do not use port 25 from a home or cloud connection; many providers block it.

Using OAuth 2.0 instead

An app password is a long-lived secret with full mail access. If you distribute the app to other users, or your Google Workspace admin has disabled app passwords, use OAuth 2.0. Create an OAuth client in the Google Cloud console, request the https://mail.google.com/ scope (for example with the Google.Apis.Auth package), and hand the access token to MailKit:

await smtp.AuthenticateAsync(new SaslMechanismOAuth2(sender, accessToken));

The rest of the code stays the same. The MailKit repository has a Gmail OAuth walkthrough covering token acquisition and refresh.

Maintaining old System.Net.Mail code

The original version of this post used System.Net.Mail. It still works with Gmail if you swap the account password for an app password:

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

using var mail = new MailMessage(sender, "receiver@example.com", "Monthly report", "See attachment.");
mail.Attachments.Add(new Attachment(@"C:\reports\report.pdf"));

using var client = new SmtpClient("smtp.gmail.com", 587)
{
    EnableSsl = true,
    Credentials = new NetworkCredential(sender, appPassword)
};
await client.SendMailAsync(mail);

Keep it for existing code if you must, but do not start new work with it. It has no OAuth support, cannot connect to port 465, and Microsoft is not adding new protocol support to it. Also note the disposal: MailMessage holds the attachment file open until it is disposed, which is a common cause of “file is being used by another process” errors.

If you are sending from a server, such as password resets or notifications, a personal Gmail account is the wrong tool. Gmail limits how many messages an account can send per day, and bulk sending gets accounts suspended. A transactional email service or your organisation’s own SMTP relay is a better fit.

Related examples

Leave a Comment