Skip to content

SendGrid Sandbox Mode — Testing Email Sending Without Delivery

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about SendGrid Sandbox Mode. We cover key concepts, practical examples, and best practices to help you master this topic.

SendGrid sandbox mode intercepts email send requests and returns a successful response without delivering the email, allowing developers to test API integration, template rendering, and personalization without sending to real recipients.

What You'll Learn

  • How to enable sandbox mode for testing
  • How to validate template rendering without sending
  • How to test personalization and attachment formatting

Why It Matters

Testing email sending in production risks sending test emails to real users or filling your own inbox with test messages. Sandbox mode lets you validate the entire email pipeline — API calls, template rendering, personalization, and attachments — without delivering a single email.

Real-World Use

DodaTech's CI/CD pipeline runs 50+ email tests using sandbox mode. Each test sends a complex email with dynamic templates, attachments, and categories, validates the 202 response, and checks that the request body was formatted correctly — all without delivering actual emails.

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, SandBoxMode, MailSettings
import base64

def send_test_email_sandbox(to_email, template_id, template_data):
    sg = SendGridAPIClient(SENDGRID_API_KEY)

    message = Mail(
        from_email='test@dodatech.com',
        to_emails=to_email,
        subject='[TEST] Welcome Email'
    )
    message.template_id = template_id
    message.dynamic_template_data = template_data

    # Enable sandbox mode
    mail_settings = MailSettings()
    mail_settings.sandbox_mode = SandBoxMode(enable=True)
    message.mail_settings = mail_settings

    try:
        response = sg.send(message)
        # Sandbox returns 200 OK with no email actually sent
        print(f"Test passed! Status: {response.status_code}")
        print("No email was delivered.")
        return True
    except Exception as e:
        print(f"Test failed: {str(e)}")
        return False

Testing Attachments

def test_attachment_format():
    """Test that attachments are properly formatted without sending"""
    pdf_content = b'%PDF-1.4 test content for validation'
    pdf_encoded = base64.b64encode(pdf_content).decode()

    message = Mail(
        from_email='test@dodatech.com',
        to_emails='test@example.com',
        subject='Test Attachment',
        html_content='<p>Test attachment</p>'
    )

    # Add test attachment
    from sendgrid.helpers.mail import Attachment, FileContent, FileName, FileType, Disposition
    attachment = Attachment(
        FileContent(pdf_encoded),
        FileName('test.pdf'),
        FileType('application/pdf'),
        Disposition('attachment')
    )
    message.add_attachment(attachment)

    # Enable sandbox
    mail_settings = MailSettings()
    mail_settings.sandbox_mode = SandBoxMode(enable=True)
    message.mail_settings = mail_settings

    sg = SendGridAPIClient(SENDGRID_API_KEY)
    response = sg.send(message)

    # Verify response
    assert response.status_code == 200 or response.status_code == 202
    print("Attachment test passed!")

    # Validate attachment size
    assert len(pdf_encoded) < 100000  # Max size check
    print(f"Attachment size: {len(pdf_encoded)} bytes (encoded)")

API-Level Sandbox Testing

import requests

def test_email_via_api_sandbox():
    """Test email request formatting via raw API with sandbox"""
    response = requests.post(
        "https://api.sendgrid.com/v3/mail/send",
        headers={
            "Authorization": f"Bearer {SENDGRID_API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "personalizations": [{
                "to": [{"email": "test@example.com"}],
                "dynamic_template_data": {
                    "userName": "Test User",
                    "companyName": "DodaTech"
                }
            }],
            "from": {"email": "test@dodatech.com"},
            "subject": "[TEST] Welcome",
            "content": [{"type": "text/html", "value": "<p>Test</p>"}],
            "mail_settings": {
                "sandbox_mode": {
                    "enable": True
                }
            }
        }
    )

    if response.status_code == 202:
        print("API test passed! Sandbox mode prevented delivery.")
        return True
    else:
        print(f"API test failed: {response.status_code} {response.text}")
        return False

Common Mistakes

1. Forgetting to Disable Sandbox in Production

If sandbox mode is accidentally left enabled in production, no emails are sent. Use environment variables to control sandbox mode.

2. Using Sandbox for Non-Testing Purposes

Sandbox mode does not validate that the rendered email looks correct. Use the SendGrid UI preview or test send for visual testing.

3. Not Testing Different Email Clients

Sandbox mode only validates the API request, not rendering across email clients (Gmail, Outlook, Apple Mail). Use Litmus or Email on Acid for rendering tests.

4. Testing at Production Volume

Sandbox mode counts against your API request rate limits. Use sandbox for functional testing, not load testing.

5. Assuming Sandbox Tests Full Delivery Pipeline

Sandbox mode skips template rendering, spam filter checks, and delivery processing. It only validates the API request format.

Practice Questions

  1. What does sandbox mode do?
  2. How do you enable sandbox mode?
  3. Does sandbox mode count against your email quota?
  4. Can sandbox mode test template rendering?
  5. What is the risk of leaving sandbox mode enabled?

Answers

  1. It intercepts email sends and returns success without delivery. 2. Set mail_settings.sandbox_mode.enable = True. 3. No, it does not count against quota. 4. No, it only validates the API request, not rendering. 5. No emails are sent in production.

Challenge

Build a comprehensive email test suite that: runs all email types (welcome, invoice, password reset) through sandbox mode, validates API responses, checks attachment formatting, verifies template data, and reports any failures with detailed error messages.

FAQ

What is sandbox mode in SendGrid?

A testing mode that intercepts email sends and returns success without delivering.

Does sandbox mode cost money?

No. Sandbox mode emails do not count against your monthly quota.

Can I test dynamic templates with sandbox mode?

Yes, but it only validates the API request, not the rendered template output.

How do I enable sandbox mode?

Set mail_settings.sandbox_mode.enable to true in your API request.

Does sandbox mode count against rate limits?

Yes, sandbox requests count towards your API rate limit.

Mini Project

Build a pre-deployment email validation tool that: sends every email template through sandbox mode, validates response status codes, checks that all dynamic template data fields are present, verifies attachment sizes and formats, and generates a report of pass/fail status for each email type before allowing deployment.

What's Next

  • Learn about bounce handling and why emails bounce
  • Explore block handling for rejected emails
  • Continue to spam report handling and reputation management

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro