Search code examples
pythonemailsparkpost

Unable to send mail via SparkPost saved templates using python client


I'm trying to send mail using SparkPost SMTP API

response = spark.transmissions.send(
    recipients=['[email protected]'],
    text='hi',
    content={
        "template_id": "my-first-email",
        "from":{"name": "someone", "email": "[email protected]"},
    },
    subject='Subject Line',
    substitution_data={
       "name": "Your Name"
    }
)

As per documentation it should work but I am getting the following error.

Traceback (most recent call last):
  File "sendmail.py", line 69, in <module>
    sparkpost()
  File "sendmail.py", line 65, in sparkpost
    "name": "Rupesh"
  File "/usr/local/lib/python2.7/dist-packages/sparkpost/transmissions.py", line 254, in send
    results = self.request('POST', self.uri, data=json.dumps(payload))
  File "/usr/local/lib/python2.7/dist-packages/sparkpost/base.py", line 41, in request
    **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/sparkpost/base.py", line 16, in request
    raise SparkPostAPIException(response)
sparkpost.exceptions.SparkPostAPIException: Call to https://api.sparkpost.com/api/v1/transmissions returned 422, errors:

        required field is missing Code: 1400 Description: content.from is a required field

PS- Everything works fine with Postman examples provided by Sparkpost.


Solution

  • When you use a stored template (by setting template_id), you do not need to set content or subject since they are embedded in the template. You can make your call like this:

    response = sp.transmissions.send(
        recipients=['[email protected]'],
        template='my-template-id'
    )
    

    Also, the python-sparkpost API client provides a layer on top of the SparkPost API so the parameters for SparkPost.transmissions.send() are not a 1:1 match for the API. The full documentation for python-sparkpost is available here.

    Here's a relevant sample from the Python client too.