### Clone SendGrid Python Repository Source: https://github.com/sendgrid/sendgrid-python/blob/main/CONTRIBUTING.md Initial setup to clone the sendgrid-python repository and navigate into the project directory. This is the first step for any contribution. ```bash git clone https://github.com/sendgrid/sendgrid-python.git cd sendgrid-python ``` -------------------------------- ### SendGrid Python Kitchen Sink Example Source: https://github.com/sendgrid/sendgrid-python/blob/main/proposals/mail-helper-refactor.md An example demonstrating various settings within the SendGrid Python library, including from email, to email, subject, plain text content, HTML content, and more. Assumes API key is in environment variables. ```python import os import sendgrid from sendgrid.helpers.mail import * msg = Mail(from_email=From('from@example.com', 'From Name'), to_email=To('to@example.com', 'To Name'), subject=Subject('Sending with Twilio SendGrid is Fun'), plain_text_content=PlainTextContent('and easy to do anywhere, even with Python'), html_content=HtmlContent('and easy to do anywhere, even with Python')) ``` -------------------------------- ### Install SendGrid Python Package Source: https://github.com/sendgrid/sendgrid-python/blob/main/README.rst Installs the SendGrid Python library using pip, the standard package installer for Python. This command ensures all necessary dependencies are fetched and installed. ```bash pip install sendgrid ``` -------------------------------- ### Create Django Project Folder and Install Dependencies (Bash) Source: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/django.md Commands to create a project directory, navigate into it, and install Django, Gunicorn, and the SendGrid Python SDK using pip. It also includes freezing dependencies into a requirements.txt file. ```bash mkdir hello-sendgrid cd hello-sendgrid pip install django gunicorn sendgrid pip freeze > requirements.txt ``` -------------------------------- ### Send Email using SendGrid Web API (Python) Source: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/aws.md Example of sending an email using the SendGrid Web API in Python. It requires the 'sendgrid' library to be installed and an environment variable 'SENDGRID_API_KEY' to be set with your SendGrid API key. This code sends a basic email with a subject and plain text content. ```python import os from sendgrid import SendGridAPIClient message = "" def send_email(): sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) from_email = "" to_emails = "" subject = "Sending with Twilio SendGrid is Fun" plain_text_content = "and easy to do via Python" html_content = "and easy to do via Python" mail = sg.client.mail.send.post(request_body=mailHelper.mail(from_email=from_email, to_emails=to_emails, subject=subject, plain_text_content=plain_text_content, html_content=html_content)) print(mail.status_code) print(mail.body) print(mail.headers) send_email() ``` -------------------------------- ### Clone SendGrid Python and Install Requirements (Bash) Source: https://github.com/sendgrid/sendgrid-python/blob/main/sendgrid/helpers/inbound/README.md Clones the sendgrid-python repository from GitHub and installs the necessary Python dependencies using pip. This is a prerequisite for running the Inbound Parse helper locally. ```bash git clone https://github.com/sendgrid/sendgrid-python.git cd sendgrid-python pip install -r requirements.txt ``` -------------------------------- ### Install SendGrid Python Module Locally for Lambda Deployment Source: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/aws.md This command installs the SendGrid Python library into the current project directory. This is necessary because AWS Lambda does not include external libraries by default, and they must be packaged with the deployment artifact. ```bash pip install sendgrid -t . ``` -------------------------------- ### Install Twilio Helper Library Source: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/sms.md Installs the necessary Twilio Python helper library using pip. This is a prerequisite for interacting with the Twilio API for sending SMS messages. ```bash pip install twilio ``` -------------------------------- ### Get Bounces using SendGrid Python API (Raw Path) Source: https://github.com/sendgrid/sendgrid-python/blob/main/README.rst This example shows an alternative method to retrieve bounce information using the SendGrid Python API by directly specifying the API path. It also requires the SENDGRID_API_KEY environment variable. The output includes the response status code, body, and headers. ```python import os from sendgrid import SendGridAPIClient sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.client._('suppression/bounces').get() print(response.status_code) print(response.body) print(response.headers) ``` -------------------------------- ### Send Email to Multiple Recipients with SendGrid Python Source: https://github.com/sendgrid/sendgrid-python/blob/main/proposals/mail-helper-refactor.md Sends an email to multiple recipients using the SendGrid Python library. The API key should be stored in an environment variable. This example shows how to define a list of recipients. ```python import os import sendgrid from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent to_emails = [ To('to0@example.com', 'To Name 0'), To('to1@example.com', 'To Name 1') ] msg = Mail(from_email=From('from@example.com', 'From Name'), to_emails=to_emails, subject=Subject('Sending with Twilio SendGrid is Fun'), plain_text_content=PlainTextContent('and easy to do anywhere, even with Python'), html_content=HtmlContent('and easy to do anywhere, even with Python')) try: response = sendgrid.send(msg, os.environ.get('SENDGRID_apikey')) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.read()) ``` -------------------------------- ### Bash: Install Specific SendGrid Version via Pip Source: https://github.com/sendgrid/sendgrid-python/blob/main/TROUBLESHOOTING.md Provides the bash command to uninstall the current SendGrid package and then install a specific version (1.6.22) using pip. This is useful for users who need to revert to or use an older version of the library that supports v2. ```bash pip uninstall sendgrid pip install sendgrid==1.6.22 ``` -------------------------------- ### Run All Tests with Docker Source: https://github.com/sendgrid/sendgrid-python/blob/main/CONTRIBUTING.md Execute all project tests using Docker. This command ensures that the code adheres to the project's testing standards before submission. ```bash make test-docker ``` -------------------------------- ### GET /ips/warmup Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves a list of all IP addresses currently in warmup mode. ```APIDOC ## GET /ips/warmup ### Description Retrieves a list of all IP addresses currently in warmup mode. ### Method GET ### Endpoint `/ips/warmup` ### Parameters (No parameters) ### Response #### Success Response (200 OK) - **Status Code**: 200 OK - **Response Body**: A JSON array where each element represents an IP address in warmup mode. Specific fields may vary. #### Response Example ```json [ "192.168.1.1", "192.168.1.2" ] ``` ``` -------------------------------- ### GET /partner_settings Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Returns a list of all partner settings that you can enable. Our partner settings allow you to integrate your Twilio SendGrid account with our partners. ```APIDOC ## Returns a list of all partner settings. ### Description This endpoint allows you to retrieve a list of all partner settings that you can enable. Our partner settings allow you to integrate your Twilio SendGrid account with our partners to increase your Twilio SendGrid experience and functionality. For more information about our partners, and how you can begin integrating with them, please visit our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/partners.html). ### Method GET ### Endpoint /partner_settings ### Parameters #### Query Parameters - **limit** (integer) - Optional - The number of results to return per page. - **offset** (integer) - Optional - The starting point for the pagination. ### Request Example ```python params = {'limit': 1, 'offset': 1} response = sg.client.partner_settings.get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ``` ### Response #### Success Response (200) - **body** (object) - The response body contains a list of partner settings. - **headers** (object) - The response headers. - **status_code** (integer) - The HTTP status code of the response. ``` -------------------------------- ### GET /stats Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves statistical data, allowing filtering by day, limit, start date, end date, and offset. ```APIDOC ## GET /stats ### Description Retrieves statistical data, allowing filtering by day, limit, start date, end date, and offset. ### Method GET ### Endpoint /stats ### Parameters #### Query Parameters - **aggregated_by** (string) - Optional - How to aggregate the statistics (e.g., 'day', 'week', 'month'). - **limit** (integer) - Optional - The number of results to return. - **start_date** (date) - Optional - The start date for the statistics query. - **end_date** (date) - Optional - The end date for the statistics query. - **offset** (integer) - Optional - The number of records to skip. ### Request Example ```python params = {'aggregated_by': 'day', 'limit': 1, 'start_date': '2016-01-01', 'end_date': '2016-04-01', 'offset': 1} response = sg.client.stats.get(query_params=params) ``` ### Response #### Success Response (200) - **body** (object) - The statistical data. - **headers** (object) - The response headers. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### GET /templates Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves all transactional templates associated with the user's account. Each user can create up to 300 templates. ```APIDOC ## GET /templates ### Description Retrieves all transactional templates associated with the user's account. Each user can create up to 300 templates. ### Method GET ### Endpoint /templates ### Response #### Success Response (200) - **status_code** (integer) - The HTTP status code of the response. - **body** (object) - The response body, containing a list of all transactional templates. - **headers** (object) - The response headers. ``` -------------------------------- ### GET /whitelabel/ips/{id} Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves a specific reverse DNS record by its ID. This allows you to fetch details for a particular reverse DNS setup. ```APIDOC ## Retrieve a reverse DNS record ### Description This endpoint allows you to retrieve a reverse DNS record. A reverse DNS record consists of a subdomain and domain that will be used to generate a reverse DNS record for a given IP. Once Twilio SendGrid has verified that the appropriate A record for the IP has been created, the appropriate reverse DNS record for the IP is generated. For more information, please see our [User Guide](https://sendgrid.com/docs/API_Reference/Web_API_v3/Whitelabel/ips.html). ### Method GET ### Endpoint /whitelabel/ips/{id} #### Path Parameters - **id** (integer) - Required - The ID of the reverse DNS record to retrieve. ### Response #### Success Response (200) - **id** (integer) - The ID of the reverse DNS record. - **domain** (string) - The domain associated with the reverse DNS record. - **subdomain** (string) - The subdomain associated with the reverse DNS record. - **ip** (string) - The IP address associated with the reverse DNS record. - **created_at** (string) - The timestamp when the record was created. - **updated_at** (string) - The timestamp when the record was last updated. #### Response Example ```json { "id": 1, "domain": "example.com", "subdomain": "email", "ip": "192.168.1.1", "created_at": "2023-01-01T12:00:00Z", "updated_at": "2023-01-01T12:00:00Z" } ``` ``` -------------------------------- ### Send Email with SendGrid Python API Client Source: https://github.com/sendgrid/sendgrid-python/blob/main/examples/helpers/README.md Demonstrates the process of sending an email using the SendGridAPIClient in Python. This involves initializing the client, preparing the email data, and calling the send method. Ensure the SendGrid API key environment variable is set. ```python sg = SendGridAPIClient() data = build_kitchen_sink() response = sg.send(data) ``` -------------------------------- ### Update Local Development Branch Source: https://github.com/sendgrid/sendgrid-python/blob/main/CONTRIBUTING.md Instructions for updating your local development branch with the latest changes from the upstream repository. Ensure your development branch is up-to-date before proceeding. ```bash git checkout git pull upstream ``` -------------------------------- ### Configure SendGrid API Key Source: https://github.com/sendgrid/sendgrid-python/blob/main/CONTRIBUTING.md Steps to set up your environment variables for API key authentication. This involves copying a sample environment file and editing it with your API key. ```bash cp .env_sample .env ``` ```bash # You do not need to do this when using Docker Compose source .env ``` -------------------------------- ### Initialize Django Project (Bash) Source: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/django.md Command to initialize a new Django project with the specified project name. ```bash django-admin startproject hello_sendgrid ``` -------------------------------- ### General v3 Web API Usage with Fluent Interface (Python) Source: https://github.com/sendgrid/sendgrid-python/blob/main/README.md This example demonstrates general usage of the SendGrid v3 Web API using the fluent interface. It requires the SENDGRID_API_KEY environment variable. The output includes the response status code, body, and headers. ```python import sendgrid import os sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY')) response = sg.client.suppression.bounces.get() print(response.status_code) print(response.body) print(response.headers) ``` -------------------------------- ### Get Single Suppression Group - Python Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md This snippet retrieves details for a specific suppression group using its ID. It sends a GET request and prints the status code, body, and headers of the response. ```python group_id = "test_url_param" response = sg.client.asm.groups._(group_id).get() print(response.status_code) print(response.body) print(response.headers) ``` -------------------------------- ### Create Attachments with SendGrid Python Source: https://github.com/sendgrid/sendgrid-python/blob/main/examples/helpers/README.md Shows how to create an attachment for an email using SendGrid's Python Attachment class. It highlights the requirement for base64 encoding the attachment content before assigning it. ```python attachment = Attachment() attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNl" "Y3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3Jhc3B1bXZ") ``` -------------------------------- ### Send Email with SendGrid Helper (Python) Source: https://github.com/sendgrid/sendgrid-python/blob/main/README.md Demonstrates how to send a simple plain text email using the SendGrid Python library and its Mail Helper class. It requires the SENDGRID_API_KEY to be set as an environment variable. The code initializes the SendGrid client, defines sender and recipient emails, subject, and content, then sends the email and prints the response status, body, and headers. ```python import sendgrid import os from sendgrid.helpers.mail import * sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY')) from_email = Email("test@example.com") to_email = To("test@example.com") subject = "Sending with SendGrid is Fun" content = Content("text/plain", "and easy to do anywhere, even with Python") mail = Mail(from_email, to_email, subject, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) ``` -------------------------------- ### Create Personalizations with SendGrid Python Source: https://github.com/sendgrid/sendgrid-python/blob/main/examples/helpers/README.md Illustrates how to use the Personalization helper class in SendGrid's Python library to customize email recipients and other aspects. This includes adding 'to' addresses and setting the 'from' address. ```python mock_personalization = Personalization() for to_addr in personalization['to_list']: mock_personalization.add_to(to_addr) mock_personalization.set_from(from_addr) mock_personalization.add_cc(cc_addr) ``` -------------------------------- ### Clone and Configure SendGrid Python Repository Source: https://github.com/sendgrid/sendgrid-python/blob/main/CONTRIBUTING.md This snippet shows how to clone the sendgrid-python repository from GitHub, navigate into the directory, and set up an 'upstream' remote pointing to the original repository. ```bash git clone https://github.com/sendgrid/sendgrid-python cd sendgrid-python git remote add upstream https://github.com/sendgrid/sendgrid-python ``` -------------------------------- ### Send Sample Inbound Email Data (Bash) Source: https://github.com/sendgrid/sendgrid-python/blob/main/sendgrid/helpers/inbound/README.md Sends sample email data to the Inbound Parse listener. Requires the sendgrid-python library to be installed. It takes a path to a sample data file as an argument. ```bash cd [path to sendgrid-python] pip install -r requirements.txt python sendgrid/helpers/inbound/send.py ./sendgrid/helpers/inbound/sample_data/default_data.txt ``` -------------------------------- ### Retrieve Google Analytics Settings using SendGrid Python Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md This snippet retrieves the current Google Analytics settings. It makes a GET request to the /tracking_settings/google_analytics endpoint and prints the response status code, body, and headers. No specific inputs are required for this GET request. ```python response = sg.client.tracking_settings.google_analytics.get() print(response.status_code) print(response.body) print(response.headers) ``` -------------------------------- ### Get Whitelabel IP by ID Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves a specific whitelabel IP address by its ID. This function makes a GET request to the /whitelabel/ips/{id} endpoint. It requires a valid IP ID as a path parameter and returns the status code, body, and headers of the response. ```python id = "test_url_param" response = sg.client.whitelabel.ips._(id).get() print(response.status_code) print(response.body) print(response.headers) ``` -------------------------------- ### GET /user/scheduled_sends Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieve all scheduled sends. ```APIDOC ## GET /user/scheduled_sends ### Description This endpoint allows you to retrieve all cancel/paused scheduled send information. ### Method GET ### Endpoint /user/scheduled_sends ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status_code** (integer) - The HTTP status code of the response. - **body** (object) - The response body containing scheduled send information. - **headers** (object) - The response headers. #### Response Example ```json { "status_code": 200, "body": {}, "headers": {} } ``` ``` -------------------------------- ### GET /whitelabel/links Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves all link brandings for your account. ```APIDOC ## GET /whitelabel/links ### Description This endpoint allows you to retrieve all link brandings. Email link brandings allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. For more information, please see our [User Guide](https://sendgrid.com/docs/API_Reference/Web_API_v3/Whitelabel/links.html). ### Method GET ### Endpoint /whitelabel/links ### Parameters #### Query Parameters - **limit** (integer) - Optional - The number of results to return. - **offset** (integer) - Optional - The starting index of the results. - **domain** (string) - Optional - Filter by domain. ### Request Example ```python params = {'limit': 1} response = sg.client.whitelabel.links.get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ``` ### Response #### Success Response (200) - **link_branding** (array) - A list of link branding objects. - **id** (string) - The ID of the link branding. - **domain** (string) - The domain used for link branding. - **subdomain** (string) - The subdomain used for link branding. - **default** (boolean) - Indicates if this is the default link branding. #### Response Example ```json { "link_branding": [ { "id": "some_id", "domain": "example.com", "subdomain": "mail", "default": true } ] } ``` ``` -------------------------------- ### Create Simple Email Object with SendGrid Python Source: https://github.com/sendgrid/sendgrid-python/blob/main/examples/helpers/README.md Demonstrates how to create a basic email object using SendGrid's Python Email and Content helper classes. This involves defining the sender, recipient, subject, and content of the email. ```python from_email = Email("test@example.com") subject = "Hello World from the SendGrid Python Library" to_email = Email("test@example.com") content = Content("text/plain", "some text here") mail = Mail(from_email, to_email, subject, content) ``` -------------------------------- ### Send Transactional Template Email using SendGrid Python Source: https://github.com/sendgrid/sendgrid-python/blob/main/proposals/mail-helper-refactor.md This snippet demonstrates sending an email using a transactional template with the SendGrid Python SDK. It sets up the email message with substitutions for dynamic content placeholders within the template. The template ID is specified, and the email is sent using an API key from an environment variable. The response details are printed, and exceptions are caught and logged. ```python import os import sendgrid from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, Attachment msg = Mail(from_email=From('from@example.com', 'From Name'), to_emails=To('to@example.com', 'To Name'), subject=Subject('Sending with Twilio SendGrid is Fun'), plain_text_content=PlainTextContent('and easy to do anywhere, even with Python'), html_content=HtmlContent('and easy to do anywhere, even with Python')) msg.substitution = [ Substitution('-name-', 'Example User'), Substitution('-city-', 'Denver') ] msg.template_id = TemplateId('13b8f94f-bcae-4ec6-b752-70d6cb59f932') try: response = sendgrid.send(msg, os.environ.get('SENDGRID_apikey')) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.read()) ``` -------------------------------- ### GET /contactdb/segments Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves all segments in your contact database. ```APIDOC ## Retrieve all segments ### Description This endpoint allows you to retrieve all of your segments. ### Method GET ### Endpoint /contactdb/segments ### Parameters ### Request Example ```python response = sg.client.contactdb.segments.get() print(response.status_code) print(response.body) print(response.headers) ``` ### Response #### Success Response (200) - **body** (object) - Response body containing a list of all segments. - **headers** (object) - Response headers. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### GET /user/settings/enforced_tls Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieve current Enforced TLS settings. ```APIDOC ## GET /user/settings/enforced_tls ### Description This endpoint allows you to retrieve your current Enforced TLS settings. ### Method GET ### Endpoint /user/settings/enforced_tls ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status_code** (integer) - The HTTP status code of the response. - **body** (object) - The response body containing Enforced TLS settings. - **headers** (object) - The response headers. #### Response Example ```json { "status_code": 200, "body": {}, "headers": {} } ``` ``` -------------------------------- ### Setup SendGrid API Key (Windows CMD) Source: https://github.com/sendgrid/sendgrid-python/blob/main/README.md Temporarily sets the SENDGRID_API_KEY environment variable for the current command-line session on Windows. This is useful for testing or short-term use. ```bash set SENDGRID_API_KEY=YOUR_API_KEY ``` -------------------------------- ### GET /whitelabel/links/subuser Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves the associated link branding for a subuser. ```APIDOC ## GET /whitelabel/links/subuser ### Description This endpoint allows you to retrieve the associated link branding for a subuser. Link whitelables can be associated with subusers from the parent account. This functionality allows subusers to send mail using their parent's link brandings. To associate a link branding, the parent account must first create a domain authentication and validate it. The parent may then associate that branded link with a subuser via the API or the Subuser Management page in the user interface. Email link brandings allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. For more information, please see our [User Guide](https://sendgrid.com/docs/API_Reference/Web_API_v3/Whitelabel/links.html). ### Method GET ### Endpoint /whitelabel/links/subuser ### Parameters #### Query Parameters - **username** (string) - Required - The username of the subuser. ### Request Example ```python params = {'username': 'test_string'} response = sg.client.whitelabel.links.subuser.get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ``` ### Response #### Success Response (200) - **id** (string) - The ID of the associated link branding. - **domain** (string) - The domain used for link branding. - **subdomain** (string) - The subdomain used for link branding. #### Response Example ```json { "id": "some_id", "domain": "example.com", "subdomain": "mail" } ``` ``` -------------------------------- ### Run Django Development Server (Bash) Source: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/django.md Commands to apply Django database migrations and start the development server. The server will be accessible at http://127.0.0.1:8000/. ```bash cd hello_sengrid python manage.py migrate python manage.py runserver ``` -------------------------------- ### GET /whitelabel/links/default Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves the default link branding for your account. ```APIDOC ## GET /whitelabel/links/default ### Description This endpoint allows you to retrieve the default link branding. Default link branding is the actual link branding to be used when sending messages. If there are multiple link brandings, the default is determined by the following order:
  • Validated link brandings marked as "default"
  • Legacy link brands (migrated from the whitelabel wizard)
  • Default Twilio SendGrid link branding (i.e. 100.ct.sendgrid.net)
