How to Specify Sender's Name & Reply-to in SendGrid (v3 API Python)


SendGrid allows you to programmatically send emails. It is one of the email providers recommended by Google, especially since they started discouraging using the Email API in Google App Engine (GAE).

In SendGrid v2 API for Python, sending email was kind of straightforward and intuitive. The standard code was


	import sendgrid
	sg = sendgrid.SendGridClient(SENDGRID_KEY)

	emailMessage = sendgrid.Mail(to=to_email, subject=subject, html=html_message, 
			from_email=from_email, from_name=from_name, reply_to=reply_to_email)
	status, msg = sg.send(emailMessage)
	print(status) 

As can be seen above, you could specify both the email address and name of the recipient. You could also specify a reply_to email address in the body. Both of these are important in situations where you are sending emails on behalf of a third party, for example, if you are running an ecommerce platform (like Shopify) where you host stores for shop owners and you have to send emails on behalf of the shop owners to their customers (a person purchases a product from Shop A and you have to send a confirmation email on behalf of Shop A to the person; the person has to be able to respond to Shop A). It would be tempting to specify the email address of Shop A as the from_email in the above code but SendGrid discourages that. Instead, they advice you to send the email from your own address (because it would be from your domain which you have verified with SendGrid) but you can use the name of Shop A as the from_name and then you specify Shop A's email as the reply_to. This way, when a user clicks on the 'Reply to' command in their email client, it populates Shop A's email address.

Unfortunately, the above code will not work in v3 API and it is difficult to locate examples in SendGrid's documentation that show the above scenario (the examples exist but they appear buried in their documentation on GitHub and not on the snippets returned by Google search). To get the above scenario in v3, use the code below


	from sendgrid import SendGridAPIClient
	from sendgrid.helpers.mail import Mail, From, ReplyTo
	sg = SendGridAPIClient(SENDGRID_KEY)
	
	emailMessage = Mail(to_emails=to_email, subject=subject, html_content=html_message, 
			from_email=From(from_email, from_name)) 
	emailMessage.reply_to = ReplyTo(reply_to_email, reply_to_name)

	try:
		response = sg.send(emailMessage)
		print(f"email response code: {response.status_code}")
		print(f"email response body: {response.body}")
		print(response.headers)

	except Exception as e:
		print("An error sending email")
		print(e)
		
Comments
Sort by
  • East
    East - 2023-03-09 13:33:39.443905
    This has been really helpful. Many thanks.