Skip to content

Instantly share code, notes, and snippets.

@fstanis
Created November 5, 2018 19:19
Show Gist options
  • Save fstanis/65d761e52ac4fd5fd73ca10641bee2f7 to your computer and use it in GitHub Desktop.
Save fstanis/65d761e52ac4fd5fd73ca10641bee2f7 to your computer and use it in GitHub Desktop.
Sends a multipart/alternative email containing 3 parts: text/plain, text/html and text/x-other.
#!/usr/bin/python3
# Copyright 2018 Google LLC.
# SPDX-License-Identifier: Apache-2.0
# Sends a multipart/alternative email containing 3 parts: text/plain, text/html and text/x-other.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
SUBJECT = 'Test email'
SENDER = 'johndoe@example.com'
SMTP_SERVER = 'smtp.gmail.com:587'
SMTP_USERNAME = 'user@gmail.com'
SMTP_PASSWORD = ''
def CreateEmail(recipient):
payload = MIMEMultipart('alternative')
payload['Subject'] = SUBJECT
payload['From'] = SENDER
payload['To'] = recipient
payload.attach(MIMEText('text version', 'plain'))
payload.attach(MIMEText('<b>html version</b>', 'html'))
payload.attach(MIMEText('this shouldn\'t be displayed', 'x-other'))
return payload
def SendPayloadViaSMTP(payload):
smtp = smtplib.SMTP(SMTP_SERVER)
try:
smtp.ehlo()
smtp.starttls()
smtp.login(SMTP_USERNAME, SMTP_PASSWORD)
smtp.sendmail(payload['From'], payload['To'], payload.as_string())
except Exception as e:
print('SMTP Exception:\n' + str(e))
finally:
smtp.quit()
def main():
email = CreateEmail('user@domain.com')
SendPayloadViaSMTP(email)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment