sendgrid-python

repository·main·Indexed 23 days ago

https://github.com/sendgrid/sendgrid-python

A Python library providing a wrapper around the SendGrid Web API v3. It allows developers to send emails, manage suppression lists, and handle inbound parse webhooks. The library includes helper classes for constructing Mail, Content, and Personalization objects, supports dynamic Handlebars templates, and provides both fluent and non-fluent interfaces for API calls.

Tokens
47.4K
Snippets
159
Records
195
Agent score
81%

What's inside sendgrid-python

  1. Common Use Cases for SendGrid Python

    main

    The use_cases/ directory contains specific implementation examples for common email patterns. Key patterns include:

    • Recipient Management: Sending to single recipients, multiple recipients, or using personalizations for bulk sending.
    • Content Types: Sending HTML-only content, using Transactional Templates, or attaching files.
    • Advanced Patterns: Asynchronous mail sending and using the 'Kitchen Sink' example which demonstrates all available settings.
  2. Deployment and Integration How-Tos

    main

    The library provides guides for integrating SendGrid into various web frameworks and cloud platforms:

    • Web Frameworks: Creating Django apps (deployed on Heroku) and Flask apps (deployed on Heroku) to send email.
    • Cloud Platforms: Deploying a 'Hello Email' app on AWS.
    • Infrastructure & Security: Setting up Domain Authentication and viewing Email Statistics.
  3. Use the Mail helper to build Mail objects

    main

    The sendgrid.helpers.mail module provides a high-level helper to quickly and easily construct Mail objects required for sending emails through the Twilio SendGrid API. This abstraction simplifies the process of defining senders, recipients, and content compared to manually constructing the underlying JSON structure.

    To use this helper, ensure you have completed the standard installation steps for the sendgrid-python library.

  4. Manage Tracking Settings

    main

    Tracking settings allow you to monitor recipient interactions such as email opens, link clicks, and Google Analytics data. You can retrieve all available tracking settings or manage specific ones like click tracking, open tracking, and Google Analytics.

    Retrieve all tracking settings: GET /tracking_settings

    params = {'limit': 1, 'offset': 1}
    response = sg.client.tracking_settings.get(query_params=params)
    print(response.status_code)
    print(response.body)
    print(response.headers)
  5. Manage IP addresses and IP pools

    main

    The IP management API allows you to manage assigned/unassigned IPs and group them into IP Pools to maintain separate reputations for different traffic types (e.g., transactional vs. marketing).

    IP Management Tasks:

    • List all IPs: sg.client.ips.get(query_params=...) (includes assigned and unassigned).
    • List assigned IPs: sg.client.ips.assigned.get().
    • Create an IP pool: sg.client.ips.pools.post(request_body=...) (Max 10 pools per user).
    • List all IP pools: sg.client.ips.pools.get().
    • Update an IP pool name: sg.client.ips.pools._(pool_name).put(request_body=...).
    • List IPs in a pool: sg.client.ips.pools._(pool_name).get().
    • Delete an IP pool: sg.client.ips.pools._(pool_name).delete().
    • Add an IP to a pool: sg.client.ips.pools._(pool_name).ips.post(request_body=...).
    • Remove an IP from a pool: sg.client.ips.pools._(pool_name).ips._(ip).delete().
  6. Configure Global Mail Settings

    main

    Global settings apply to the entire message and are not tied to a specific personalization. You can configure the sender, reply-to address, content, attachments, and template IDs globally.

    Key global attributes include:

    • from_email: The sender address.
    • reply_to: The address used for replies.
    • content: The body of the email (can be multiple types like text/plain and text/html).
    • attachment: Files attached to the email.
    • template_id: The ID of a dynamic template to use.
    • category: A category assigned to the message.
    • custom_arg: Custom arguments for tracking or metadata.
    • batch_id: A unique ID for batching messages.
    from sendgrid.helpers.mail import Mail, From, To, Content, MimeType, Attachment, FileContent, FileName, FileType, Disposition, ContentId, TemplateId
    
    message = Mail()
    message.from_email = From('help@twilio.com', 'Twilio SendGrid')
    message.reply_to = ReplyTo('help_reply@twilio.com', 'Twilio SendGrid Reply')
    message.content = [Content(MimeType.text, 'Plain text content'), Content(MimeType.html, '<strong>HTML content</strong>')]
    message.template_id = TemplateId('13b8f94f-bcae-4ec6-b752-70d6cb59f932')
  7. AMP-HTML Email Content Requirements

    main

    When sending AMP-HTML emails, adhere to the following content structure for best results:

    1. AMP HTML Content: Required. Must be valid AMP for Email code.
    2. Fallback Content: You must include at least one of the following:
      • HTML Content: Standard HTML for fallback in older clients.
      • Plain Text Content: Recommended for deliverability.

    Best Practice: Provide both HTML and Plain Text content to ensure compatibility with all email clients and to handle content display after the 30-day AMP support period.

  8. Configure MailSettings and TrackingSettings

    main

    You can fine-tune how SendGrid handles your email using MailSettings and TrackingSettings.

    MailSettings

    Used for controlling delivery behavior, such as:

    • sandbox_mode: Test sending without actually delivering.
    • spam_check: Enable/disable spam checking and set thresholds.
    • footer_settings: Customize the footer text and HTML.
    • bypass_bounce_management, bypass_list_management, etc.: Control how SendGrid manages bounces and unsubscribes.
    • bcc_settings: Configure automatic BCC.

    TrackingSettings

    Used for monitoring engagement:

    • click_tracking: Track clicks in links.
    • open_tracking: Track email opens.
    • subscription_tracking: Manage unsubscribe links and text.
    • ganalytics: Enable Google Analytics tracking with UTM parameters (UtmSource, UtmMedium, UtmTerm, UtmContent, UtmCampaign).
    from sendgrid.helpers.mail import MailSettings, TrackingSettings, SandBoxMode, ClickTracking, OpenTracking, Ganalytics
    
    mail_settings = MailSettings()
    mail_settings.sandbox_mode = SandBoxMode(True)
    
    tracking_settings = TrackingSettings()
    tracking_settings.click_tracking = ClickTracking(True, False)
    tracking_settings.ganalytics = Ganalytics(True, UtmSource("utm_source"), UtmMedium("utm_medium"), UtmTerm("utm_term"), UtmContent("utm_content"), UtmCampaign("utm_campaign"))
    
    message.mail_settings = mail_settings
    message.tracking_settings = tracking_settings
  9. Define Personalizations in a Mail object

    main

    Personalizations allow you to send customized content to different recipients within a single API call. You can define unique To, Cc, Bcc, Subject, Header, Substitution, CustomArg, and SendAt values for each personalization by passing a p (personalization index) argument to the helper classes.

    When setting these values, you can assign a single object or a list of objects to the corresponding attribute on the Mail instance. The p parameter determines which personalization group the setting belongs to.

  10. Use the Stats helper to build email statistics objects

    main

    The Stats helper is designed to simplify the creation of Stats objects, which are used to format email statistics for transmission to a database or other storage systems.

    To use this helper, ensure you have your SENDGRID_API_KEY configured in your environment variables. For complete implementation details, refer to the official SendGrid API documentation for the Stats endpoint.