Use SendGrid API to send emails from a Python script

import requests

def send_mail():
    # API Config
    api_url = 'https://api.sendgrid.com/v3/mail/send'

    # TO
    to_email = 'hello@codesnap.io'

    #FROM
    fom_name = 'Codesnap'
    fom_email = 'noreply@codesnap.io'
    from_subject = 'Hello World!'
    body = "What's new?"

    headers = {
        'content-type': 'application/json',
        'Authorization': 'Bearer ************' # API KEY
    }
    payload = {
        "personalizations": [
            {"to": [
                {
                    "email": to_email
                }
            ]}
        ],
        "from": {
            "email": fom_email,
            "name": fom_name
        },
        "subject": from_subject,
        "content": [{
            "type": "text/html", "value": body
        }]}

    r = requests.post(api_url, data=json.dumps(payload), headers=headers)
    if (r):
        return True
    else:
        return False

 

Top