pythondjangosendgridsendgrid-api-v3

Error when sending email through Sendgrid API


On my production server I am getting the error below

"init() got an unexpected keyword argument 'apikey'"

The same code on the development server is working.

My production server is running gunicorn and I have added the environment variable SENDGRID_API_KEY to the gunicorn.service file. I have restarted gunicorn and nginx. I can see that the environment variable is loaded.

The method I am calling to send the email is below:

def sendtestemail(to):
    sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
    from_email = Email("<myemail>@<mydomain>.com")
    to_email = Email(to)
    subject = "Sending with SendGrid is Fun"
    content = Content("text/plain", "and easy to do anywhere, even with Python")
    mail = Mail(from_email, subject, to_email, content)
    response = sg.client.mail.send.post(request_body=mail.get())
    return [response.status_code, response.body, response.headers]

Solution

  • The issue originates from a breaking change introduced in sendgrid 6.0. The keyword argument for apikey has been removed and replaced with a positional argument.

    To resolve with your example, remove apikey= from your arguments, and just pass the api_key as a positional argument.

        sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    

    This can be a bit confusing when looking back at all previous examples as well as GitHub documentation, but this example on the official documentation does get it right.


    Note: I do see that at the time of asking your question, you were indeed following the documentation I linked above correctly. There are a few issues opened where the documentation remained inaccurate for quite some time, but was resolved back in may.