Email link brandings allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. For more information, please see our [User Guide](https://sendgrid.com/docs/API_Reference/Web_API_v3/Whitelabel/links.html). ### Method GET ### Endpoint /whitelabel/links/default ### Parameters #### Query Parameters - **domain** (string) - Optional - Filter by domain. ### Request Example ```python params = {'domain': 'test_string'} response = sg.client.whitelabel.links.default.get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ``` ### Response #### Success Response (200) - **id** (string) - The ID of the default link branding. - **domain** (string) - The domain used for link branding. - **subdomain** (string) - The subdomain used for link branding. - **default** (boolean) - Indicates if this is the default link branding. #### Response Example ```json { "id": "some_id", "domain": "example.com", "subdomain": "mail", "default": true } ``` ``` -------------------------------- ### Initialize SendGrid API Client in Python Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md This snippet shows how to initialize the SendGridAPIClient using an API key stored in an environment variable. Ensure the SENDGRID_API_KEY environment variable is set with your valid SendGrid API key that has the required permissions. ```python from sendgrid import SendGridAPIClient import os sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) ``` -------------------------------- ### GET /ips/pools Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves all IP pools associated with your account. ```APIDOC ## GET /ips/pools ### Description This endpoint allows you to retrieve all of your IP pools. IP Pools allow you to group your dedicated SendGrid IP addresses together. ### Method GET ### Endpoint /ips/pools ### Parameters None ### Request Example ```json null ``` ### Response #### Success Response (200) - **pools** (array) - An array of IP pool objects. - **name** (string) - The name of the IP pool. - **ips** (array) - An array of IP addresses associated with the pool. - **created_at** (string) - Timestamp of creation. - **id** (integer) - The ID of the IP pool. #### Response Example ```json { "pools": [ { "name": "marketing", "ips": [], "created_at": "2023-10-27T10:00:00Z", "id": 12345 }, { "name": "transactional", "ips": [], "created_at": "2023-10-27T10:05:00Z", "id": 67890 } ] } ``` ``` -------------------------------- ### Send Legacy Template Email with Mail Helper Class (Python) Source: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/legacy_templates.md This snippet sends a legacy transactional email using SendGrid's Mail Helper Class in Python. It requires the SENDGRID_API_KEY environment variable and assumes a legacy template ID is configured. The code constructs an email with substitutions and a specific template ID, then posts it via the SendGrid API. ```python import sendgrid import os from sendgrid.helpers.mail import Email, Content, Substitution, Mail try: # Python 3 import urllib.request as urllib except ImportError: # Python 2 import urllib2 as urllib sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) from_email = Email("test@example.com") subject = "I'm replacing the subject tag" to_email = Email("test@example.com") content = Content("text/html", "I'm replacing the body tag") mail = Mail(from_email, subject, to_email, content) mail.personalizations[0].add_substitution(Substitution("-name-", "Example User")) mail.personalizations[0].add_substitution(Substitution("-city-", "Denver")) mail.template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932" try: response = sg.client.mail.send.post(request_body=mail.get()) except urllib.HTTPError as e: print (e.read()) exit() print(response.status_code) print(response.body) print(response.headers) ``` -------------------------------- ### Interactive Docker Shell for Testing Source: https://github.com/sendgrid/sendgrid-python/blob/main/CONTRIBUTING.md Opens an interactive bash shell within the Docker container used for testing. This allows for manual inspection or execution of commands within the test environment. ```bash command=bash make test-docker ``` -------------------------------- ### GET /ips/assigned Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves a list of only assigned IP addresses. ```APIDOC ## GET /ips/assigned ### Description Retrieve all assigned IPs **This endpoint allows you to retrieve only assigned IP addresses.** A single IP address or a range of IP addresses may be dedicated to an account in order to send email for multiple domains. The reputation of this IP is based on the aggregate performance of all the senders who use it. ### Method GET ### Endpoint `/ips/assigned` ### Parameters (No query parameters available for this endpoint) ### Request Example ```python response = sg.client.ips.assigned.get() ``` ### Response #### Success Response (200) - **ip** (string) - The IP address. - **pools** (array) - A list of IP pools the IP belongs to. - **assigned_at** (string) - Timestamp of when the IP was assigned. - **warmup_status** (boolean) - Indicates if the IP is currently in warmup. - **created_at** (string) - Timestamp of when the IP was created. - **type** (string) - The type of IP address (e.g., 'shared', 'dedicated'). - **subuser** (string) - The subuser the IP is assigned to, if any. - **domain** (string) - The domain associated with the IP, if any. - **authentication_results** (object) - Authentication details for the IP. #### Response Example ```json [ { "ip": "192.168.1.1", "pools": ["default_pool", "marketing_pool"], "assigned_at": "2016-01-01T12:00:00.000Z", "warmup_status": true, "created_at": "2015-01-01T12:00:00.000Z", "type": "dedicated", "subuser": "my_subuser", "domain": "example.com", "authentication_results": { "dkim": true, "spf": true, "dmarc": "pass" } } ] ``` ``` -------------------------------- ### Commit and Push Code Changes Source: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/aws.md These Git commands add all changes in the current directory to the staging area, commit them with a message, and then push the commit to the remote repository. This is a standard workflow for version control and deployment. ```bash $ git add . $ git commit -m 'hello-email app' $ git push ``` -------------------------------- ### GET /contactdb/segments/{segment_id} Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves a single segment by its ID. ```APIDOC ## Retrieve a segment ### Description This endpoint allows you to retrieve a single segment with the given ID. ### Method GET ### Endpoint /contactdb/segments/{segment_id} ### Parameters #### Path Parameters - **segment_id** (integer) - Required - The ID of the segment to retrieve. ### Request Example ```python params = {'segment_id': 1} segment_id = "test_url_param" response = sg.client.contactdb.segments._(segment_id).get(query_params=params) print(response.status_code) print(response.body) print(response.headers) ``` ### Response #### Success Response (200) - **body** (object) - Response body containing details of the requested segment. - **headers** (object) - Response headers. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Get User Profile Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves the user's profile information. ```APIDOC ## GET /user/profile ### Description Retrieves your user profile information. ### Method GET ### Endpoint /user/profile ### Parameters ### Request Example ```python response = sg.client.user.profile.get() print(response.status_code) print(response.body) print(response.headers) ``` ### Response #### Success Response (200) - **status_code** (integer) - The HTTP status code of the response. - **body** (object) - The response body containing user profile details. - **headers** (object) - The response headers. #### Response Example ```json { "status_code": 200, "body": {}, "headers": {} } ``` ``` -------------------------------- ### Define AWS Lambda Function and API Gateway with CodeStar Source: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/aws.md This YAML template defines a serverless AWS Lambda function and configures it to be triggered by API Gateway events (GET and POST). It specifies the handler, runtime, and imports necessary resources like the LambdaTrustRole, associating it with a CodeStar project. ```yaml AWSTemplateFormatVersion: 2010-09-09 Transform: - AWS::Serverless-2016-10-31 - AWS::CodeStar Parameters: ProjectId: Type: String Description: CodeStar projectId used to associate new resources to team members Resources: HelloEmail: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: python3.6 Role: Fn::ImportValue: !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']] Events: GetEvent: Type: Api Properties: Path: / Method: get PostEvent: Type: Api Properties: Path: / Method: post ``` -------------------------------- ### GET /geo/stats Source: https://github.com/sendgrid/sendgrid-python/blob/main/USAGE.md Retrieves email statistics segmented by country and state/province. ```APIDOC ## GET /geo/stats ### Description Retrieve email statistics by country and state/province. **This endpoint allows you to retrieve your email statistics segmented by country and state/province.** **We only store up to 7 days of email activity in our database.** By default, 500 items will be returned per request via the Advanced Stats API endpoints. Advanced Stats provide a more in-depth view of your email statistics and the actions taken by your recipients. You can segment these statistics by geographic location, device type, client type, browser, and mailbox provider. For more information about statistics, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/index.html). ### Method GET ### Endpoint `/geo/stats` ### Parameters #### Query Parameters - **end_date** (date) - Optional - The end date for the statistics. Format: YYYY-MM-DD. Defaults to today. - **country** (string) - Optional - The country to filter statistics by (e.g., 'US'). - **aggregated_by** (string) - Required - How to aggregate the statistics. Options: `day`, `week`, `month`. - **limit** (integer) - Optional - The number of results to return. Default is 500. - **offset** (integer) - Optional - The number of records to offset from the beginning of the list. - **start_date** (date) - Optional - The start date for the statistics. Format: YYYY-MM-DD. ### Request Example ```python params = {'end_date': '2016-04-01', 'country': 'US', 'aggregated_by': 'day', 'limit': 1, 'offset': 1, 'start_date': '2016-01-01'} response = sg.client.geo.stats.get(query_params=params) ``` ### Response #### Success Response (200) - **stats** (array) - An array of statistic objects, each containing data for a specific geographic location and time period. - **date** (string) - The date for this statistic entry. - **stats** (array) - An array of location-specific statistics. - **location** (string) - The country or state/province. - **metrics** (object) - The performance metrics for this location. - **sent** (integer) - Number of emails sent. - **opens** (integer) - Number of unique opens. - **unique_opens** (integer) - Number of unique opens. - **clicks** (integer) - Number of unique clicks. - **unique_clicks** (integer) - Number of unique clicks. - **spam_reports** (integer) - Number of spam reports. - **unsubscribes** (integer) - Number of unsubscribes. - **bounces** (integer) - Number of bounces. #### Response Example ```json { "stats": [ { "date": "2016-01-01", "stats": [ { "location": "US", "metrics": { "sent": 1000, "opens": 200, "unique_opens": 150, "clicks": 50, "unique_clicks": 40, "spam_reports": 1, "unsubscribes": 5, "bounces": 10 } }, { "location": "California", "metrics": { "sent": 500, "opens": 100, "unique_opens": 75, "clicks": 25, "unique_clicks": 20, "spam_reports": 0, "unsubscribes": 2, "bounces": 5 } } ] } ] } ``` ``` -------------------------------- ### Send Email using SendGrid Python API Source: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/send_a_single_email_with_multiple_reply_to_addresses.md This snippet shows how to send an email using the SendGrid Python library. It includes setting the sender, recipient, subject, HTML content, and reply-to addresses. It also demonstrates API client initialization and sending the message, with basic error handling. ```python import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, ReplyTo message = Mail( from_email='from_email@example.com', to_emails='to@example.com', subject='Sending with Twilio SendGrid is Fun', html_content='and easy to do anywhere, even with Python') message.reply_to_list = [ ReplyTo( email='reply-to-1@example.com', name="Reply To Name 1", ), ReplyTo( email='reply-to-2@example.com', name="Reply To Name 2", ) ] try: sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sendgrid_client.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e) ```