How to Use Resend MCP Servers to Send Emails

Community Article Published April 27, 2025

Email remains a critical communication channel for applications, whether for transactional notifications, marketing campaigns, or user engagement. However, building and maintaining a reliable email sending infrastructure is complex, involving challenges like deliverability, scalability, and reputation management. This is where email API services like Resend step in.

Resend is a modern email API designed specifically for developers. It focuses on providing a clean, simple interface, excellent deliverability, and robust features to make sending emails programmatically a breeze. Forget wrestling with SMTP servers, IP reputation, and arcane configuration files; Resend handles the heavy lifting, letting you focus on building your application.

Why Choose Resend?

  • Developer-First: Built with developers in mind, featuring clear documentation, helpful SDKs, and a straightforward API.
  • High Deliverability: Focuses on ensuring your emails actually reach the inbox by managing infrastructure, authentication (SPF, DKIM, DMARC), and reputation.
  • Scalability: Handles sending volume from a few emails to millions without you needing to manage servers.
  • Modern Features: Offers features like webhooks for real-time tracking, templating support, and detailed analytics.
  • Simple Pricing: Often features generous free tiers and predictable paid plans.

This tutorial will guide you through the entire process of integrating Resend into your application, from setting up your account to sending emails programmatically and implementing best practices. We'll cover:

  1. Getting Started: Signing up, setting up your domain, and obtaining API keys.
  2. Environment Setup: Installing the necessary tools (using Python as an example).
  3. Sending Emails: Crafting and sending your first emails via the API.
  4. Advanced Features: Incorporating attachments and using tags.
  5. Monitoring: Handling responses and using webhooks.
  6. Best Practices: Ensuring deliverability and avoiding common pitfalls.

By the end of this guide, you'll be equipped to reliably send emails from your application using Resend.

1. Getting Started with Resend

Tired of Postman? Want a decent postman alternative that doesn't suck?

Apidog is a powerful all-in-one API development platform that's revolutionizing how developers design, test, and document their APIs.

Unlike traditional tools like Postman, Apidog seamlessly integrates API design, automated testing, mock servers, and documentation into a single cohesive workflow. With its intuitive interface, collaborative features, and comprehensive toolset, Apidog eliminates the need to juggle multiple applications during your API development process.

Whether you're a solo developer or part of a large team, Apidog streamlines your workflow, increases productivity, and ensures consistent API quality across your projects.

image/png

Before writing any code, you need to set up your Resend account and configure it for sending.

A. Sign Up for a Resend Account

Navigate to the Resend website and sign up for an account. They typically offer a free tier that's perfect for development and testing, allowing you to send a certain number of emails per month without charge.

B. Explore the Dashboard

Once logged in, familiarize yourself with the Resend dashboard. Key areas include:

  • Overview: A summary of your sending activity.
  • Domains: Where you'll add and manage the domains you want to send emails from.
  • API Keys: Where you generate and manage the keys your application will use to authenticate with the Resend API.
  • Emails: Logs of emails sent, including their status (sent, delivered, bounced, etc.).
  • Webhooks: Configuration for receiving real-time notifications about email events.

C. Create an API Key

Your application needs an API key to securely interact with Resend.

  1. Go to the "API Keys" section in the dashboard.
  2. Click "Create API Key".
  3. Give your key a descriptive name (e.g., "MyWebApp Production" or "Development Test Key").
  4. Choose the appropriate permissions (often "Full access" is needed for sending).
  5. Click "Create".

Crucially: Resend will show you the API key only once. Copy it immediately and store it securely. Treat this key like a password; anyone with access to it can send emails from your account. We'll discuss secure storage later.

D. Add and Verify Your Domain

To send emails that appear to come from your domain (e.g., [email protected]) and maximize deliverability, you must add and verify your domain with Resend. Sending from unverified domains often lands emails in spam or gets them rejected entirely.

  1. Go to the "Domains" section.
  2. Click "Add Domain".
  3. Enter the domain name you want to send emails from (e.g., yourdomain.com).
  4. Choose the region closest to your users.
  5. Click "Add".

