import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # create message object instance message = MIMEMultipart() # setup the parameters of the message message['From'] = '[email protected]' message['To'] = '[email protected]' message['Subject'] = 'Example email with HTML and plain text' # create the HTML message html = """Hello World!
""" html_msg = MIMEText(html, 'html') # create the plain text message plain_text = "Hello World!" plain_text_msg = MIMEText(plain_text, 'plain') # add messages to the MIMEMultipart object message.attach(html_msg) message.attach(plain_text_msg) # create an SMTP server connection and send the message with smtplib.SMTP('smtp.example.com', port=587) as smtp: smtp.login('[email protected]', 'password') smtp.sendmail(message['From'], message['To'], message.as_string())
from email.mime.base import MIMEBase from email import encoders # create message object instance message = MIMEMultipart() # setup the parameters of the message message['From'] = '[email protected]' message['To'] = '[email protected]' message['Subject'] = 'Example email with attachment' # attach the file filename = 'example.txt' attachment = open(filename, 'rb') attachment_data = MIMEBase('application', 'octet-stream') attachment_data.set_payload(attachment.read()) encoders.encode_base64(attachment_data) attachment_data.add_header('Content-Disposition', f'attachment; filename={filename}') message.attach(attachment_data) # create an SMTP server connection and send the message with smtplib.SMTP('smtp.example.com', port=587) as smtp: smtp.login('[email protected]', 'password') smtp.sendmail(message['From'], message['To'], message.as_string())In both examples, we import MIMEMultipart from the email module in Python's standard library.