Reputation: 11
i want to write an application that send emails to users while using sendgrid,i have gone to sendgrid and followed all the instructions including installing sendgrid and setting the environmental variable.
i have tried putting the environmental variable in the path but still shows the error
i have also tried putting it in the code but still it fails with the same error
this is my code of send-mail.py:
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
message = Mail(
from_email='[email protected]',
to_emails='[email protected]',
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('SG.97-
h52MJSXK4C7_FIl5yzw.q3GsOa4P_AO1pKvUcOzQg6XzuRXEY3mzD-Ci5eN2I2E'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e
)
i have created a folder called Mail and created a file inside named send_mail.py
i expect to send an email but it throws a HTTP Error 401: Unauthorized
Upvotes: 0
Views: 5822
Reputation: 519
You are attempting to get an environment variable whose name is the API key. This is most likely returning None which is making your authentication fail. You may also want to consider regenerating your API key sense you have now disclosed it to the internet.
Try replacing SendGridAPIClient(os.environ.get('SG.97-
h52MJSXK4C7_FIl5yzw.q3GsOa4P_AO1pKvUcOzQg6XzuRXEY3mzD-Ci5eN2I2E'))
with SendGridAPIClient('SG.97-
h52MJSXK4C7_FIl5yzw.q3GsOa4P_AO1pKvUcOzQg6XzuRXEY3mzD-Ci5eN2I2E')
.
Upvotes: 3