These integration guides are not official documentation and the Strapi Support Team will not provide assistance with them.
What Is SendGrid?
SendGrid is a cloud-based email delivery platform that handles message sending through traditional SMTP or a modern REST API, eliminating the need to build or maintain your own mail server. Configure an API key, call an endpoint, and SendGrid manages queuing, retries, and feedback loops automatically.
Transactional emails—password resets, order confirmations, verification links—fire automatically in response to user actions. Marketing emails are scheduled campaigns for promotion and relationship nurturing. SendGrid supports both types, with its API particularly effective for high-volume, low-latency transactional requirements.
Beyond raw delivery, SendGrid provides high deliverability rates, sender authentication tools, and bounce management to keep messages out of spam folders. Scalable infrastructure handles traffic spikes without rate-limit issues.
Customizable dynamic templates and detailed analytics track opens, clicks, and bounces in real time, converting raw SMTP events into actionable data. The API-first approach allows programmatic template adjustments, audience segmentation, and performance monitoring directly from your codebase, letting you focus on product features rather than email infrastructure.
Why Integrate SendGrid with Strapi
Pairing Strapi's flexible content management with SendGrid's purpose-built email platform creates an end-to-end workflow for messages that land where they're supposed to—your users' inboxes—without bolting on extra infrastructure.
Strapi's plugin architecture treats email as a first-class citizen, so you can install the official SendGrid provider from the Marketplace and drop a few environment variables into place. Because the provider follows the same pattern as other plugins, swapping or upgrading services later is nothing more than a config change, not a refactor.
Every action in Strapi—user registration, password reset, content publication—can trigger lifecycle hooks that fire off emails through SendGrid's API. By wiring a hook such as afterCreate to the email service, you automatically send confirmations the moment a new account is created, or ping subscribers when a blog post goes live.
The result is real-time communication handled entirely inside your CMS, which you can verify from the Strapi Admin Panel or through the official email documentation.
Strapi's structured data lets you inject user names, order numbers, or Media Library assets directly into dynamic templates. Need a receipt with a branded image attachment? Pull the file's URL from Strapi and let SendGrid handle embedded media.
SendGrid manages DKIM, bounce suppression, and high-volume queuing so you don't have to. Its analytics surface open rates and clicks, while it provides deliverability insights rather than explicit spam report analytics.
SPF configuration requires manual DNS setup. Strapi remains focused on content. That separation means you can grow from a handful of daily notifications to thousands without re-architecting anything.
With one npm install and a dozen lines of configuration, you gain a production-ready email pipeline.
The provider respects environment variables, works the same on local dev and Strapi Cloud (see the cloud-specific instructions in the advanced email guide), and surfaces a simple strapi.plugin('email').service('email').send() API you can call from any controller. Less boilerplate, fewer moving parts, and more time spent shipping features.
Keep in touch with the latest Strapi and SendGrid updates
How to Integrate SendGrid with Strapi
This comprehensive workflow covers two approaches: Strapi's official provider and a custom SDK setup. You'll configure API keys, environment variables, dynamic templates, and sandbox testing to build a complete email solution.
Prerequisites
Your development environment needs Node.js 16 or higher, npm or Yarn, and Strapi v4+. For your SendGrid account, you can create API keys without a verified sender identity or authenticated domain, but verifying your sender identity or domain is recommended to send emails reliably.
You should be comfortable with JavaScript, RESTful APIs, and basic email concepts including SPF and DKIM records for deliverability. Cloud users need to understand where environment variables are added in the dashboard.
Environment variable management is essential since all secrets (API keys, default senders) must stay outside your codebase for security.
Setting Up Your Environment
From your Strapi project root, install the official provider:
1npm install @strapi/provider-email-sendgridCreate a .env file:
1SENDGRID_API_KEY=SG.xxxxxx
2SENDGRID_DEFAULT_FROM=no-reply@yourdomain.com
3SENDGRID_DEFAULT_REPLY_TO=support@yourdomain.comAdd .env to .gitignore so secrets never hit version control. For production, map the same keys in your hosting dashboard. Cloud users can add them under Settings → Variables. Development and production typically use different keys and sender addresses.
Configuring SendGrid for Integration
In the SendGrid dashboard, open Settings → API Keys and generate a key with "Mail Send" permission. Copy it immediately—SendGrid won't display it again. Under Sender Authentication, choose either Single Sender for prototypes or Domain Authentication for production, which signs emails with SPF/DKIM for inbox trust.
For dynamic templates, navigate to Email API → Dynamic Templates and create one now. Note the template ID. Key endpoints include /mail/send, /templates, and /user/webhooks/event. Test your key:
1curl -X POST https://api.sendgrid.com/v3/mail/send \
2 -H "Authorization: Bearer $SENDGRID_API_KEY" \
3 -H "Content-Type: application/json" \
4 -d '{ "personalizations":[{ "to":[{ "email":"test@yourdomain.com"}]}], "from":{ "email":"test@yourdomain.com"}, "subject":"Ping", "content":[{ "type":"text/plain", "value":"It works"}]}'A 202 status confirms your setup.
Configuration Method 1: Strapi Email Provider Plugin
For most projects, the plugin handles everything you need. Create config/plugins.js (or .ts) and configure the provider:
1module.exports = ({ env }) => ({
2 email: {
3 config: {
4 provider: 'sendgrid',
5 providerOptions: {
6 apiKey: env('SENDGRID_API_KEY'),
7 },
8 settings: {
9 defaultFrom: env('SENDGRID_DEFAULT_FROM'),
10 defaultReplyTo: env('SENDGRID_DEFAULT_REPLY_TO'),
11 },
12 },
13 },
14});Send mail from any controller or service:
1await strapi
2 .plugin('email')
3 .service('email')
4 .send({
5 to: user.email,
6 subject: 'Welcome aboard!',
7 html: `<p>Hello ${user.username}, your account is live.</p>`,
8 });The provider works with Strapi's Admin Panel, allowing non-technical teammates to trigger test sends without code changes.
Configuration Method 2: Custom API Integration
For fine-grained control over scheduling, attachments, or advanced templates, use the SDK directly:
1npm install @sendgrid/mailCreate src/services/sendgrid.js:
1// src/services/sendgrid.js
2'use strict';
3
4const sgMail = require('@sendgrid/mail');
5
6module.exports = ({ env }) => {
7 sgMail.setApiKey(env('SENDGRID_API_KEY'));
8
9 const send = async ({ to, subject, html, templateId, data }) => {
10 const msg = {
11 to,
12 from: env('SENDGRID_DEFAULT_FROM'),
13 subject,
14 html,
15 // Use one path or the other:
16 templateId,
17 dynamic_template_data: data,
18 };
19
20 try {
21 await sgMail.send(msg);
22 } catch (error) {
23 strapi.log.error('SendGrid error', error.response?.body);
24 throw error;
25 }
26 };
27
28 return { send };
29};This approach provides direct access to every feature, from batch sends to scheduled delivery. You're also responsible for SDK updates and maintenance.
Implementing Email Templates
Dynamic templates separate layout from logic. Create a template with Handlebars placeholders like {{name}} or {{reset_link}}. Publish the version and store its ID in your .env or configuration.
Sending with the plugin:
1await strapi
2 .plugin('email')
3 .service('email')
4 .send({
5 to: user.email,
6 from: env('SENDGRID_DEFAULT_FROM'),
7 templateId: env('SENDGRID_WELCOME_TEMPLATE'),
8 dynamic_template_data: {
9 name: user.username,
10 reset_link: `https://yourapp.com/reset?token=${token}`,
11 },
12 });Strapi's structured content types map directly to dynamic_template_data, enabling personalized experiences for each recipient.
Testing the Integration
To prevent real email sends during development, use dedicated email testing services like Mailtrap, as neither SendGrid nor Strapi's Admin Panel includes a built-in sandbox mode or a native 'Send test email' feature. For end-to-end testing, create a dummy user, trigger registration via the API, and monitor the Activity Feed for Delivered or Bounce events.
Log responses for valuable error codes when SPF, DKIM, or rate limits affect delivery. Consistent 202 responses and successful inbox delivery confirm production readiness.
Keep in touch with the latest Strapi and SendGrid updates
Project Example: Build a Subscription Platform with SendGrid and Strapi
Imagine you're launching "Newsletter Hub," a subscription service that sends curated weekly digests to tech enthusiasts. Strapi sits at the core, exposing a subscribers Collection Type and storing every article you publish; SendGrid delivers the emails; a Next.js frontend handles sign-ups and profile management.
Users sign up on the site, Strapi creates a subscriber record, a confirmation email arrives in their inbox, and once they verify, they start receiving the weekly digest assembled from new content.
Below is an excerpt of the custom Strapi service powering this workflow. It listens to the afterCreate lifecycle of the Subscriber content type, generates a verification token, and sends a confirmation email with dynamic template data:
1// src/api/subscriber/services/email-service.js
2'use strict';
3
4const sgMail = require('@sendgrid/mail');
5sgMail.setApiKey(process.env.SENDGRID_API_KEY);
6
7module.exports = {
8 async afterCreate(event) {
9 const { email, fullName } = event.result;
10
11 // Token generation handled by a separate utility
12 const token = await strapi
13 .service('api::token.token')
14 .createVerification(email);
15
16 const verificationUrl = `https://yourapp.com/verify?token=${token}`;
17
18 await sgMail.send({
19 to: email,
20 from: process.env.SENDGRID_DEFAULT_FROM,
21 templateId: process.env.SENDGRID_TEMPLATE_CONFIRMATION,
22 dynamic_template_data: {
23 name: fullName,
24 verification_url: verificationUrl,
25 },
26 });
27 },
28
29 async sendWeeklyDigest(subscriber, digestContent) {
30 await sgMail.send({
31 to: subscriber.email,
32 from: process.env.SENDGRID_DEFAULT_FROM,
33 templateId: process.env.SENDGRID_TEMPLATE_DIGEST,
34 dynamic_template_data: digestContent,
35 });
36 },
37};Building a real-world platform introduces four technical hurdles you'll want to tackle early:
- Rate limiting for bulk sends: Requires queuing outgoing messages or batching them so you never exceed account quotas.
- Deliverability through domain authentication: Means configuring SPF and DKIM records to keep confirmations out of spam and ensure high inbox placement.
- Template versioning and synchronization: Involves maintaining template IDs in environment variables and documenting changes so frontend and backend teams stay aligned.
- Webhook event handling: Requires exposing a secure Strapi endpoint to receive event webhooks, updating subscriber status on bounces, blocks, or successful deliveries.
Once these foundations are solid, you can build compelling features:
- Automated sequences: Trigger when new articles are published, thanks to Strapi lifecycle hooks.
- Personalization: Becomes straightforward—each digest can reference the reader's chosen topics pulled from Strapi fields.
- Analytics integration: Coupled with analytics, you'll surface open and click rates directly in an internal dashboard for rapid content iteration.
Follow best practices: store API keys in environment variables, add exponential back-off retries around email sends, and log every request for auditing. While the Newsletter Hub code is intentionally concise—omitting queue infrastructure and full token validation—it demonstrates the minimal surface area you need to ship a production-grade subscription engine.
Advanced SendGrid Features with Strapi
Once the basic setup is running, you can tap into richer features to tighten feedback loops, automate campaigns, and keep your inbox reputation healthy. Webhooks let you capture real-time events (opens, clicks, bounces), the send_at parameter schedules messages for the perfect moment, while A/B tests and suppression lists keep your content relevant and compliant.
The Event Webhook is the cornerstone. By posting delivery data back to Strapi, you can store engagement metrics alongside user records and trigger follow-up actions through lifecycle hooks. A minimal controller might look like this:
1// src/api/email-event/controllers/email-event.js
2module.exports = {
3 async sendgridWebhook(ctx) {
4 const sig = ctx.request.headers['sendgrid-signature'];
5 const timestamp = ctx.request.headers['sendgrid-timestamp'];
6 const events = ctx.request.body;
7
8 // Verify signature (replace with a real util from SendGrid docs)
9 if (!strapi.utils.verifySendgridSignature(sig, timestamp, events)) {
10 ctx.throw(401, 'Invalid signature');
11 }
12
13 // Persist first event; extend as needed
14 await strapi.db.query('api::email-event.email-event').create({
15 data: {
16 type: events[0].event,
17 email: events[0].email,
18 metadata: events[0],
19 },
20 });
21
22 ctx.send({ received: true });
23 },
24};Always validate the signature documented in the API reference to prevent spoofing. Schedule bursts or drip campaigns by passing send_at in the payload, letting SendGrid queue messages while Strapi focuses on content.
Run A/B tests by rotating template IDs and logging webhook results to identify the highest-converting variant. Sync suppression groups to Strapi so that unsubscribed users are excluded automatically, avoiding costly compliance mistakes.
Pair webhook data with custom dashboards or pipe it into external analytics. Monitor both the activity feed and Strapi logs to catch anomalies early and keep delivery rates high.
Troubleshooting Common Issues
Even the most carefully configured integrations can encounter issues. Here's how to diagnose and resolve common problems when connecting Strapi with SendGrid:
Authentication errors: Surface when Strapi can't connect to the service. Check that
SENDGRID_API_KEYloads before Strapi starts and verify the key has "Mail Send" permission. A typo or missing variable inconfig/plugins.jsprevents Strapi from loading the provider, throwing a "Could not load email provider 'sendgrid'" message in server logs. Confirm your key in the dashboard, then restart the server.Sender verification issues: SendGrid blocks emails when sender verification fails or rate limits trigger. A 403 response mentioning "from address does not match a verified Sender Identity" indicates you're sending from an unverified address. Verify the sender or authenticate your domain in the UI. The activity feed shows blocked requests in real time—track these patterns to identify verification gaps.
Deliverability problems: Delivered emails that disappear point to deliverability problems. Missing SPF or DKIM records route messages to spam or cause bounces. After publishing DNS records from domain authentication, retest and monitor the bounce column in the activity feed. Numbers drop immediately when records propagate correctly.
Template errors: Break silently. Unmatched
{{variable}}placeholders in dynamic templates or defaultno-reply@strapi.iosenders embedded in Strapi's templates cause failures without clear error messages. Match every placeholder with data indynamic_template_dataand replace default addresses with verified ones.Webhook failures: Occur when signatures aren't validated or endpoints aren't publicly reachable. Verify timestamp and signature headers on each call and restrict traffic to HTTPS for your
/webhooks/sendgridroute.
For deeper investigation, reference the documentation and community resources. When logs don't reveal the issue, the support forum provides additional troubleshooting guidance.
Strapi Open Office Hours
If you have any questions about Strapi 5 or just would like to stop by and say hi, you can join us at Strapi's Discord Open Office Hours, Monday through Friday, from 12:30 pm to 1:30 pm CST.
For more details, visit the Strapi documentation and the SendGrid documentation.