Skip to content

Instantly share code, notes, and snippets.

@epicserve
Created January 3, 2012 21:07
Show Gist options
  • Save epicserve/1556936 to your computer and use it in GitHub Desktop.
Save epicserve/1556936 to your computer and use it in GitHub Desktop.
A little script to test sending email
#!/usr/bin/env python
from argparse import ArgumentParser
import smtplib
from email.mime.text import MIMEText
"""
Example Usage:
./send_email.py \
--smtp-host="smtp.example.com" \
--smtp-user="myusername" \
--smtp-password="xxxxxxxx" \
--smtp-use-tls \
--sender "Example Sender <username@example.com>" \
--to="Example To1 <example1@example.com>,Example To2 <example2@example.com>" \
--subject="My Subject" \
--message="Message body goes here."
"""
def send_email(sender, receivers, subject, message, smtp_settings):
s = smtp_settings
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ", ".join(receivers)
if s.SMTP_USE_TLS:
mail = smtplib.SMTP_SSL(s.SMTP_HOST, s.SMTP_SSL_PORT)
else:
mail = smtplib.SMTP(s.SMTP_HOST, s.SMTP_PORT)
mail.login(s.SMTP_USER, s.SMTP_PASSWORD)
mail.sendmail(sender, receivers, msg.as_string())
def main():
args.to = args.to.split(',')
send_email(args.sender, args.to, args.subject, args.message, args)
if __name__ == '__main__':
usage = "%(prog)s [options]"
parser = ArgumentParser()
parser.add_argument("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="Be verbose.")
parser.add_argument("-d", "--debug",
action="store_true", dest="debug", default=False,
help="Print debug messages")
parser.add_argument("--smtp-host", required=True,
action="store", dest="SMTP_HOST",
help="The SMTP host")
parser.add_argument("--smtp-user",
action="store", dest="SMTP_USER",
help="The SMTP user")
parser.add_argument("--smtp-port",
action="store", dest="SMTP_PORT", default=25,
help="The SMTP port")
parser.add_argument("--smtp-password",
action="store", dest="SMTP_PASSWORD",
help="The SMTP password")
parser.add_argument("--smtp-use-tls",
action="store_true", dest="SMTP_USE_TLS", default=False,
help="Use SMTP TLS")
parser.add_argument("--smtp_ssl_port",
action="store", dest="SMTP_SSL_PORT", default=465,
help="The SMTP SSL port")
parser.add_argument("--sender", required=True,
action="store", dest="sender",
help="The from email address")
parser.add_argument("--to", required=True,
action="store", dest="to",
help="The list of recepients with each recepient seperated by a comma")
parser.add_argument("--subject", required=True,
action="store", dest="subject",
help="The email subject")
parser.add_argument("--message", required=True,
action="store", dest="message",
help="The email email message")
args = parser.parse_args()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment