Install Required Libraries
- To send emails using the SendGrid API with Python, first ensure you have the required libraries. Install them using pip:
pip install sendgrid
Set Up Your API Key
- After installing the library, you need to securely store your SendGrid API key. Set it as an environment variable:
import os
os.environ['SENDGRID_API_KEY'] = 'YOUR_SENDGRID_API_KEY'
Import Required Modules
- In your Python script, import the necessary modules to begin working with the SendGrid API:
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
Create the Email Content
- Now, define the content of your email. Create a `Mail` object that includes sender, recipient, subject, and body of the email:
def create_email(sender, recipient, subject, content):
message = Mail(
from_email=sender,
to_emails=recipient,
subject=subject,
html_content=content
)
return message
Send the Email via SendGrid
- After creating the email content, use the SendGrid client to send the email:
def send_email(message):
try:
sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print(f"Email sent! Status code: {response.status_code}")
except Exception as e:
print(f"Error: {e}")
Utilize the Functions
- With the helper functions defined, you can now create and send an email:
if __name__ == "__main__":
sender = 'your-email@example.com'
recipient = 'recipient-email@example.com'
subject = 'Hello from SendGrid'
content = '<strong>This is a test email using SendGrid and Python!</strong>'
message = create_email(sender, recipient, subject, content)
send_email(message)