Resend will now provide you with several DNS records (usually types like TXT, CNAME, or MX) that you need to add to your domain's DNS settings via your domain registrar (like GoDaddy, Namecheap, Cloudflare, etc.). These records typically include:

  • SPF (Sender Policy Framework): Specifies which mail servers are authorized to send emails on behalf of your domain.
  • DKIM (DomainKeys Identified Mail): Adds a digital signature to your emails, allowing receiving servers to verify the email hasn't been tampered with and originates from your authorized servers.
  • DMARC (Domain-based Message Authentication, Reporting, and Conformance): Tells receiving servers what to do with emails that fail SPF or DKIM checks (reject, quarantine, or monitor) and where to send reports. While Resend might not strictly require DMARC for basic sending, implementing it is a critical best practice for long-term deliverability and security.

Adding DNS records can take some time to propagate (anywhere from a few minutes to 48 hours, though usually much faster). Once Resend detects the correct records, your domain status in the dashboard will change to "Verified". You can only send emails from verified domains (or the initial onboarding.resend.com domain provided for testing).

2. Setting Up Your Development Environment (Python Example)

Now let's prepare your local environment to interact with the Resend API. We'll use Python for our examples, but Resend offers official SDKs for Node.js, Ruby, PHP, Go, Java, Elixir, and .NET. The concepts are similar across languages.

A. Install the Resend Python SDK

If you haven't already, make sure you have Python and pip (Python's package installer) installed. Then, install the Resend library:

pip install resend

B. Secure Your API Key

Never hardcode your API key directly into your source code. This is a major security risk. Instead, use environment variables.

  1. Create a file named .env in the root of your project directory (ensure this file is listed in your .gitignore file to prevent accidentally committing it).

  2. Add your API key to the .env file:

    RESEND_API_KEY=re_YOUR_API_KEY_HERE
    
  3. Install a library to load environment variables from the .env file into your application environment, such as python-dotenv:

    pip install python-dotenv
    
  4. In your Python script, you can now load and access the key like this:

    import os
    import resend
    from dotenv import load_dotenv
    
    load_dotenv() # Load variables from .env file
    
    resend.api_key = os.getenv("RESEND_API_KEY")
    
    if not resend.api_key:
        raise ValueError("RESEND_API_KEY environment variable not set.")
    
    # ... rest of your email sending code ...
    

3. Sending Your First Email Programmatically

With the setup complete, let's send an email using the Python SDK.

A. Basic Email Structure

The core components of any email sent via the Resend API are:

  • from: The sender's email address (must be associated with a verified domain or the test domain).
  • to: The recipient's email address (or a list of addresses).
  • subject: The email's subject line.
  • html or text: The body of the email. Providing html allows for rich formatting, while text provides a fallback for clients that don't render HTML. It's best practice to provide both.

B. Code Example (Python)

Create a Python file (e.g., send_test_email.py) and add the following code:

import os
import resend
from dotenv import load_dotenv

# Load environment variables (especially the API key)
load_dotenv()
resend.api_key = os.getenv("RESEND_API_KEY")

if not resend.api_key:
    raise ValueError("RESEND_API_KEY environment variable not set.")

# Define email parameters
params = {
    "from": "Your Name <[email protected]>", # Replace with your verified sender
    "to": ["[email protected]"], # Replace with the recipient's email
    "subject": "My First Email with Resend!",
    "html": "<h1>Hello from Resend!</h1><p>This is my <strong>first email</strong> sent using the Resend Python SDK.</p>",
    "text": "Hello from Resend! This is my first email sent using the Resend Python SDK.",
    "tags": [ # Optional tags for categorization
        {"name": "category", "value": "test_emails"},
        {"name": "source", "value": "python_sdk_tutorial"}
    ]
}

