Archive

Posts Tagged ‘email’

Sending mail from command line

May 20, 2010 Leave a comment

Recently I wanted to add mail sending functionality to one of my scripts. This script runs on my desktop computer, so no fancy company mail servers/fixed IP/DNS records for me. When I googled it up I saw many different methods in varying complexity. My need was the simplest you can think of- just to send email. I didn’t care if it’s always from the same address. My solution was to use Ubuntu’s default exim4 mail server, with Gmail. Exim authenticates with your gmail user/password and the mail is always sent from the same address (user@gmail.com). This is heavily based on this, although a little different.

First I had to install exim4-config, so:
# sudo apt-get install exim4-config

Then I needed to configure exim to work with Gmail:
# sudo dpkg-reconfigure exim4-config

My selections:

  • General type of mail configuration: mail sent by smarthost; no local mail
  • System mail name: localhost
  • IP-address to listen: 127.0.0.1
  • Other destinations for which mail is accepted: (leave blank)
  • Visible domain name for local users: localhost
  • IP address or host name of the outgoing smarthost: smtp.gmail.com::587
  • Keep number of DNS-queries minimal: no
  • Split configuration into small files: no
  • Root and postmaster mail recipient: (leave blank)

Edit /etc/exim4/passwd.client (you can use gedit if you’re not comfortable with vi):
# sudo vi /etc/exim4/passwd.client

Add those lines (replace “user” and “password” with your own):

gmail-smtp.l.google.com:user@gmail.com:password
*.google.com:user@gmail.com:password
smtp.gmail.com:user@gmail.com:password

Finally update (refresh) exim configuration:
# sudo update-exim4.conf

That’s about it. To send the contents of /etc/motd as mail (just example):
# cat /etc/motd | mail -a “FROM: user@gmail.com” -a “BCC: somemail@somedomain.com” -s “This is the subject” recipient@somedomain.com

The “BCC:” is optional of course. If you don’t specify “FROM:” the default is the current user.

If you don’t have the “mail” command then just install mailutils:
# sudo apt-get install mailutils

Happy mailing!

Advertisements