通过WebApi Python选项使用Cloud9发送Sendgrid

时间:2017-02-11 02:27:20

标签: python sendgrid cloud9-ide sendgrid-api-v3

我在Cloud9 Python环境中使用sendgrid时遇到问题。这是我的代码,如SendGrid安装选项所示。

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

echo“export SENDGRID_API_KEY ='YOUR_API_KEY'”> sendgrid.env

echo“sendgrid.env”>>的.gitignore

source ./sendgrid.env **

pip install 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选项。,

1 个答案:

答案 0 :(得分:0)

所以我发现Cloud9不允许你设置环境变量,因此我不得不在上面的代码中对我的API KEY进行硬编码。

所有归功于Using Cloud9 IDE and Mailgun getting this error Net::SMTPSyntaxError in Devise::RegistrationsController#create的作者,他在处理类似问题时发现了这一点。

谢谢!