Send Emails from Terminal with Python

Opening the Terminal is always faster than opening an email client or a browser, and with Python we can use a SMTP server to send emails right from the terminal, no muss, no fuss. Sent messages will also be appended to the INBOX.sent file.

Python comes with the built-in smtplib module for sending emails using the Simple Mail Transfer Protocol (SMTP). smtplib uses the RFC 821 protocol for SMTP. The imaplib.module uses the RFC 2060 but it is also backward compatible with IMAP4 (RFC 1730).

Also, note that this is a Python 3 script, unfortunately macOS' build-in version is 2.7. You can install Python 3 using brew.

Download

Copy the script below or download it here: send-email.zip

#!/usr/local/Cellar/python/3.7.4/bin/python3

#####################
# Python Send Email #
#####################

#
# Imports
#
import os
import time
import ssl
import imaplib
import smtplib
import email
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.headerregistry import Address
from email.message import EmailMessage

#
# Help Text
#
print("\n -----------------------------------------------\n =[           PYTHON E-MAIL SENDER            ]=\n -----------------------------------------------\n = Use \\ to break the line. Recipient format   =\n = can be email@srv.com or Name <mail@srv.com> =\n -----------------------------------------------\n") 


#
# Create Message
#
def create_email_message(from_address, to_address, subject, body):
    msg = EmailMessage()
    msg['From'] = from_address
    msg['To'] = to_address
    msg['Subject'] = subject
    msg.set_content(body)
    return msg

#
# Message Data
#
if __name__ == '__main__':
    msg = create_email_message(
        from_address='User Dude <myemail@server.com>',
        to_address=input(' Recipient: '),
        subject=input(' Subject: '),
        body=input('\n Message: ').replace('\\', '\n'))

#
# Account Details
#
login_email = 'myemail@server.com'
login_passwd = input('\n Password: ')

#
# Send Data to Server
#
try:
    with smtplib.SMTP('server.com', port=587) as smtp_server:
        smtp_server.ehlo()
        smtp_server.starttls()
        smtp_server.login(login_email, login_passwd)
        smtp_server.send_message(msg)

#
# Print Delivery Status
#
        print('\n \u2713 Email sent successfully.')

except Exception as e:
    print('\n Error: ',e, '\n Email not sent!')

#
# Save Message to INBOX.Sent
#
text = msg.as_string()
try:
    with imaplib.IMAP4_SSL('server.com', 993) as imap_server:
        imap_server.login(login_email, login_passwd)
        imap_server.append('INBOX.Sent', '\\Seen', imaplib.Time2Internaldate(time.time()), text.encode('utf8'))
        imap_server.logout()

#
# Print Saving Status
#
        print(' \u2713 Saved to INBOX.sent successfully.')
except Exception as e:
    print('\n Error: ',e, '\n Could not save email to INBOX.sent!')

Edit the Script

You need to change a few lines to make the script functional. So change these lines with the proper information:

### Edit the shebang tag with the proper path to Python binary. ###

#!/usr/local/Cellar/python/3.7.4/bin/python3

### Type your name and email address here ###

from_address='User Dude <myemail@server.com>',

### Type your username here. Usually that is your email address ###

login_email = 'myemail@server.com'

### Type your smtp server and it's port here ###

with smtplib.SMTP('server.com', port=587) as smtp_server:

### Type your imap server and it's port here ###

with imaplib.IMAP4_SSL('server.com', 993) as imap_server:

Running the Script

You can run the script by typing:

python send-email.py

Using python's absolute path:

/usr/local/Cellar/python/3.7.4/bin/python3 send-email.py

Or you can add the x flag (execute) and run it directly:

chmod +x send-email.py
mv send-email.py email
./email

Output:


 MTeam7 [~] $ email

-----------------------------------------------
=[           PYTHON E-MAIL SENDER            ]=
-----------------------------------------------
= Use \ to break the line. Recipient format   =
= can be email@srv.com or Name <mail@srv.com> =
-----------------------------------------------

Recipient: MTeam7 <mteam7@myserver.com>
Subject: Hi there MTeam7, I need some help!

Message: Hey MTeam7, how are you?\\Please mate, can you help me send emails from a terminal session using Python?\Sure it will speed-up things!\\Thank you in advance mate.\\User Dude

Password: ThisIsMyEMailPassword

✓ Email sent successfully.
✓ Saved to INBOX.sent successfully.

Received Email:

Email

{{ message }}

{{ 'Comments are closed.' | trans }}