Search code examples
pythonjsonpython-requestsmailjet

Add variables in python request for mailjet


I'm just getting started with Python and can't seem to add variables into my payload for a request with mailjet.

This is the example curl script:

curl -s \
 -X POST \
 --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
 https://api.mailjet.com/v3/send \
 -H 'Content-Type: application/json' \
 -d '{
"FromEmail":"pilot@mailjet.com",
"FromName":"Mailjet Pilot",
"Subject":"Your email flight plan!",
"Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
"Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
"Recipients":[
    {
        "Email": "passenger@mailjet.com"
    }
  ]
}'

I've converted it into a Python request like so:

import requests

emailFrom = "<my_email>"

fromName = "<my_name>"

message = "test"

emailTo = "<second_email>"

headers = {
   'Content-Type': 'application/json',
}

payload = {'FromEmail':'<my_email>', 
'FromName':'<my_name>', 'Subject':'Plan', 'Text-part':'Dearz', 'Html-part':'<h1>Done</h1>', 'Recipients':[{'Email':'<second_email>'}]}

response = requests.post('https://api.mailjet.com/v3/send', headers=headers, data=payload, auth=('<PUBLIC_KEY>', '<PRIVATE_KEY>'))

Instead of having these fixed values I've tried to use variables that are at the start of the python script but I can't get the script to send an email when I use these.

How would I add the variables into the Python script?

Cheers :)


Solution

  • the problem relies upon the way. you are trying to send the data.

    so instead this:

    response = requests.post('https://api.mailjet.com/v3/send', headers=headers, data=payload, auth=('<PUBLIC_KEY>', '<PRIVATE_KEY>'))
    

    try replacing data with json:

    response = requests.post('https://api.mailjet.com/v3/send', headers=headers, json=payload, auth=('<PUBLIC_KEY>', '<PRIVATE_KEY>'))
    

    hope this helps