try:
    print(f"Sending email to {params['to']}...")
    email = resend.Emails.send(params)
    print(f"Email sent successfully! ID: {email['id']}")
    # The response object 'email' contains the ID of the sent email
    # {'id': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'}

except Exception as e:
    print(f"Error sending email: {e}")

Explanation:

  1. Import Libraries: We import os and dotenv for environment variable handling and resend for the SDK.
  2. Load API Key: We load the .env file and set resend.api_key.
  3. Define Parameters: We create a dictionary params holding all the necessary information for the email.
    • from: Format often includes a name (Your Name <sender@...>), but just the email address works too. Crucially, the domain (yourverifieddomain.com) must be verified in Resend.
    • to: This is a list of strings, even for a single recipient.
    • subject: The subject line.
    • html: The HTML version of your email body.
    • text: The plain text version.
    • tags: An optional list of key-value pairs for tracking and filtering emails within the Resend dashboard.
  4. Send Email: resend.Emails.send(params) makes the API call.
  5. Handle Response:
    • If successful, the call returns a dictionary containing the id of the sent email.
    • If an error occurs (e.g., invalid API key, unverified domain, rate limit exceeded), an exception is raised, which we catch and print.

C. Running the Code

  1. Replace "Your Name <[email protected]>" and "[email protected]" with your actual verified sender address and a test recipient address.
  2. Ensure your .env file is correctly set up with your RESEND_API_KEY.
  3. Run the script from your terminal: python send_test_email.py

Check the recipient's inbox (and spam folder, just in case during initial testing). You should also see the email logged in your Resend dashboard under the "Emails" section.

D. Sending to Multiple Recipients (To, Cc, Bcc)

The SDK makes sending to multiple people straightforward:

params = {
    "from": "[email protected]",
    "to": ["[email protected]", "[email protected]"],
    "cc": ["[email protected]"],
    "bcc": ["[email protected]"],
    "subject": "Group Update",
    "html": "<p>Hello team!</p>",
    "text": "Hello team!",
}

# ... send email using resend.Emails.send(params) ...

Simply provide lists of email addresses for the to, cc, and bcc fields.

4. Advanced Email Features

Resend supports more than just basic text and HTML emails.

A. Sending Attachments

To send files, you need to read the file content and provide it in the attachments parameter.

import os
import resend
from dotenv import load_dotenv

load_dotenv()
resend.api_key = os.getenv("RESEND_API_KEY")

# --- Read attachment content ---
attachment_path = "path/to/your/invoice.pdf" # Replace with actual path
file_content = b""
try:
    with open(attachment_path, "rb") as f: # Read in binary mode
        file_content = f.read()
except FileNotFoundError:
    print(f"Error: Attachment file not found at {attachment_path}")
    exit()
# -----------------------------

params = {
    "from": "Billing <[email protected]>",
    "to": ["[email protected]"],
    "subject": "Your Invoice",
    "html": "<p>Please find your invoice attached.</p>",
    "text": "Please find your invoice attached.",
    "attachments": [
        {
            "filename": "invoice_customer_copy.pdf", # Name recipient sees
            "content": file_content # The raw file content
        }
    ],
}

try:
    email = resend.Emails.send(params)
    print(f"Email with attachment sent successfully! ID: {email['id']}")
except Exception as e:
    print(f"Error sending email with attachment: {e}")

The attachments parameter takes a list of dictionaries. Each dictionary needs:

  • filename: The name the recipient will see for the attached file.
  • content: The raw binary content of the file. Read the file in binary mode ("rb") to ensure correct handling.

B. Using Email Templates

