Skip to content

Instantly share code, notes, and snippets.

@dpwrussell
Last active December 29, 2015 04:39
Show Gist options
  • Save dpwrussell/7616042 to your computer and use it in GitHub Desktop.
Save dpwrussell/7616042 to your computer and use it in GitHub Desktop.
Python sendmail
email_details.cfg
""" This relies on a 'email_details.cfg' file with the following settings
[EmailDetails]
host: smtp.mydomain.com
port: 587
username: username
password: password
recipients: [email protected]
sender: [email protected]
"""
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
import re
import ConfigParser
def validateEmail(email):
if len(email) > 7:
if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
return 1
return 0
# Secret Details Config
email_details = 'email_details.cfg'
config = ConfigParser.RawConfigParser()
config.read(email_details)
HOST = config.get('EmailDetails', 'host')
PORT = config.getint('EmailDetails', 'port')
USERNAME = config.get('EmailDetails', 'username')
PASSWORD = config.get('EmailDetails', 'password')
RECIPIENTS = config.get('EmailDetails', 'recipients')
SENDER = config.get('EmailDetails', 'sender')
subject = 'Test Subject'
message = 'Test Message'
recipients = RECIPIENTS.split(',')
s = smtplib.SMTP(HOST, PORT)
# s.ehlo()
s.starttls()
s.login(USERNAME, PASSWORD)
for recipient in recipients:
if validateEmail(recipient):
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = SENDER
msg['To'] = recipient
print('msgasstring: %s' %msg.as_string())
s.sendmail(SENDER, [recipient], msg.as_string())
s.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment