Send email from command line: Difference between revisions

From James's Wiki
(Created page with "https://www.brewpiremix.com/send-mail-from-your-raspberry-pi/")
 
No edit summary
Line 1: Line 1:
https://www.brewpiremix.com/send-mail-from-your-raspberry-pi/
Source=https://www.brewpiremix.com/send-mail-from-your-raspberry-pi/<br>
Send Mail from your Raspberry Pi
 
I have to go searching for how to do this every time. This time I thought I would memorialize the instructions. I found this in an article written by Stacy Prowell on Medium.com.
 
The first thing you need is some additional software. I am going to use Postfix, which is a mail transfer agent (MTA) — that is, something that knows how to talk to other MTAs to send and receive email. In particular, Postfix supports the simple mail transfer protocol (SMTP), so it can talk to nearly any other MTA out there, including Google’s Gmail. In case you don’t like Gmail, there are guides online like this one for getting Postfix to talk to other SMTP servers.
1. Install Postfix
 
Run the following command at the prompt to install Postfix along with simple authentication layer security (SASL), which Postfix will use to connect to Gmail.
 
sudo apt install postfix libsasl2-modules
 
During the installation, you will be asked about how the mail server should operate. You want an Internet Site, where email is sent and received directly using SMTP, so select that option.
Screenshot of package configuration screen
So many choices
 
Now you’ll be asked for the “system mail name.” You should use your hostname (raspberrypi, for instance) or, if you have a fully-qualified domain name for your network via your ISP or a service like DYN, then you can use that. Don’t stress over this; you can modify it later by editing the /etc/postfix/main.cf file if you need to.
Screenshot of a package configuration dialog
Set the server name
2. Get an Application Password for Postfix from Google
 
have Google set up for two-factor authentication (2FA), so how will the Pi be able to send an email? Well, it turns out you can get Google to generate an application password, which is a password to allow a specific application to connect.
 
To get an application password head to: https://myaccount.google.com and log in.
Screenshot of Google account options
Account security settings
 
Select “Security” from the list on the left.
Screenshot of Google account security options
Manage your application passwords
 
Note that I have two-step verification turned on. You might or might not; either way, creating an application password for each application is a good idea. If you lose a device or it is stolen, you can revoke the application password and not have to change your existing password or passwords for other applications.
 
There should be a box for “Signing in to Google” that contains an option for “App passwords.” Click on that. You might have to sign in again at this point (I did). This should take you to the page to manage application passwords. The example account I am using doesn’t have any.
Screenshot of app password manager
Create a new application password
 
Now click on “Select app” and select Mail. Then click on “Select device” and select Other. You’ll need to enter the name of the device (for this example it is raspberrypi4). Click Generate to create the application password.
Screenshot of new application password
A new application password! Don’t get excited; I’ve already deleted it.
 
You should now be presented with a new application password. This is the text in the yellow block in the image above. Success! Do not click done! Copy the app password first, or write it down. You’ll need it and you can’t display it again.
3. Configure SASL
 
(A lot of the content of this section is taken from the Postfix SASL HowTo.)
 
We are almost done. The next thing to do is to add the app password you just generated to the SASL configuration. Run the following command.
 
sudo nano -B /etc/postfix/sasl/sasl_passwd
 
This command will open the file in an editor. It is likely the file does not exist, and you will see an empty file. Add the following line, replacing username and password with your Gmail username and the application password you just generated (don’t include the spaces).
 
[smtp.gmail.com]:587 username@gmail.com:password
 
This line tells SASL that when it connects to the host smtp.gmail.com at port 587 to download mail, it should use the given username and password to connect. Exit and save with CTRL+x, y, and Enter.
 
This file contains a “clear text” password. Run the following command to protect that file.
 
sudo chmod u=rw,go= /etc/postfix/sasl/sasl_passwd
 
This command sets the user permissions (root) to read and write and removes any permissions for the group and others. (Fans of the numerical form of chmod will recognize this as 0600.)
 
Now turn this file into a hash file for Postfix. Run the following command.
 
sudo postmap /etc/postfix/sasl/sasl_passwd
 
This command will create a new file named sasl_passwd.db in the same directory. It should already have the permissions set correctly, but just in case, let’s also explicitly set the permissions.
 
