from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage import smtplib msg = MIMEMultipart('alternative') msg['From'] = '[email protected]' msg['To'] = '[email protected]' msg['Subject'] = 'Test Email' # add plain text body text = MIMEText('Hello, this is a test email.') msg.attach(text) # add HTML body html = MIMEText('Hello, this is a test email.
', 'html') msg.attach(html) # send email s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login('[email protected]', 'password') s.sendmail(msg['From'], msg['To'], msg.as_string()) s.quit()
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage import smtplib msg = MIMEMultipart() msg['From'] = '[email protected]' msg['To'] = '[email protected]' msg['Subject'] = 'Test Email with Image Attachment' # add image attachment with open('image.jpg', 'rb') as f: image = MIMEImage(f.read(), name='image.jpg') msg.attach(image) # send email s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login('[email protected]', 'password') s.sendmail(msg['From'], msg['To'], msg.as_string()) s.quit()This example creates a multipart message with an image attachment. The image file is read in binary mode and attached to the email using MIMEImage. The email.mime.multipart package is part of the email package in Python's standard library. The email package contains modules for sending and receiving email messages using various protocols, including SMTP, IMAP, and POP3.