简体   繁体   中英

How to send a simple HTML file from a bash script with the curl command using SendGrid's SMTP API?

I am new to bash scripting. I have spent hours searching for a solution..

#!/bin/bash

# EMAIL_TO, FROM_EMAIL, etc variables are initialized here
# ...
# ...

maildata='{"personalizations": [{"to": [{"email": "'${EMAIL_TO}'"}]}],"from": {"email": "'${FROM_EMAIL}'",
    "name": "'${FROM_NAME}'"},"subject": "'${SUBJECT}'","content": [{"type": "text/html", "value": "'${bodyHTML}'"}]}'

curl    --url https://api.sendgrid.com/v3/mail/send \
        --header 'Authorization: Bearer '$SENDGRID_API_KEY \
        --header 'Content-Type: application/json' \
        --data "'$maildata'"

The snippet above works fine whenever bodyHTML is set here, inside the script. But I want an external html file to be sent in this manner.

So, the question: How can I send, for example, "mail.html" using the above scheme? (How to set the bodyHTML variable? What command(s) to use? bodyHTML=$(cat "mail.html") # results in an error message on executing the curl line)

The issue seems to have to do with the bodyHTML (initialized either from file or within script) containing double quotation marks. As in , for example. But what to do with it...? Perhaps I need to first serialize HTML as JSON within the script..? How?

i guess bodyHTML needs proper json-encoding, try

maildata='{"personalizations": [{"to": [{"email": "'${EMAIL_TO}'"}]}],"from": {"email": "'${FROM_EMAIL}'",
"name": "'${FROM_NAME}'"},"subject": "'${SUBJECT}'","content": [{"type": "text/html", "value": '$(printf "%s" "${bodyHTML}" | php -r 'echo json_encode(stream_get_contents(STDIN));')'}]}'

... ofc they should probably ALL be properly json-encoded, not just the HTML, but the html seems like the thing most likely to break your json here..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM