I tried to add the send mail using sendgrid in my django & react project, but it is not working. My code in backend api view is like following:
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!'})
I already add the SENDGRID_API_KEY in the .env file of my django backend, and installed the sendgrid using pipenv.
The error is like this; Error HTTP Error 403: Forbidden
Please let me know if the description is not enough.
This is because of the sender email authentication in the Sendgrid Web API settings. I have solve this problem by add the sender email address into the sendgrid web api single authentication list.