[Send Email Over SMTP] Sends email over smtp, works for qmul email, but not NHS #python #email
# set up the SMTP server
# for qmul:
# host = smtp-mail.outlook.com
# port = 587
# username, password = full hh..@qmul.ac.uk email address
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import sys
try:
s = smtplib.SMTP(host=<smtp_host>, port=<smtp_port>)
s.starttls()
s.login(<username>, <password>)
except Exception as e:
print(e)
sys.exit(1)
def send_email(to, email_from, subject, body, attachments = [], reply_to = None):
"""
Sends an email to a list of recipients
to: list of email address of recipients
email_from: email address to send from
subject: subject line of email
body: body text in html
attachments: list of filepaths to attachments to include
reply_to: email address to reply to
"""
# create the message
msg = MIMEMultipart()
# setup the parameters of the message
msg['From'] = email_from
msg['To'] = ', '.join(to)
msg['Subject'] = subject
msg['reply-to'] = email_from if reply_to is None else reply_to
# add in the message body
msg.attach(MIMEText(body, 'html'))
for f in attachments:
# add in attachment
with open(f, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(f)
)
# After the file is closed
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
# send the message via the server set up earlier.
s.send_message(msg)