Skip to content

Instantly share code, notes, and snippets.

@edubxb
Last active July 20, 2022 10:01
Show Gist options
  • Save edubxb/8a1a6092032b7b1f7621 to your computer and use it in GitHub Desktop.
Save edubxb/8a1a6092032b7b1f7621 to your computer and use it in GitHub Desktop.
Simple program to send emails from command line
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2022 Eduardo Bellido Bellido
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import getpass
import platform
from optparse import OptionParser, OptionGroup
import smtplib
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import COMMASPACE, formatdate
description = "Simple program to send emails from command line"
usage = "%prog [OPTIONS]"
version = "v1.3 20/07/2022"
def send_mail(sender, to, subject, body, cc=None, bcc=None, important=False,
files=None, server="localhost", port="25"):
body_charset = 'UTF-8'
recipients = to
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = COMMASPACE.join(to)
if cc is not None:
recipients += cc
msg['CC'] = COMMASPACE.join(cc)
if bcc is not None:
recipients += bcc
msg['BCC'] = COMMASPACE.join(bcc)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = Header(subject, 'utf-8').encode()
if important:
msg['Importance'] = 'high'
msg.attach(MIMEText(body, 'plain', body_charset))
if files is None:
files = []
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload(open(f, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' %
os.path.basename(f))
msg.attach(part)
smtp = smtplib.SMTP(server, port)
smtp.sendmail(sender, recipients, msg.as_string())
smtp.close()
op = OptionParser(description=description, usage=usage, version=version)
mandatory_opts = OptionGroup(op, "Mandatory")
mandatory_opts.add_option("-t", "--to", action="store", dest="to",
metavar="EMAILs", type="string",
help="Coma-separated mail recipients")
mandatory_opts.add_option("-s", "--subject", action="store", dest="subject",
metavar="SUBJECT", type="string",
help="Subject of the email")
mandatory_opts.add_option("-m", "--body", action="store", dest="body",
metavar="TEXT", type="string",
help="Text body of the email")
optional_opts = OptionGroup(op, "Optional")
optional_opts.add_option("-n", "--name", action="store", dest="sender_name",
metavar="NAME", type="string",
help="Email sender name")
optional_opts.add_option("-f", "--from", action="store", dest="sender",
metavar="EMAIL", type="string",
default=getpass.getuser() + "@" + platform.node(),
help="Email sender address (default: %default)")
optional_opts.add_option("-c", "--cc", action="store", dest="cc",
metavar="EMAILs", type="string",
help="Coma-separated mail recipients for carbon copy")
optional_opts.add_option("-b", "--bcc", action="store", dest="bcc",
metavar="EMAILs", type="string",
help="""Coma-separated mail recipients for blind
carbon copy""")
optional_opts.add_option("-i", "--important", action="store_true",
dest="important",
help="Mark email as important", default=False)
optional_opts.add_option("-a", "--attach", action="append", dest="files",
metavar="FILE", type="string",
help="Attach a file to the email")
optional_opts.add_option("-r", "--server", action="store", dest="server",
metavar="HOST", type="string", default="localhost",
help="Relay SMTP server (default: %default)")
optional_opts.add_option("-p", "--port", action="store", dest="port",
metavar="PORT", type="string", default="25",
help="Relay SMTP server port (default: %default)")
op.add_option_group(mandatory_opts)
op.add_option_group(optional_opts)
(opts, args) = op.parse_args()
if len(sys.argv) < 2:
op.print_help()
sys.exit(0)
if opts.body is None:
print("Error: empty body")
sys.exit(1)
if opts.subject is None:
print("Error: empty subject")
sys.exit(1)
to = opts.to.split(',')
cc = None
bcc = None
files = None
sender = opts.sender
if opts.sender_name:
sender = opts.sender_name + '<' + opts.sender + '>'
if opts.cc:
cc = opts.cc.split(',')
if opts.bcc:
bcc = opts.bcc.split(',')
if opts.files:
files = opts.files
else:
files = []
try:
send_mail(sender, to, opts.subject, opts.body, cc, bcc, opts.important,
files, opts.server, opts.port)
except Exception as err:
print("Error sending email: " + str(err))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment