петък, 13 септември 2013 г.

How to send email trough console (smtp)

This one took me a whole lot of nerves to figure it out, and in the end, it turned out I was sleeping the whole time.
The idea was to backup the database of my forum and to send it to an email. There are lots of sites suggesting ways to do it, but here's my final choice (source):

NOW="$(date +"%m%d%Y")"
/usr/bin/mysqldump -hlocalhost -uDBUSER -pDBPass DBName | gzip > /BCKlocation/BCK_NAME$NOW.sql.gz
nail -r "sender@email.com" -s "test" -a /BCKlocation/BCK_NAME$NOW.sql.gz RECIPIENT@email.com
This will attach your backup to the email and send it to the recipient email. I spent the whole night trying this, until I figured that the last option is the recipient email and nothing else. It turned out I was sending myself emails on the email I thought I'm sending them from. Quite stupid, but anyway. Note, it's better not to write your password in a file, so if you have the option to do this trough ssh, it's better to use only -p .

Now comes the funny part - how to set up the smtp. Well, I did it with a .mailrc file in which I put:

set smtp=smtp://name.of.the smtp.server:port
set ssl-verify=ignore
set from=user@domain.com
set smtp-auth=login
set smtp-auth-user=user@domain.com
set smtp-auth-password=password

This options depend on your hosting, so you need to check them there. You can also set them without the .mailrc file, just by typing
mailx -v -s "$EMAIL_SUBJECT -S smtp-use-starttls -S ... $TO_EMAIL_ADDRESS
where ... are all of the options you have in the .mailrc.

But that's all. Doing this, you can happily send yourself emails, reminders, and other goodies, just for the fun of it.
The nice part is that you don't need to use your hosting email to do that, you can use any email server supporting smtp.

If you want to use gmail, here's the smtp setting:

set smtp-use-starttls
set ssl-verify=ignore
set smtp=smtp.gmail.com:587
set smtp-auth=login
set smtp-auth-user=name@gmail.com
set smtp-auth-password=pass
set from=name@gmail.com

and the command:

$ mailx -v -s "$EMAIL_SUBJECT" $TO_EMAIL_ADDRESS
Nice, huh!
For the man of nail and all its cool options you can see here.