I can't figure out how to properly add a from name using the mail helper, so that receiver sees the name as well along with the "from Email"
def send_email(to: str, subject: str, template_name: str, template_data: dict, from_email: str = None):
# api key
sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
# from
from_email = Email(from_email if from_email else '[email protected]')
# to
to_email = Email(to)
# render the html to replace the dynamic data
rendered = render_to_string(f'sendgrid/{template_name}', template_data)
# content type
content = Content('text/html', rendered)
# email object
mail = Mail(from_email, subject, to_email, content)
# response from send grid
response = sg.client.mail.send.post(request_body=mail.get())
# return
return HttpResponse(response.body)
I tried
from_name = 'My Name' as well as fromname and than added that in mail = Mail(from_email, from_name, subject, to_email, content) but it didn't work.
As well as, still getting errors and the email isn't sending.
def send_email(to: str, subject: str, template_name: str, template_data: dict, from_email: str = None):
sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
data = {
"personalizations": [
{
"to": [
{
"email": "[email protected]",
"name": "John Doe"
}
],
"subject": subject
}
],
"from": {
"email": "[email protected]",
"name": "Sam Smith"
},
"reply_to": {
"email": "[email protected]",
"name": "Sam Smith"
},
"subject": "Hello, World!",
"content": [
{
"type": "text/html",
"value": render_to_string(f'sendgrid/{template_name}', template_data)
}
]
}
response = sg.client.mail.send.post(request_body=data)
# return
return HttpResponse(response.body)
Worked, thanks!
How did you guys do this? I'm having the same problem and it's nowhere in the documentation
@marchofreason See this one: https://github.com/sendgrid/sendgrid-python/blob/master/examples/helpers/mail_example.py#L150
When this link dies again, it's in this repo examples/helpers/mail_example.py, build_kitchen_sink method:
mail.from_email = Email("[email protected]", "Example User")
Most helpful comment
@marchofreason See this one: https://github.com/sendgrid/sendgrid-python/blob/master/examples/helpers/mail_example.py#L150
When this link dies again, it's in this repo examples/helpers/mail_example.py,
build_kitchen_sinkmethod:mail.from_email = Email("[email protected]", "Example User")