While Resend focuses on the sending mechanism, you often need dynamic email content. You can achieve this in a few ways:

  1. Server-Side Templating: Use your application's templating engine (like Jinja2 in Flask/Django, Handlebars in Node.js, ERB in Rails) to generate the HTML and text content before passing it to the Resend send function. This is the most common approach.
  2. Resend Templates (React Email): Resend heavily promotes using React Email, an open-source library (not tied only to Resend) for building email templates using React components. You can render these templates to HTML strings in your backend (even if it's not Node.js) and then send them via Resend. This offers a modern component-based way to design emails.

C. Custom Headers

Add custom email headers using the headers parameter (a dictionary):

params = {
    # ... other params ...
    "headers": {
        "X-Customer-ID": "cust_12345",
        "X-Mailer-Source": "MyPythonApp"
    }
}

5. Handling Responses and Webhooks

Understanding what happens after you call send is crucial.

A. API Response

  • Success: The resend.Emails.send() function returns a dictionary like {'id': '...'}. This ID confirms Resend accepted the email for delivery. It does not guarantee delivery itself.
  • Failure: An exception is raised. The exception message usually contains details about the error (e.g., missing_required_fields, invalid_api_key, validation_error, domain_not_verified). Log these errors for debugging.

B. Webhooks for Real-Time Events

Delivery happens asynchronously. To get real-time updates on email status (delivered, bounced, opened, clicked, marked as spam), use Webhooks.

  1. Create a Webhook Endpoint: Build an HTTP endpoint (URL) in your web application that can receive POST requests from Resend.
  2. Configure in Resend: Go to the "Webhooks" section in the Resend dashboard. Add a new webhook, providing the URL of your endpoint and selecting the events you want to be notified about (e.g., email.delivered, email.bounced, email.complained).
  3. Secure Your Endpoint: Resend signs webhook requests with a secret signature. Verify this signature in your endpoint to ensure the request genuinely came from Resend. The SDK or documentation provides details on how to do this.
  4. Process Events: When an event occurs (e.g., an email bounces), Resend sends a JSON payload to your endpoint. Your application should parse this payload and take appropriate action, such as marking the user's email as invalid in your database or logging the event.

Monitoring bounces and complaints is vital for maintaining good sender reputation. High bounce/complaint rates can get your sending privileges restricted.

6. Best Practices and Troubleshooting

  • Verify Domains: Always send from verified domains using proper SPF/DKIM/DMARC. This is the single most important factor for deliverability.
  • Use Environment Variables: Never expose API keys in code.
  • Provide Both HTML and Text: Ensures readability across all email clients.
  • Monitor Bounces/Complaints: Use webhooks to track these events and clean your mailing lists (remove invalid addresses). High rates damage your reputation.
  • Warm-Up IPs (High Volume): If sending very large volumes, consult Resend's documentation or support about IP warming strategies.
  • Respect Unsubscribes: Provide a clear unsubscribe link (often legally required) and honor requests immediately.
  • Content Matters: Avoid spammy content, misleading subject lines, and excessive images.
  • Check Resend Logs: The "Emails" section in the dashboard is invaluable for debugging specific sending issues.
  • Rate Limits: Be aware of sending limits on your plan. Implement retries with exponential backoff in your code if you anticipate hitting limits.

Common Troubleshooting:

  • 401 Unauthorized / invalid_api_key: Check if your API key is correct and properly loaded via environment variables.
  • 422 Unprocessable Entity / domain_not_verified: Ensure the from address uses a domain fully verified in Resend (check DNS record status).
  • 422 Unprocessable Entity / missing_required_fields: Double-check that from, to, subject, and at least one of html or text are provided.
  • Emails Go to Spam: Review domain authentication (SPF/DKIM/DMARC), check content against spam filters, ensure list hygiene, and consider sender reputation.

Conclusion

Resend offers a powerful yet simple way for developers to integrate reliable email sending into their applications. By setting up your account correctly, verifying your domain, using the SDKs, handling responses/webhooks, and following deliverability best practices, you can ensure your crucial application emails reach their destination. Explore the official Resend documentation for even more features like detailed analytics, suppression lists, and advanced configurations.

Community

Your need to confirm your account before you can post a new comment.

Sign up or log in to comment