2

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

I am able to send a simple mail.

from_email = Email("useremail@gmail.com")
subject = "Welcome"
to_email = Email("toemail@gmail.com")
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.

Ajay Shewale
  • 159
  • 1
  • 2
  • 13

2 Answers2

1

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)
Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36
  • I tried above it works, but the format I saved the template, I am not getting the mail in the same format. – Ajay Shewale May 29 '18 at 09:36
  • You may have to edit the template properly. Try the template locally and them paste the HTML in Sendgrid. If you are using Outlook to check your mails then you need to have your mails in `
    ` structure for the the mail to be viewed properly.
    – Subhrajyoti Das May 29 '18 at 09:56
  • Also, can you tell me how can I add a username(use of substitution ) in my template? – Ajay Shewale May 29 '18 at 11:09
  • I have updated the code above for using substitution. The sample code has been copied from mail_example.py. You can find all the details over there. – Subhrajyoti Das May 29 '18 at 11:30
  • for substitution in personalization['substitutions']: TypeError: 'NoneType' object has no attribute '__getitem__' I added the code, encountered above error. – Ajay Shewale May 29 '18 at 11:37
  • You need to import substitution class to your file. You have to create the Substitution object with the values required and then pass the substitution variables to the loop. It is all there in `mail_example.py`. Please take a look there. It would solve most of your code related issues. – Subhrajyoti Das May 29 '18 at 11:42
  • mail.personalizations[0].add_substitution(Substitution("-name-", "Ajay")) I have added this comment and it works....thanks though... – Ajay Shewale May 29 '18 at 11:47
-2

If you are using latest sendgrid python library (~6.1.0) you need to follow the documentation from their github readme.. https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/transactional_templates.md

You need to pass the dynamic data via message.dynamic_template_data in as python dict. Also use From, To, Subject object from sendgrid mail helper class.

    message.dynamic_template_data = 
    {
        'subject': 'Testing Templates',
        'name': 'Some One',
        'city': 'Denver' 
    }

Here is the complete code snippet..

import os 
import json 
from sendgrid import SendGridAPIClient 
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='from_email@example.com',
    to_emails='to@example.com',
    html_content='<strong>and easy to do anywhere, even with Python</strong>') message.dynamic_template_data = {
    'subject': 'Testing Templates',
    'name': 'Some One',
    'city': 'Denver' } 
message.template_id = 'd-f43daeeaef504760851f727007e0b5d0' 
try:
    sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sendgrid_client.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers) 
except Exception as e:
    print(e.message)