Sending emails from the Raspberry Pi

Email from the Raspberry Pi
There are many cases when it can be very useful to be able to send emails from the Raspberry Pi to arbitrary recipients. This is not the same as having a real MTA running on the Pi (like Sendmail, Postfix, Exim, QMail, etc.), which can also receive and store emails. In the following we are only going to cover the possibility of sending emails, not receiving. In most cases this is enough, as people tend to use GMail, Yahoo! Mail and other major email service providers and they store their emails on the servers of these providers. Still, sending out emails from the Raspberry Pi can come in handy in many situations. For example, you could have some sensors connected to the GPIO pins of the Pi and you could program the Pi to send you an email when the temperature in the room rises above or drops below certain threshold values, when a gas sensor registers unwanted gas leaks or when the measured voltage of a monitored battery becomes too low. You could also have your Pi send you daily or weekly emails with summarized system data. Or maybe you could connect a webcam to the Raspberry Pi and set up some motion detection software, which would send you an email as soon as it detects motion in a given area of your house. Maybe we don’t even need to go this far. Maybe you are hosting a WordPress website on your Raspberry Pi and you would like to provide your readers with the possibility to subscribe to the posts. This all means that the Pi needs to be able to send out emails, which, unfortunately, can be complicated to accomplish.
In order to achieve this we are going to install a piece of software called SSMTP, which is a simple tool for sending emails. We are also going to configure PHP in a way which is going to make it possible to send emails from inside PHP scripts. This way it’s going to be easy for web applications (like WordPress plugins) to send mails to chosen recipients.
Many email servers today have very strict rules for accepting emails. For example if the email is not coming from a machine with a static IP address, they might classify the email as SPAM. We don’t want that to happen with the emails sent from the Raspberry Pi, so we are going to send the emails to a Goggle server, which will send them forward to the real recipients. In order to be able to accomplish this, you must have a GMail account.

Installing and configuring SSMTP

1. Make sure your repositories are up-to-date:

apt-get update

2. Install SSMTP and mail utilitites:

apt-get install ssmtp

apt-get install mailutils

3. Edit the SSMTP configuration file:

nano /etc/ssmtp/ssmtp.conf

a) Mandatory lines:

root=postmaster
mailhub=smtp.gmail.com:587
hostname=raspberrypi
AuthUser=YourGMailUserName@gmail.com
AuthPass=YourGMailPassword
UseSTARTTLS=YES

Be sure to specify the correct GMail user name and password here, otherwise you will get authentication errors.

If the host name of your Raspberry Pi is different from “raspberrypi”, specify your actual host name here instead.

b) Optional lines:

rewriteDomain=your.domain

Specify this if you would like the outgoing emails to appear to be sent from your.domain (instead of from gmail.com).

FromLineOverride=YES

Specify this if you would like SSMTP to leave the From field of the emails untouched. Otherwise it will overwrite the from field with the name of the Linux user which sends the email. The overwriting name is taken from the 5th value in the line that corresponds to the sending user, from the /etc/passwd file. If you plan to send emails from a website (for example from a WordPress plugin) and wish to have nice sender names like “John Doe”, I recommend commenting this line (which is equal to setting the value to NO), otherwise your website will only be able to send emails with less nice sender names, like johndoe@your.domain. In other words, you probably want SSMTP to overwrite the sender field with a nice name taken from the /etc/passwd file.

4. Edit the SSMTP aliases file:

nano /etc/ssmtp/revaliases

This file contains data about the email accounts for existing Linux users in the format local_account:outgoing_address:mailhub[:port]

You should create one line for all the users in your system from which you plan to be able to send emails. For example:

root:root@your.domain:smtp.gmail.com:587
www-data:yourwebpagesname@your.domain:smtp.gmail.com:587

In case you wish to send out emails from a WordPress plugin, you must make sure that you have a line for the user www-data, which is the user under which WordPress runs.

5. Set the permissions of the SSMTP configuration file:

chmod 774 /etc/ssmtp/ssmtp.conf

The  permissions of the file /etc/ssmtp/ssmtp.conf determine  who will be able to send emails from the Raspberry Pi. By default this file is owned by the user root and the group of the file is also root. So if you want other users, like www-data to be able to send emails (which you definitely want if you’re using a WordPress plugin for example to send out emails), then you need to give read rights to the users who are not the owner of the file and not in the group of the file. The above permissions (774) mean that the owner (root) will be able to read/write/execute the file (7), the other users in the root group will be able to do the same (7) and the users which are not in the group will only have the right to read the file (4). For more details type chmod –help.

If you prefer not to allow every user on your system to send emails, then add the www-data user (or the user who you would like to grant permission for sending emails) to the root group and only give the rights to the users in this group:

sudo usermod -a -G root www-data
chmod 770 /etc/ssmtp/ssmtp.conf

