通过Python中的SendGrid发送电子邮件

时间:2017-04-30 12:58:35

标签: python python-2.7 sendgrid

我正在尝试使用我的脚本中的上述功能通过Sendgrid发送电子邮件。

import MySQLdb
import sendgrid
import os
from sendgrid.helpers.mail import *

def sendalert(alertbody):
    sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SG.---....'#Not revealing my API key))
    from_email = Email("abcd@gmail.com")
    to_email = Email("abcd@gmail.com")
    subject = "Zomato Negative review"
    content = Content(alertbody)
    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)

调用类似sendalert(“Yo”)的内容会给我以下错误消息:

Traceback (most recent call last):
File "zomato.py", line 91, in <module>
readreview(input_text)
File "zomato.py", line 64, in readreview
sendalert(review_text) # sending the email alert
File "zomato.py", line 16, in sendalert
response = sg.client.mail.send.post(request_body=mail.get())
File "/Library/Python/2.7/site-packages/python_http_client-2.2.1-     py2.7.egg/python_http_client/client.py", line 204, in http_request
return Response(self._make_request(opener, request))
File "/Library/Python/2.7/site-packages/python_http_client-2.2.1-py2.7.egg/python_http_client/client.py", line 138, in _make_request
return opener.open(request)
File  "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)

urllib2.HTTPError:HTTP错误401:未经授权

如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

你能试试吗

import os
import sendgrid


def sendalert(alertbody):
    sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SG.---....'#Not     revealing my API key))

    message = sendgrid.Mail()
    message.add_to("abcd@gmail.com")
    message.set_from("abcd@gmail.com")
    message.set_subject("Zomato Negative review")
    message.set_text(alertbody)

    sg.send(message)

你仍然可以按照自己的方式创建电子邮件,但是发送它的方式肯定是错误的SendGrid documentation

顺便说一句,错误表明你传递的密钥在某种程度上是错误的。

答案 1 :(得分:0)

我遇到了类似的问题,请确保使用admin SendGrid帐户或具有Mail 发送权限的Teammates帐户生成API密钥。