Prerequisite You should have an API key from Resend and have it stored in a .env file.

Introduction

This guide demonstrates how to send a basic email using the Resend API. You’ll learn how to set up your environment, configure your API key, and send an email.

Setup

Step 1: Install Required Packages

First, install the necessary packages using pip:

pip install python-dotenv resend

Step 2: Create a .env File

Create a .env file in the project root with your Resend API key and email details:

RESEND_API_KEY=your_resend_api_key
RESEND_EMAIL_FROM=your_email_from_address
RESEND_EMAIL_TO=recipient_email_address

Sending an Email

Step 3: Create the Python Script

Create a Python script named resend-email-example.py with the following content:

resend-email-example.py
import os
from dotenv import load_dotenv
import resend

# Load environment variables from .env file
load_dotenv()

# Get API key and email details from environment variables
resend.api_key = os.getenv('RESEND_API_KEY')
email_from = os.getenv('RESEND_EMAIL_FROM')
email_to = os.getenv('RESEND_EMAIL_TO')

# Define email content
subject = "Hello World"
email_body = "<strong>It works!</strong>"

try:
    # Send the email using Resend API
    response = resend.Emails.send({
        "from": email_from,
        "to": email_to,
        "subject": subject,
        "html": email_body
    })
    # Print and return the response
    print(f"Email sent to {email_to}. Response: {response}")
    response
except Exception as e:
    # Print and return the error message
    print(f"Failed to send email. Error: {e}")
    {"status": "error", "message": str(e)}

Step 4: Run the Script

Ensure you have the .env file in the same directory as the script. Then, execute the script:

python resend-email-example.py

Conclusion

You have successfully sent an email using the Resend API! This guide provided a basic example to get you started. You can now expand on this by customizing the email content and handling different email sending scenarios.