Send email with SendGrid: exact code for API and SMTP in C# and HTML
By Maya Collins Updated 8 min read
Some links on Digital Snatch are affiliate links: if you buy through them we may earn a commission, at no extra cost to you. Prices and ratings come from AppSumo and are checked daily; the deal page always shows the current price.
On this page (8 sections)
In short: To send email using SendGrid, use either the SendGrid API or SendGrid SMTP with minimal C# code: for API, post JSON with email data via SendGrid client; for SMTP, configure SMTP client with SendGrid credentials and send MIME email including HTML.
Part of our guide on millionverifier vs zerobounce
Exact minimal C# code snippets show how to send email via SendGrid API and SMTP, including HTML content handling.
| SendGrid API | HTTP JSON requests |
|---|---|
| SMTP port | 587 or 465 |
| Email size limit | up to 30MB |
| API key length | typically 69 characters |
| HTML support | full MIME content |
The short version
- SendGrid offers two main ways: API for direct HTTP calls, SMTP for standard mail clients.
- Minimal code examples in C# show how to send both plain text and HTML emails.
- You must first create a verified SendGrid account and generate an API key or SMTP credentials.
- Sending HTML content requires building the email body with HTML tags and setting the MIME type.
- Use the API for more features and better error handling; SMTP is simpler but less flexible.
What you need
You need a SendGrid account with email sending enabled and verified sender identity.
Generate an API key with 'Full Access' permissions for API sending or obtain your SMTP username and password.
Install the SendGrid C# client library via NuGet for API usage or use standard .NET SMTP classes.
Prepare your code editor and .NET development environment for compiling and running C# programs. For the detail, see our notes on draft follow up sequences fast.
- SendGrid account with verified sender
- API key or SMTP credentials
- C# .NET development tools
- SendGrid NuGet package (for API)
- Basic knowledge of email MIME types
How to send email via SendGrid API
Using the SendGrid API sends email by calling their HTTP endpoint with JSON data including sender, recipient, subject, and content.
Install the SendGrid NuGet package and write code to build a Mail object, assign fields, and send asynchronously.
This API method supports sending HTML email by specifying the content type as 'text/html' and including HTML tags in the body. There is more on improving bulk email inbox placement in a separate guide.
API sending handles retries and detailed error responses better than SMTP, making it suitable for production.
When sending email via the SendGrid API, you need to handle exceptions and check the response status code. For example, a 202 status code indicates the email was accepted for delivery, while 4xx or 5xx codes signal client or server errors respectively. Checking these codes helps you implement retries or log failures appropriately.
One practical example: after calling SendEmailAsync, you might check if the response.StatusCode equals System.Net.HttpStatusCode.Accepted (202). If not, log the response body for error details. This step ensures you catch issues like invalid API keys, malformed emails, or rate limiting. People in this spot often ask about calculating bounce rates as well.
Note that the API allows sending multiple recipients and personalizations in a single request, reducing the number of calls needed for bulk emails. You can add multiple To, Cc, and Bcc addresses, as well as substitutions for personalized content. This feature is not as straightforward via SMTP, which generally sends one email per recipient list.
- Install SendGrid NuGet package in your C# project.
- Create a SendGridClient instance using your API key.
- Build a SendGridMessage object with From, To, Subject, and Content (plain text or HTML).
- Call the SendEmailAsync method and handle the response status.
| Feature | SendGrid API | SendGrid SMTP |
|---|---|---|
| Protocol | HTTP POST JSON | SMTP standard mail protocol |
| Complexity | Medium, requires SDK | Low, standard SMTP client |
| HTML Email Support | Yes, explicit content type | Yes, MIME email |
| Error Handling | Detailed API responses | Limited SMTP status codes |
| Authentication | API key | Username and password |
| Use case | Preferred for apps | Legacy compatibility |
How to send email using SendGrid SMTP
SendGrid SMTP works like any SMTP server but uses SendGrid credentials and servers (smtp.sendgrid.net).
Configure your SMTP client with host smtp.sendgrid.net, port 587 (TLS) or 465 (SSL), and login with your SendGrid username 'apikey' and the API key as password. The other half of this decision is email verification lifetime offers.
Build a MIME email message in C# with HTML body if needed and send via the SMTP client.
SMTP is simpler to set up if you already use SMTP clients but gives less control than API calls.
Using SMTP with SendGrid requires careful attention to security. Always use TLS (port 587) or SSL (port 465) to encrypt the email transmission. Sending credentials or email content over unencrypted connections risks interception and exposure of sensitive data. People in this spot often ask about manage replies from multiple mailboxes together as well.
A common pitfall is forgetting to set the SMTP client’s EnableSsl property to true when using port 465. Without SSL enabled, the connection will fail or be insecure. For port 587, you must explicitly start TLS with the client’s StartTls() method or equivalent, depending on your SMTP library.
Here is a brief example: create a new SmtpClient with Host = 'smtp.sendgrid.net', Port = 587, EnableSsl = true; then authenticate with NetworkCredential('apikey', your_api_key). Send a MailMessage with From, To, Subject, and Body set. If you get authentication errors, verify your API key and username are correct and active.
- Set SMTP host to 'smtp.sendgrid.net' and use port 587 with TLS.
- Set username to 'apikey' and password to your actual API key string.
- Create a MailMessage setting From, To, Subject, and Body (with IsBodyHtml=true for HTML content).
- Use SmtpClient to send the MailMessage synchronously or asynchronously.
Sending HTML email content with SendGrid
HTML emails require setting the email content type to 'text/html' and embedding valid HTML markup.
Both API and SMTP methods support HTML content, but the API method explicitly defines content types in the message object.
Avoid overly complex HTML or unsupported CSS to ensure compatibility with most email clients.
You can combine plain text and HTML bodies for clients that do not render HTML by providing both parts in the message.
When crafting HTML email content, test your emails across major clients like Outlook, Gmail, Apple Mail, and mobile apps. Some CSS styles may not render consistently, such as float or background images. Using simple table layouts and inline styles increases compatibility.
For example, avoid using JavaScript or external style sheets, as these are stripped or blocked by most clients. Instead, embed styles inline within each element. Tools like Litmus or Email on Acid can simulate email client rendering for testing.
To include both plain text and HTML, create a multipart/alternative MIME structure. This ensures clients that cannot display HTML fallback gracefully to plain text. In the SendGrid API, add both content types to the message. In SMTP, create AlternateViews for plain text and HTML and add them to the MailMessage.
- For API: add a SendGridContent object with 'text/html' type and your HTML string.
- For SMTP: set MailMessage.IsBodyHtml property to true and assign an HTML string to Body.
- Test rendering by sending to multiple email clients to catch formatting issues.
- Keep inline CSS minimal and use tables for layout to maximize client compatibility.
Basic SendGrid account setup for sending email
Sign up at SendGrid’s website and verify your email address to activate sending capabilities.
Add and verify sender identities or domains to prove ownership and reduce spam risk: emails from unverified senders will be rejected.
Generate an API key with appropriate permissions: ‘Full Access’ for sending email via API or SMTP.
Configure domain authentication under Sender Authentication for improved deliverability and inbox placement.
- Create a SendGrid account and validate your email address.
- In SendGrid dashboard, navigate to Sender Authentication and add a verified sender email or domain.
- Create an API key in the Settings > API Keys section and copy it securely.
- If using SMTP, confirm SMTP username is 'apikey' and use your API key as the password.
Common mistakes when sending email with SendGrid
One frequent mistake is neglecting to handle SendGrid API rate limits. When too many requests are made in a short time, SendGrid returns a 429 Too Many Requests status. Failing to detect and wait before retrying causes unnecessary failures and blocked sends.
Another issue is not monitoring bounce or spam reports. SendGrid provides event webhooks to track delivery status, bounces, and spam complaints. Ignoring these reports results in degraded sender reputation and deliverability over time.
Hardcoding API keys in source code repositories, especially public ones, exposes your credentials to abuse. Use environment variables or secure secrets management to store keys safely. If a key is compromised, revoke it immediately from your SendGrid dashboard to prevent unauthorized use.
- Using incorrect SMTP credentials– use 'apikey' as username and your API key as password.
- Not verifying sender email or domain– leads to emails being rejected or spammed.
- Hardcoding API keys in public code repositories– exposes your key to misuse.
- Sending complex HTML without testing– causes rendering errors in many email clients.
- Ignoring API response errors– losing track of delivery failures or limits exceeded.
Questions people still ask
Can I send bulk emails using SendGrid API or SMTP?
Yes, but you must respect SendGrid's sending limits and best practices. Use the API for more efficient bulk sends with templates and personalization. SMTP can send bulk but less efficiently.
How do I include attachments with SendGrid API in C#?
Add attachments as Base64 encoded content in the SendGridMessage.Attachments collection, specifying filename and MIME type. SMTP attachments are added to the MailMessage.Attachments property.
What port should I use for SendGrid SMTP?
Use port 587 for TLS encryption or port 465 for SSL. Port 25 is often blocked by ISPs and not recommended.
Is SendGrid free to use for sending emails?
SendGrid offers a free tier with monthly sending limits. For higher volumes, you must upgrade to paid plans.
How do I handle email bounces with SendGrid?
Configure SendGrid’s webhook event notifications to receive bounce events. This data helps maintain list hygiene and improves deliverability.
