【发布时间】:2021-02-02 20:32:43
【问题描述】:
我尝试在我的 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
如果描述不够,请告诉我。
【问题讨论】:
-
尝试读取响应对象中的消息。您的 from_email 是否与您在发送网格仪表板中针对您的 API 进行的配置相同?我强烈建议先尝试一个 python 脚本(在发送网格的文档中提供),以确保您的发送网格配置没有问题。干杯
-
from_email 与 send grid api 中的配置邮件相同。
标签: django django-views smtp sendgrid sendgrid-templates