Skip to content

Instantly share code, notes, and snippets.

@mtik00
Created June 9, 2015 15:53
Show Gist options
  • Save mtik00/129d292663b06745bc4d to your computer and use it in GitHub Desktop.
Save mtik00/129d292663b06745bc4d to your computer and use it in GitHub Desktop.
Python 2.4-compliant sendmail function
def sendmail(subject, to, sender, body, mailserver, body_type="html", attachments=None, cc=None):
"""Send an email message using the specified mail server using Python's
standard `smtplib` library and some extras (e.g. attachments).
NOTE: This function has no authentication. It was written for a mail server
that already does sender/recipient validation.
WARNING: This is a non-streaming message system. You should not send large
files with this function!
NOTE: The body should include newline characters such that no line is greater
than 990 characters. Otherwise the email server will insert newlines which
may not be appropriate for your content.
http://stackoverflow.com/a/18568276
"""
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ', '.join(to)
if cc:
msg['Cc'] = ", ".join(cc)
else:
cc = []
msg.attach(MIMEText(body, body_type))
attachments = [] or attachments
for attachment in attachments:
part = MIMEBase('application', "octet-stream")
part.set_payload(open(attachment, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment))
msg.attach(part)
server = smtplib.SMTP(mailserver)
server.sendmail(sender, to + cc, msg.as_string()) # pragma: no cover
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment