问题描述
我尝试在django&react项目中使用sendgrid添加发送邮件,但无法正常工作。 我在后端api视图中的代码如下:
import os
import json
from rest_framework.response import Response
from sendgrid import SendGridapiclient
from sendgrid.helpers.mail import Mail
def send_invitation(request):
if request.method == 'POST':
TO_EMAILS = [('My Email Address','My fullname'),]
FROM_EMAIL = 'my another email address'
TEMPLATE_ID = 'send-grid template id'
message = Mail(
from_email=FROM_EMAIL,to_emails=TO_EMAILS)
message.dynamic_template_data = {
'subject': 'SendGrid Development','place': 'New York City','event': 'Twilio Signal'
}
# message.add_filter('templates','enable','1')
message.template_id = TEMPLATE_ID
try:
sg = SendGridapiclient(os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
code,body,headers = response.status_code,response.body,response.headers
print(f"Response code: {code}")
print(f"Response headers: {headers}")
print(f"Response body: {body}")
print("Dynamic Messages Sent!")
return Response({'message': 'Your Invitation is sent successfully!'})
except Exception as e:
print("Error {0}".format(e))
return Response({'error': 'Your Invitation is Failed to send!'})
我已经在Django后端的.env文件中添加了SENDGRID_API_KEY,并使用pipenv安装了sendgrid。
错误是这样的; Error HTTP Error 403: Forbidden
如果描述不够,请告诉我。
解决方法
这是因为Sendgrid Web API设置中的发件人电子邮件身份验证。 我已经通过将发件人电子邮件地址添加到sendgrid Web API单一身份验证列表中来解决此问题。