Using curl to send email
curl --ssl-reqd \ --url 'smtps://smtp.gmail.com:465' \ --user 'username@gmail.com:password' \ --mail-from 'username@gmail.com' \ --mail-rcpt 'john@example.com' \ --upload-file mail.txt
mail.txt file contents:
From: "User Name" <username@gmail.com>To: "John Smith" <john@example.com>Subject: This is a testHi John,I’m sending this mail with curl thru my gmail account.Bye!
Additional info:
I’m using
curl
version 7.21.6 with SSL support.You don't need to use the
--insecure
switch, which preventscurl
from performing SSL connection verification. See this online resource for further details.It’s considered a bad security practice to pass account credentials thrucommand line arguments. Use
--netrc-file
. See the documentation.You must turn on access for less secure apps or the newer App passwords.
if one wants to send mails as carbon copy or blind carbon copy:
curl --url 'smtps://smtp.gmail.com:465' --ssl-reqd \ --mail-from 'username@gmail.com' --mail-rcpt 'john@example.com' \ --mail-rcpt 'mary@gmail.com' --mail-rcpt 'eli@example.com' \ --upload-file mail.txt --user 'username@gmail.com:password' --insecure
From: "User Name" <username@gmail.com>To: "John Smith" <john@example.com>Cc: "Mary Smith" <mary@example.com>Subject: This is a testa BCC recipient eli is not specified in the data, just in the RCPT list.
Crate a simple email.conf
file like so
Username: hi@example.comPassword: OKbNGRcjiVPOP/IMAP Server: mail.example.com
And simply run sendmail.sh
, like so after making it executable (sudo chmod +x sendmail.sh
)
./sendmail.sh
Code
#!/bin/bashARGS=$(xargs echo $(perl -anle 's/^[^:]+//g && s/:\s+//g && print' email.conf) < /dev/null)set -- $ARGS "$@"; declare -A email;email['user']=$1email['pass']=$2email['smtp']=$3email['port']='587';email['rcpt']='your-email-address@gmail.com';email_content='From: "The title" <'"${email['user']}"'>To: "Gmail" <'"${email['rcpt']}"'>Subject: from '"${email['user']}"' to GmailDate: '"$(date)"'Hi Gmail,'"${email['user']}"' is sending email to you and it should work.Regards';echo "$email_content" | curl -s \ --url "smtp://${email['smtp']}:${email['port']}" \ --user "${email['user']}:${email['pass']}" \ --mail-from "${email['user']}" \ --mail-rcpt "${email['rcpt']}" \ --upload-file - # email.txtif [[ $? == 0 ]]; then echo; echo 'okay';else echo "curl error code $?"; man curl | grep "^ \+$? \+"fi