Daniel Michaels

I forget things so I write them down.

github twitter instagram email
Curl you an email for great good
Aug 12, 2019
2 minutes read

Curl

Today I learnt that Curl can also be used to send emails. One of my projects is to manage a fleet of embedded devices that communicate information back to our servers. Email is one part of this process. And, curl is installed on these devices, greatly simplifying things.

Syntax

# gmail specific
curl --url 'smtps://smtp.gmail.com:587' --ssl-reqd \
--mail-from 'username@gmail.com' --mail-rcpt 'rcpt@email.com' \
--user 'username@gmail.com:password' --insecure \
--upload-file fileToBeUploaded.txt

Let’s break down each component:

  • --url - specifies the SMTP server address and port
  • --ssl-reqd - mandates SSL/TLS must be used
  • --mail-from - who sent the email
  • --mail-rcpt - the addressee
  • --user - credentials for the mail server
  • --insecure - a curl idiom that tells curl to ignore CA errors and continue
  • upload-file - curl cannot send a body, but will accept an RFC 5322 compliant text file as its message. Json, HTML and text data can be sent by adding a Content-Type header appropriate to the type of data being sent.

Curl documentation.

Bash script

A simple example bash script to illustrate some of the potential that this curl functionality provides us. The code can be found here.

#!/bin/bash
# A simple email script that takes a recipient and
# RFC5322 compliant text file as the message body.

echo "Curl auto-emailer"
echo "SUPPORTS GMAIL ONLY"

RCPT=$1 # 'username@example.com'
FILE=$2 # takes a filename, relative or abs path
FROM=server@gmail.com # 'me@me.com'
EMAIL=server@gmail.com:p@ssword # 'username@gmail.com:password'

if [ -z "$1" ]
  then
    echo "Missing argument 1; recipient address\
      eg username@gmail.com"
    exit
elif [ -z "$2" ]
then
  echo "Missing argument; File to be uploaded"
  exit
else
  curl --url 'smtp://smtp.gmail.com:587' --ssl-reqd \
    --mail-from $FROM --mail-rcpt $RCPT \
    --user $EMAIL --upload-file $FILE  --insecure
fi

This is for demonstration purposes only. Also, its worth mentioning that entering credentials in the commandline without the appropriate safe guards can be a security issue!

Further Reading

Check out curl wttr.in and curl rates.sx in your terminal for some of the more interactive things that can be done with this great tool. The possibilities of curl are nearly endless and its used by many of us everyday.

If you want to learn more about sending emails from the commandline then this might be worth a read. More information about sending HTML RFC5322 complaint message body files can be found here.


Tags: web curl

Back to posts