sudo chmod u=rw,go= /etc/postfix/sasl/sasl_passwd.db
 
4. Configure Postfix
 
Now let’s finish up the configuration of Postfix. Run the following commands.
 
sudo cp /etc/postfix/main.cf !#$.dist
sudo nano /etc/postfix/main.cf
 
Find the line (near the bottom) that starts with relayhost =. Here is where we specify that we want to use Google’s SMTP server as our relay host, and this must match what we put in /etc/postfix/sasl/sasl_passwd. Change the line so it looks as follows.
 
relayhost = [smtp.gmail.com]:587
 
Next, add the following to the end of the file. (Documentation for these options and others can be found here.)
 
# Enable authentication using SASL.
smtp_sasl_auth_enable = yes
# Use transport layer security (TLS) encryption.
smtp_tls_security_level = encrypt
# Do not allow anonymous authentication.
smtp_sasl_security_options = noanonymous
# Specify where to find the login information.
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd
# Where to find the certificate authority (CA) certificates.
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
 
Save and exit with CTRL+x, y, and Enter, and then restart Postfix with the following command.
 
sudo systemctl restart postfix
 
5. Testing Email
 
Next, let’s verify that we can send an email via Google’s SMTP server. Type the following at the command line, replacing username with your Gmail user name (so the email goes to you).
 
sendmail username@gmail.com
Subject: It works!
Hey, it works!
.
 
The first line uses the sendmail command to send an email to the specified recipients (you can list more than one). The subsequent lines optionally specify mail headers like the subject, and then the body of the email. The entire thing is terminated by a period. Note that this is just one way to send email using the sendmail command. Later we will use sendmail to send the output of commands.
 
Check your email. If you got an email from yourself (remember: Postfix is using your credentials) then everything is working. If you didn’t, then you should check a few places on the system.
Checking for Problems
 
The most obvious problems are an inability to reach the Gmail server and a failure to authenticate with the Gmail server.
 
Inability to reach the Gmail SMTP servers
 
Make sure the network is connected and see if you can reach the Gmail SMTP server. The easiest way to do this is to “ping” smtp.gmail.com. If you see a failure message like “ping: smtp.gmail.com: Name or service not known,” then you should check your network connectivity. (It is possible that your ISP or the Google service itself is down… but this is less likely.)
 
Failure to authenticate with the Gmail SMTP servers
 
To see this, check the file /var/log/syslog for messages from postfix. If you see a message like the one below, your credentials were not accepted.
 
Dec 10 08:04:01 raspberrypi postfix/smtp[18329]: 331F960582: SASL authentication failed; server smtp.gmail.com[108.177.122.108] said: 535-5.7.8 Username and Password not accepted. Learn more at?535 5.7.8  https://support.google.com/mail/?p=BadCredentials c188sm1372198ywb.56 - gsmtp
 
Check that the content of /etc/postfix/sasl/sasl_passwd is exactly what it should be, and make sure you ran the postmap command to create the hash file. If everything looks correct, or if you don’t have your application password written down, go back to Google account management and delete the old application password, create a new one, and carefully add it to /etc/postfix/sasl/sasl_passwd and then run the postmap command given earlier.
Adding Email Aliases
 
You can add email aliases by editing the file /etc/aliases and then running the newaliases command. This can be used to tell Postfix how to handle local email addresses.
 
For example, perhaps you want email to the pi user to go to your Gmail account. You would run the following command to edit the aliases file.
 
sudo nano -R /etc/aliases
 
Next, you would add the following line, where username is your Gmail username.
 
pi: username@gmail.com
 
Finally, tell the system about the new mail aliases by running the following command.
 
sudo newaliases
 
Now mail sent to pi will be forwarded along by Postfix to your Gmail account.
 
Depending on what you are using the Pi for, you might forward postmaster, webmaster, or other names. Note that these don’t have to correspond to any local account.
Sending Text Messages
 
A computer in our server room sends me a text message each morning using a dedicated cellular long term evolution (LTE) modem. The Pi doesn’t have one (though you can buy them; for instance, here’s one), but if you’ve successfully followed the above instructions, your Pi can send email, and it turns out you can send a text message by first sending an email.
 