Be careful though. Adding the www-data user to the root group might sometimes not be very safe, as it will allow your website to do many things on your system.

6. Nice sender names:

If you would like your website (WordPress for example) to be able to send emails which appear to be sent from a person with a nice name like “John Doe” or “Your super web site” instead of from a simple  sender name like you@your.domain, then you need to make sure that in the /etc/ssmtp/ssmtp.conf file the FromLineOverride line is commented (#) or set to NO and you need to give a nice name to the www-data user. You can do this by editing the passwords file:
nano /etc/passwd

Find the line corresponding to www-data and set the fifth value in it to a nice name like “Your super website”.

Sending emails from command line

Once you’re done with the above setup and configuration process, you can send emails very easily from command line, which is great because you can also put the sending into Bash scripts, which can be called by other applications running on your Pi. A simple example looks like this:

echo “Test text” | mail -s “Test Mail” targetperson@example.com

The text “Test text” is sent to the email address targetperson@example.com (you may also specify multiple addresses separated by spaces) with the subject “Test Mail”. For more options type mail –help.

Sending emails from PHP scripts

If you would also like to be able to send out emails from PHP scrips (which is the case if you plan to send emails from your website, perhaps from a WordPress plugin like Subscribe2), then you need to configure PHP to find the mail sending application.

1. Edit your PHP configuration file:

nano etc/php5/apache2/php.ini

Find (F6) the line which contains sendmail_path and set it to the appropriate value:

sendmail_path = /usr/sbin/sendmail -t -i

2. To test if PHP is indeed able to send out emails, create a file named mailtest.php and put the following code into it:

<?php
$to = “targetperson@example.com”;
$subject = “PHP Test mail”;
$message = “This is a test email”;
$from = “you@your.domain”;
$headers = “From:” . $from;
mail($to,$subject,$message,$headers);
echo “Mail Sent.”;
?>

Test by calling your script from command line:

PHP mailtest.php


Troubleshooting

If you fail to configure things properly, you might run into some errors when trying to send emails. Some common error messages are the following:

1. Authentication failure:

Authorization failed (535 5.7.1 http://support.google.com/mail/bin/answ … swer=14257 a1sm11494547eep.2 – gsmtp

The most probable cause of this is that you have specified a wrong username or password for your GMail account in the /etc/ssmtp/ssmtp.conf file. Double check the values of the AuthUser and AuthPass fields.

2. Connection lost in the middle of processing:

send-mail: Connection lost in middle of processing

Chances are you specified the wrong port for the Google smtp somewhere in /etc/ssmtp/ssmtp.conf or in /etc/ssmtp/revaliases.

3. Your website (for example your WordPress plugin) gives an error message when you try to send an email from it or it appears to have sent the email but it never arrives to the recipient(s):

Check the last lines of your logs. There should be some relevant error messages in there:

tail /var/log/mail.log

tail /var/log/syslog

One of the most common problems is that you have not given the www-data user rights to read the /etc/ssmtp/ssmtp.conf file. Check the permissions of the file:

ls -l /etc/ssmtp/ssmtp.conf

and if something is not right, set the permissions, for example:

chmod 774 /etc/ssmtp/ssmtp.conf



Comments

Sending emails from the Raspberry Pi — 67 Comments

    • Andrew > You can send emails through php scripts, I had this function installed on my Raspberry Pi, but it strangely disappeared …

    • Hello,
      In case of SMTP server which doesn´t require authentication all you need to do is set up following field in /etc/ssmtp/ssmtp.conf

      mailhub=smtp.yourserver.com

      hope it helps

    • I’m happy I could help :) That’s the reason I started this site, to share knowledge. Even one happy reader means it was worth writing the article :) And the fact that my guide helped you set it up in 5 min is amazing. It took 3 days for me to figure it out back then 😛

      • thanx great and easy instructions, set it up in 6 min.
        next project is enhancing secu on the router, as the raspi now is the only weakness in terms of security…
        afterwards i will write a nice little droid transmitting the gathered info to owncloud login page so that data stored on owncloud will be available from outside the lan…

        Thank you very much for yur 3days live time. Hopefully it was not the whole 3 days from 00 to 24 😉

  1. Pingback: Configurar comando mail de raspbian con cuenta de Google Gmail | Void Technology

  2. Pingback: frakturmedia » Blog Archive » Setting up Raspberry Pi’s for scraping

  3. I have a really stupid problem….the command line “mail” command is not found. I installed wheezy some time ago (~ 6 months). Just trying to get e-mail to work for the first time. The ssmtp package installed okay. Used the find command to try to find “mail” – came up empty. What package am I missing ?

    Here’s my PATH:
    pi@raspberrypi ~ $ echo $PATH
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games

    Thanks !

  4. Thanks for the great write up. I thing to note is if you have 2-step verification enabled for your Gmail account you need to generate and use an application specific password to make this work.

  5. Thanks a lot for clear information. I reccomend in file /etc/ssmtp/ssmtp.conf

    change line:
    root=postmaster change
    to
    root=YourGMailUserName@gmail.com

  6. Didn’t work for me. I also had to install mailutils with:
    sudo apt-get install mailutils

    but now I get
    echo “pi test mail”| mail -s “Test mail from pi” me@domain.com
    *** glibc detected *** /usr/sbin/sendmail: free(): invalid pointer: 0x00a41513 ***
    mail: cannot send message: Process exited on signal
    mail: Cannot open file /home/pi/dead.letter: No such file or directory

    • hi, i have got the same issues as you . where u able to resolve it? if yes , how?
      Thanks for your reply!

      • I have the same problem as well.
        Since you wrote your comment 3 months ago I hope you have managed to solve it by now! If so could you tell me how you managed it please. Many thanks

  7. Works fine. Except with mailtest.php it has a little flaw for me.

    Instead using the value of $fromto (noreply@webite.ext) it uses my real e-mail …

  8. it seems Fromto: is overrides when using gmail server. I changed it to my mail-relay server of my local-isp and the fromto: works as it should be.

  9. I did this on a clean install and even after doing update and upgrade, there was no mail program. I had to do the apt-get install mailutils. On another machine, I had installed LAMP before doing ssmtp and it worked as described above. I suspect one of those might have installed mailutils (probably mysql).

  10. Many thanks for this very helpful note. Your instructions worked “out of the box”.
    The communal router here won’t allow addressing by name and frequently reboots, assigning new IP addresses. As the Pi is headless, this causes trouble. Using ifconfig | SSMTP in a boot script gets round the problem easily.
    Thanks again.

  11. i get this error:

    PHP Parse error: syntax error, unexpected ‘@’ in /var/www/mail.php on line 2

    What i have to do?! The php file is like this:

  12. plse, i’m a new user of the rasberry pi and i need serious help.
    i want to use the raspi to send students examination results through e-mail and sms.
    it’s kind of a project, someone plse help me..!!!!!

  13. Hi there,

    I am working on a Java library for home automation for the Pi, and am using the JavaMail Library/API to send notifications, and received commands via email. It is pretty neat, and easy to use !!!

  14. Pingback: RPi 101 – Introdução ao RaspberryPi ! | HackerSchool do IST

  15. Thanks for the guide. I did need to make a change to get it to work.
    Looks like the settings are specific for GMail.
    To work with TLS add this line:
    UseTLS=YES

    And remove the UseSTARTTLS=YES

  16. In fact, you do not need to install anything.
    Exim is already installed on Raspbian, but it is configured by default to stay local.
    You just have to change the file “update-exim4.conf.conf”
    “dc_eximconfig_configtype=’satellite’
    etc.”

  17. Hi guys and gals,

    Having an issue editing my ssmtp.conf file. When I try and save my .conf file it says there is no such file or directory. I’ve tried in both regular user and super user as well. Any ideas? Very new to email set up.

    Thanks in advance!

    • Hi Jonathan,

      I am also running xbian but having some trouble sending even a simple echo test. What did define exactly in revaliases and ssmtp.conf ?
      Thanks

      • SOLVED (Xbian on Model B+), I have forgot about 2 step verification in google, so I used a google-generated app-specific password instead of my usual gmail password. Here’s my “ssmtp.config”:
        ***

        root=ME@gmail.com
        mailhub=smtp.gmail.com:587
        hostname=MYHOSTNAME
        FromLineOverride=YES
        UseSTARTTLS=YES
        AuthUser=ME@gmail.com
        AuthPass= MY_APP_SPECIFIC_PASS

        ***
        and I put this in “revaliases”:
        ***

        root:ME@gmail.com:smtp.gmail.com:587

        ***

  18. I get the following warnings and errors trying to run the php test file.

    pi@raspberrypi ~/src $ php mailtest.php
    PHP Warning: Module ‘apc’ already loaded in Unknown on line 0
    PHP Warning: PHP Startup: apc.shm_size now uses M/G suffixes, please update your ini files in Unknown on line 0
    PHP Parse error: syntax error, unexpected ‘mail’ (T_STRING) in /home/pi/src/mailtest.php on line 7

    Appreciate if you could help.

  19. Instead of adding users (like www-data) to the roog group, wouldn’t it be safer to set the group of /etc/ssmtp/ssmtp.conf to ‘mail’?

    $chown root:mail /etc/ssmtp/ssmtp.conf
    $gpasswd -a www-data mail
    $gpasswd -a YourUserName mail

  20. Pingback: A secure cloud storage solution (Pi + ownCloud) – Part 2 of 2 | Rob Seder

  21. If you have an email account with GoDaddy, you can alter your settings in your ssmtp.conf file and your revaliases file as shown below:

    ssmtp.conf:

    mailhub=smtpout.secureserver.net
    USETLS=YES
    AuthUser=
    AuthPass=

    Don’t for get to remove the angle brackets above. They are just placeholders.

    revaliases:

    root:youraddress@yourdomain.com:smtpout.secureserver.net:465
    pi:youraddress@yourdomain.com:smtpout.secureserver.net:465

  22. Hello I’m trying to setup ossn (open source social network) but I need something to send verification mail, then will this method work for me??? Or I need change something???

  23. sir, i want to send the value of a variable in the python program as an email(every two hours). how can i do it? plz reply

    • Hi! Configure email to work, then write a shell script which calls the python program and sends the value in email. Schedule you shell script with cron to run every 2 hours.

  24. Hi, I am somewhat confused by the naming and revaliases…. so I am hoping you could provide some feedback.

    1. Thank you very much for this guide – it worked really well to it going. I used this with fial2ban and the email process worked perfectly.

    I want default names like pi and root to be able to use this as well. I use Gmail so I though the following would work in the revalaises file but it did not.

    root:address@gmail.com:smtp.gmail.com:587
    pi:address@gmail.com:smtp.gmail.com:587

    I have also about an aliases file used a bit differently (link below)
    http://www.sbprojects.com/projects/raspberrypi/exim4.php

    what is the the differences? which one is best – I would be happy to get one approch to work :-).

    2. I would like a friend pi name – not by app but by individual pi itself.

    Is sudo chfn -f “NAME” pi a better way to do this?

    Thanks in advance for any/all help.

  25. hi, i have a script scheduled which send me email for backup.. i can’t understand very well what happen, because i receive a correct mail with attachment, but also a second one that have an incorrect CCn, so gmail send me an “Mail delivery failure”..

    the second mail seem to be a system mail, because the body is: “sudo: no tty present and no askpass program specified”. is not important for now what the messagge means, but ccn is “andrea@raspberrypi”.

    in my mail.log:

    Mar 20 13:44:02 raspberrypi sSMTP[2963]: Creating SSL connection to host
    Mar 20 13:44:02 raspberrypi sSMTP[2963]: SSL connection using RSA_ARCFOUR_SHA1
    Mar 20 13:44:05 raspberrypi sSMTP[2963]: Sent mail for andrea@raspberrypi (221 2.0.0 closing connection ge8sm6215358wjc.32 – gsmtp) uid=1001 username=andrea outbytes=1632
    Mar 20 13:44:05 raspberrypi sSMTP[2966]: Creating SSL connection to host
    Mar 20 13:44:06 raspberrypi sSMTP[2966]: SSL connection using RSA_ARCFOUR_SHA1
    Mar 20 13:44:08 raspberrypi sSMTP[2966]: Sent mail for root@raspberrypi (221 2.0.0 closing connection k6sm2889647wia.6 – gsmtp) uid=1001 username=andrea outbytes=616

  26. Hiii, i have follwed all the steps,excpect Step3 b which is optional and in Step4 i wrote root:root@gmail.com:smtp.gmail.com:587
    Step5 i skiped this sudo usermod -a -G root www-data
    chmod 770 /etc/ssmtp/ssmtp.conf
    even i skiped step6

    and when i did echo i stuck with error as
    cannot send message:process excited with a non zero-status

    please make me to come out of this mess,i really trying hard to comeout what might be missing
    i have static ip and proxy id and passwrd i set those paramters in /etc/enviroment and /etc/apt/ /etc/network am able to use wget apt and web browser also

  27. Pingback: Sending emails with the Raspberry Pi |

  28. Pingback: Tether Android Phone to Raspberry Pi (for MMS/SMS) | DL-UAT

  29. Thanks for the tutorial it has worked well – almost!

    The email gets sent from the command line but I get this error

    Mail” contains invalid character ‘\342′

    also, and more importantly, it doesnt seem to work with php.

    From the command line the php returns “-bash PHP: Command not found”

  30. Very helpful, thank you! You might want to consider changing the smart quotes in the code samples to inch marks so that the sample code will execute properly from the shell.

  31. Pingback: Emails versenden mit dem Raspberry Pi |

  32. Great tutorial, as simple as following the steps 1,2,3. Was looking for a solution to a sendmail problem and this was it. Awesome.

  33. I am getting the following message when sending a test message. Any help would be appreciated.

    mail: cannot sent message: Process exited with a non-zero status

    Thanks,
    -SD:

  34. Pingback: Getting Your (Annoyingly Dynamic) IP Address Emailed To You Every Day | Linskill Repo

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>