Search code examples
pythonsendgridsendgrid-templates

SENDGRID: send an email using transactional template using python?


I am trying to send an email using the transactional template, sendgrid.

I am able to send a simple mail.

from_email = Email("[email protected]")
subject = "Welcome"
to_email = Email("[email protected]")
content = ("text/plane","Text here")
mail = Mail(from_email, subject, to_email, content)

I have created a template which I want to use to send emails. How can I do this?

I was using template_id parameter and passing through the Mail(), but it's not working.

template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932"

I checked the class Mail(object) which has self._template_id parameter. The field in Mail() class is as follwos:

if self.template_id is not None:
    mail["template_id"] = self.template_id

What am I missing here?

I just want to send a mail using the template I have created.


Solution

  • You cannot send it as a parameter. You can set it as a normal setter though in the following way.

    mail.template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932"
    

    You can find the same implementation in the mail_example.py file in the sendgrid package

    Using Substitution/Personalization:

    #add this code to your method where you have initialized Mail() object
    personalization = get_mock_personalization_dict()
    mail.add_personalization(build_personalization(personalization))
    mail.add_personalization(build_personalization(personalization))
    
    #Example of a Personalization Object
    def get_mock_personalization_dict():
        mock_pers = dict()
        mock_pers['substitutions'] = [Substitution("%name%", "Example User"),
                                  Substitution("%city%", "Denver")]
    
    #Updates the mail object with personalization variable
    def build_personalization(personalization):
        for substitution in personalization['substitutions']:
             personalization.add_substitution(substitution)