0

我在使用 Cloud9 Python 环境中的 sendgrid 时遇到问题。这是 SendGrid 设置选项建议的我的代码。

注意:我生成了一个实际的 API,显然“YOUR_API_KEY”已替换为适当的密钥。

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env

回声“sendgrid.env”>> .gitignore

来源 ./sendgrid.env**

点安装 sendgrid

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

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

    from_email = Email("test@example.com")
    to_email = Email("myemail@example.com")
    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())


print(response.status_code)
print(response.body)
print(response.headers)

获取此错误日志

> Traceback (most recent call last):   File "schedule.py", line 92, in
> <module>
>     response = sg.client.mail.send.post(request_body=mail.get())   File
> "/usr/local/lib/python2.7/dist-packages/python_http_client/client.py",
> line 204, in http_request
>     return Response(self._make_request(opener, request))   File "/usr/local/lib/python2.7/dist-packages/python_http_client/client.py",
> line 138, in _make_request
>     return opener.open(request)   File "/usr/lib/python2.7/urllib2.py", line 410, in open
>     response = meth(req, response)   File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
>     'http', request, response, code, msg, hdrs)   File "/usr/lib/python2.7/urllib2.py", line 448, in error
>     return self._call_chain(*args)   File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
>     result = func(*args)   File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
>     raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Unauthorized

那么这与缺少库有关吗?一些 Cloud9 限制?不应该,因为我什至没有弄乱 SMTP 选项。,

4

1 回答 1

0

So I found out that Cloud9 doesn't let you set environment variables so I had to hardcode my API KEY in the code above.

All credit goes to the author of Using Cloud9 IDE and Mailgun getting this error Net::SMTPSyntaxError in Devise::RegistrationsController#create who found out about this when dealing with a similar problem.

Thanks!

于 2017-02-11T03:19:51.777 回答