Published at

Sending Emails with BCC using SendGrid in Python

Sending Emails with BCC using SendGrid in Python

Learn how to send emails with BCC recipients using SendGrid in Python. This guide provides a clear, step-by-step implementation for intermediate learners.

Authors
  • avatar
    Name
    James Lau
    Twitter
  • Indie App Developer at Self-employed
Sharing is caring!
Table of Contents

This post demonstrates how to send emails with BCC (Blind Carbon Copy) recipients using the SendGrid API in Python. BCC is useful when you want to send a copy of an email to someone without other recipients knowing.

Prerequisites

  • A SendGrid account and API key.
  • Python 3.6 or higher.
  • The SendGrid Python library (sendgrid)

Install the SendGrid library using pip:

pip install sendgrid

Code

Here’s the code that will send emails with BCC using SendGrid:

def read_template(file_path):
    """Read the file and return the contents as a string."""
    with open(file_path, 'r', encoding='utf-8') as file:
        return file.read()

def replace_placeholders(template, replacements):
    """Replace placeholders in the template with provided values."""
    for placeholder, value in replacements.items():
        template = template.replace('{{ ' + placeholder + ' }}', value)
    return template

# BCC Email
@sync_to_async
def send_email(subject, message, recipient_list):
    import sendgrid
    from sendgrid.helpers.mail import Mail, Content, Personalization, From, To, Cc, Bcc

    sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('EMAIL_HOST_PASSWORD'))
    from_email = settings.DEFAULT_FROM_EMAIL
    to_emails = ["abcd@gmail.com"]

    personalization = Personalization()
    for bcc_addr in recipient_list:
        personalization.add_bcc(Bcc(bcc_addr))

    html_content = read_template(BASE_DIR / "templates/email/email_template.html")
    msg_html = replace_placeholders(html_content, {
        "body": message
    })

    message = Mail(
        from_email=from_email,
        to_emails=to_emails,
        subject=subject,
        html_content=msg_html
    )
    message.add_personalization(personalization)

    response = sg.send(message)
    return response

Explanation

  1. Import necessary libraries:

    • sendgrid: The main SendGrid library.
    • sendgrid.helpers.mail: A module containing helper classes to construct the email.
  2. send_email(subject, message, recipient_list) function:

    • Takes the email subject, message body, and a list of BCC recipient email addresses as input.
    • Initializes the SendGrid client with your API key (stored in an environment variable EMAIL_HOST_PASSWORD).
    • Sets the from_email address from the Django settings.
    • Creates a Personalization object to add BCC recipients.
    • Iterates through the recipient_list and adds each email address as a Bcc object to the Personalization.
    • Loads the email template and replace the placeholder “body” with the message.
    • Creates a Mail object and sets the sender, recipient, subject, and content.
    • Adds the personalization data (including BCCs) to the Mail object.
    • Sends the email using sg.send(message).
    • Returns the response from the SendGrid API.
  3. read_template(file_path) function:

    • Read the file and return the contents as a string.
  4. replace_placeholders(template, replacements) function:

    • Replace placeholders in the template with provided values.

Usage

To use this code, you would call the send_email function with the appropriate parameters:

subject = "Test Email with BCC"
message = "This is a test email sent with BCC recipients."
recipient_list = ["bcc1@example.com", "bcc2@example.com"]

response = send_email(subject, message, recipient_list)

print(response.status_code)

Replace "bcc1@example.com", and "bcc2@example.com" with the actual email addresses you want to BCC. Also, ensure your EMAIL_HOST_PASSWORD environment variable is set with your SendGrid API key.

Important Considerations

  • Error Handling: The provided code lacks explicit error handling. In a production environment, you should add try...except blocks to catch potential exceptions during the SendGrid API call.
  • Asynchronous Sending: For better performance, especially in web applications, consider sending emails asynchronously using Celery or other task queues.
  • Rate Limits: Be aware of SendGrid’s rate limits to avoid being throttled.
  • Template Management: For more complex emails, consider using SendGrid’s template engine for better maintainability.

This example provides a basic implementation of sending emails with BCC using SendGrid. Adapt it to your specific needs by adding error handling, asynchronous sending, and more sophisticated template management.

Sharing is caring!