First, a word of warning. Sending an email over a connection to Gmail isn’t likely to cost you any more than you are already paying for internet connectivity. But receiving a text message on your phone just might. Check your plans, and be courteous of other people who might not want unsolicited text messages from you.
Email to Text
 
Cellular providers will convert emails sent to a special address into text messages, and forward them along. Text replies may be converted back to a return email, but this is less certain. The two articles below cover this in some detail and provide information for both short message service (SMS) and multimedia message service (MMS), where supported.
 
    How to send a text message from your email account
    How to Send Text Messages Via Email for Free (SMS & MMS)
 
Here are the top four North American providers and the information for each. (Apologies to non-North American readers; there are far too many wireless services around the world for me to try to include them all.)
Service Name SMS Email Suffix MMS Email Suffix
AT&T Mobility @txt.att.net @mms.att.net
Verizon Wireless @vtext.com @vzwpix.com
T-Mobile @tmomail.net @tmomail.net (same)
Sprint Corporation @messaging.sprintpcs.com @pm.sprint.com
view raw
email-to-text.csv hosted with ❤ by GitHub
 
You use these by finding the provider for the recipient of the message, and then sending an email to the ten-digit (North American) phone number followed by the appropriate email suffix.
 
For instance, suppose your cell phone number is (724) 555–1212, and your provider is Verizon. Then you can send yourself a text by sending an email message to the address 7245551212@vtext.com. These SMS messages are typically limited to 140 characters.
 
You can also send MMS messages, but this is a bit more complex.
Email to Text from the Raspberry Pi
 
My carrier is Sprint, and my number is (not really) 724–555–1212. So to send a text to my phone I can send a short text email to 7245551212@messaging.sprintpcs.com. Let’s try a test.
 
At the prompt of the Raspberry Pi, try the following (replacing the address with whatever is correct for your cell phone).
 
echo "Test" | sendmail 7245551212@messaging.sprintpcs.com
 
You should receive a text on your phone.
Screenshot of a text message
Success!
 
Great! If you don’t, check your Gmail for a delivery failure notice, and make sure you are using the correct address for the recipient (you, in this case).
Reply to Text
 
What happens if you reply to a text? Well, that depends on your service provider. For my provider (Sprint) an email is created and sent.
Reply email
Talking back to the text
 
You can reply to this email, and the result will be a (possibly very ugly) text message. Communication achieved!
 
Note that if you are getting your hopes up on automatically processing the replies, you should be careful. The reply above was sent as a base 64 encoded rich text file. That is, you may have to do some work if you want true two-way communication.

Revision as of 09:39, 3 December 2021

Source=https://www.brewpiremix.com/send-mail-from-your-raspberry-pi/
Send Mail from your Raspberry Pi

I have to go searching for how to do this every time. This time I thought I would memorialize the instructions. I found this in an article written by Stacy Prowell on Medium.com.

The first thing you need is some additional software. I am going to use Postfix, which is a mail transfer agent (MTA) — that is, something that knows how to talk to other MTAs to send and receive email. In particular, Postfix supports the simple mail transfer protocol (SMTP), so it can talk to nearly any other MTA out there, including Google’s Gmail. In case you don’t like Gmail, there are guides online like this one for getting Postfix to talk to other SMTP servers. 1. Install Postfix

Run the following command at the prompt to install Postfix along with simple authentication layer security (SASL), which Postfix will use to connect to Gmail.

sudo apt install postfix libsasl2-modules

During the installation, you will be asked about how the mail server should operate. You want an Internet Site, where email is sent and received directly using SMTP, so select that option. Screenshot of package configuration screen So many choices

Now you’ll be asked for the “system mail name.” You should use your hostname (raspberrypi, for instance) or, if you have a fully-qualified domain name for your network via your ISP or a service like DYN, then you can use that. Don’t stress over this; you can modify it later by editing the /etc/postfix/main.cf file if you need to. Screenshot of a package configuration dialog Set the server name 2. Get an Application Password for Postfix from Google

have Google set up for two-factor authentication (2FA), so how will the Pi be able to send an email? Well, it turns out you can get Google to generate an application password, which is a password to allow a specific application to connect.

To get an application password head to: https://myaccount.google.com and log in. Screenshot of Google account options Account security settings

Select “Security” from the list on the left. Screenshot of Google account security options Manage your application passwords

