Search code examples
pythontwiliosendgrid

Sendgrid sample example is not working and how to email to multiple recipients?


I've create an API Key as required by the code and added it in the environments.
Below is the code I'm using and have followed the steps provided here.

# using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='from_email@example.com',
    to_emails='to@example.com',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')
try:
    sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)

It throws this error:

Traceback (most recent call last):
File "sendgrid_email.py", line 18, in <module>
    print(e.message)
AttributeError: "ForbiddenError" object has no attribute "message"

And while printing exception it shows pylint warning-

Instance of "Exception" has no "message" member

Any ideas on what I'm doing wrong or what I'm missing?

Also, to_emails is having only one email address, how do we attach multiple recipients?


Solution

  • Give API Key its full access, follow steps:

    1. Settings
    2. API Keys
    3. Edit API Key
    4. Full Access
    5. Update

    Whitelist your domain, follow steps:

    1. Settings
    2. Sender Authentication
    3. Domain Authentication
    4. Select DNS Host
    5. Enter your domain name
    6. Copy all records and put them in your Advanced DNS management console

    NOTE: When adding records, make sure not to have domain name in the host. Crop it out.

    If you do not want to authenticate domain, you can try with Single Sender Verification as well.

    Note: It might take some time for records to start functioning.


    If you're using pylinter, e.message will say

    Instance of 'Exception' has no 'message' member
    

    This is because message attribute is generated dynamically by sendgrid which pylinter is unable to access as it doesn't exists before runtime.

    So, to prevent that, at the top of your file or above print(e.message) line, you need to add either one of the below, they mean the same thing-

    # pylint: disable=no-member
    

    E1101 is code to no-member, fine more here

    # pylint: disable=E1101
    

    Now the code below should work for you. Just make sure you have SENDGRID_API_KEY set in environment. If not, you may also directly replace it with os.environ.get("SENDGRID_API_KEY") which is not a good practice though.

    # pylint: disable=E1101
    
    import os
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail
    
    message = Mail(
        from_email="from_email@your-whitelisted-domain.com",
        to_emails=("recipient1@example.com", "recipient2@example.com"),
        subject="Sending with Twilio SendGrid is Fun",
        html_content="<strong>and easy to do anywhere, even with Python</strong>")
    try:
        sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e.message)
    

    to_emails can receive tuple for multiple recipients. e.g.

    to_emails=("recipient1@example.com", "recipient2@example.com"),