首页 > 解决方案 > SendGrid 邮件发送在我的 django rest-api 视图中不起作用

问题描述

我尝试在我的 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

如果描述不够,请告诉我。

标签: djangodjango-viewssmtpsendgridsendgrid-templates

解决方案


这是因为 Sendgrid Web API 设置中的发件人电子邮件身份验证。我通过将发件人电子邮件地址添加到 sendgrid web api 单一身份验证列表中解决了这个问题。


推荐阅读