Note that I have two-step verification turned on. You might or might not; either way, creating an application password for each application is a good idea. If you lose a device or it is stolen, you can revoke the application password and not have to change your existing password or passwords for other applications.

There should be a box for “Signing in to Google” that contains an option for “App passwords.” Click on that. You might have to sign in again at this point (I did). This should take you to the page to manage application passwords. The example account I am using doesn’t have any. Screenshot of app password manager Create a new application password

Now click on “Select app” and select Mail. Then click on “Select device” and select Other. You’ll need to enter the name of the device (for this example it is raspberrypi4). Click Generate to create the application password. Screenshot of new application password A new application password! Don’t get excited; I’ve already deleted it.

You should now be presented with a new application password. This is the text in the yellow block in the image above. Success! Do not click done! Copy the app password first, or write it down. You’ll need it and you can’t display it again. 3. Configure SASL

(A lot of the content of this section is taken from the Postfix SASL HowTo.)

We are almost done. The next thing to do is to add the app password you just generated to the SASL configuration. Run the following command.

sudo nano -B /etc/postfix/sasl/sasl_passwd

This command will open the file in an editor. It is likely the file does not exist, and you will see an empty file. Add the following line, replacing username and password with your Gmail username and the application password you just generated (don’t include the spaces).

[smtp.gmail.com]:587 username@gmail.com:password

This line tells SASL that when it connects to the host smtp.gmail.com at port 587 to download mail, it should use the given username and password to connect. Exit and save with CTRL+x, y, and Enter.

This file contains a “clear text” password. Run the following command to protect that file.

sudo chmod u=rw,go= /etc/postfix/sasl/sasl_passwd

This command sets the user permissions (root) to read and write and removes any permissions for the group and others. (Fans of the numerical form of chmod will recognize this as 0600.)

Now turn this file into a hash file for Postfix. Run the following command.

sudo postmap /etc/postfix/sasl/sasl_passwd

This command will create a new file named sasl_passwd.db in the same directory. It should already have the permissions set correctly, but just in case, let’s also explicitly set the permissions.

sudo chmod u=rw,go= /etc/postfix/sasl/sasl_passwd.db

4. Configure Postfix

Now let’s finish up the configuration of Postfix. Run the following commands.

sudo cp /etc/postfix/main.cf !#$.dist sudo nano /etc/postfix/main.cf

Find the line (near the bottom) that starts with relayhost =. Here is where we specify that we want to use Google’s SMTP server as our relay host, and this must match what we put in /etc/postfix/sasl/sasl_passwd. Change the line so it looks as follows.

relayhost = [smtp.gmail.com]:587

Next, add the following to the end of the file. (Documentation for these options and others can be found here.)

  1. Enable authentication using SASL.

smtp_sasl_auth_enable = yes

  1. Use transport layer security (TLS) encryption.

smtp_tls_security_level = encrypt

  1. Do not allow anonymous authentication.

smtp_sasl_security_options = noanonymous

  1. Specify where to find the login information.

smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd

  1. Where to find the certificate authority (CA) certificates.

smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Save and exit with CTRL+x, y, and Enter, and then restart Postfix with the following command.

sudo systemctl restart postfix

5. Testing Email

Next, let’s verify that we can send an email via Google’s SMTP server. Type the following at the command line, replacing username with your Gmail user name (so the email goes to you).

sendmail username@gmail.com Subject: It works! Hey, it works! .

The first line uses the sendmail command to send an email to the specified recipients (you can list more than one). The subsequent lines optionally specify mail headers like the subject, and then the body of the email. The entire thing is terminated by a period. Note that this is just one way to send email using the sendmail command. Later we will use sendmail to send the output of commands.

Check your email. If you got an email from yourself (remember: Postfix is using your credentials) then everything is working. If you didn’t, then you should check a few places on the system. Checking for Problems

The most obvious problems are an inability to reach the Gmail server and a failure to authenticate with the Gmail server.

Inability to reach the Gmail SMTP servers

Make sure the network is connected and see if you can reach the Gmail SMTP server. The easiest way to do this is to “ping” smtp.gmail.com. If you see a failure message like “ping: smtp.gmail.com: Name or service not known,” then you should check your network connectivity. (It is possible that your ISP or the Google service itself is down… but this is less likely.)

Failure to authenticate with the Gmail SMTP servers

To see this, check the file /var/log/syslog for messages from postfix. If you see a message like the one below, your credentials were not accepted.

Dec 10 08:04:01 raspberrypi postfix/smtp[18329]: 331F960582: SASL authentication failed; server smtp.gmail.com[108.177.122.108] said: 535-5.7.8 Username and Password not accepted. Learn more at?535 5.7.8 https://support.google.com/mail/?p=BadCredentials c188sm1372198ywb.56 - gsmtp

Check that the content of /etc/postfix/sasl/sasl_passwd is exactly what it should be, and make sure you ran the postmap command to create the hash file. If everything looks correct, or if you don’t have your application password written down, go back to Google account management and delete the old application password, create a new one, and carefully add it to /etc/postfix/sasl/sasl_passwd and then run the postmap command given earlier. Adding Email Aliases

You can add email aliases by editing the file /etc/aliases and then running the newaliases command. This can be used to tell Postfix how to handle local email addresses.

For example, perhaps you want email to the pi user to go to your Gmail account. You would run the following command to edit the aliases file.

sudo nano -R /etc/aliases

Next, you would add the following line, where username is your Gmail username.

pi: username@gmail.com

Finally, tell the system about the new mail aliases by running the following command.

sudo newaliases

Now mail sent to pi will be forwarded along by Postfix to your Gmail account.

Depending on what you are using the Pi for, you might forward postmaster, webmaster, or other names. Note that these don’t have to correspond to any local account. Sending Text Messages

A computer in our server room sends me a text message each morning using a dedicated cellular long term evolution (LTE) modem. The Pi doesn’t have one (though you can buy them; for instance, here’s one), but if you’ve successfully followed the above instructions, your Pi can send email, and it turns out you can send a text message by first sending an email.

First, a word of warning. Sending an email over a connection to Gmail isn’t likely to cost you any more than you are already paying for internet connectivity. But receiving a text message on your phone just might. Check your plans, and be courteous of other people who might not want unsolicited text messages from you. Email to Text

Cellular providers will convert emails sent to a special address into text messages, and forward them along. Text replies may be converted back to a return email, but this is less certain. The two articles below cover this in some detail and provide information for both short message service (SMS) and multimedia message service (MMS), where supported.

   How to send a text message from your email account
   How to Send Text Messages Via Email for Free (SMS & MMS)

Here are the top four North American providers and the information for each. (Apologies to non-North American readers; there are far too many wireless services around the world for me to try to include them all.) Service Name SMS Email Suffix MMS Email Suffix AT&T Mobility @txt.att.net @mms.att.net Verizon Wireless @vtext.com @vzwpix.com T-Mobile @tmomail.net @tmomail.net (same) Sprint Corporation @messaging.sprintpcs.com @pm.sprint.com view raw email-to-text.csv hosted with ❤ by GitHub

You use these by finding the provider for the recipient of the message, and then sending an email to the ten-digit (North American) phone number followed by the appropriate email suffix.

For instance, suppose your cell phone number is (724) 555–1212, and your provider is Verizon. Then you can send yourself a text by sending an email message to the address 7245551212@vtext.com. These SMS messages are typically limited to 140 characters.

You can also send MMS messages, but this is a bit more complex. Email to Text from the Raspberry Pi

My carrier is Sprint, and my number is (not really) 724–555–1212. So to send a text to my phone I can send a short text email to 7245551212@messaging.sprintpcs.com. Let’s try a test.

At the prompt of the Raspberry Pi, try the following (replacing the address with whatever is correct for your cell phone).

echo "Test" | sendmail 7245551212@messaging.sprintpcs.com

You should receive a text on your phone. Screenshot of a text message Success!

Great! If you don’t, check your Gmail for a delivery failure notice, and make sure you are using the correct address for the recipient (you, in this case). Reply to Text

What happens if you reply to a text? Well, that depends on your service provider. For my provider (Sprint) an email is created and sent. Reply email Talking back to the text

You can reply to this email, and the result will be a (possibly very ugly) text message. Communication achieved!

Note that if you are getting your hopes up on automatically processing the replies, you should be careful. The reply above was sent as a base 64 encoded rich text file. That is, you may have to do some work if you want true two-way communication.