from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage import smtplib msg = MIMEMultipart() msg.attach(MIMEText('Hello, this is a sample email with an image.')) with open('/path/to/image.jpg', 'rb') as fp: img = MIMEImage(fp.read()) msg.attach(img) msg['Subject'] = 'Test Email with an Image' msg['From'] = '[email protected]' msg['To'] = '[email protected]' server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login('[email protected]', 'password') server.send_message(msg) server.quit()
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib msg = MIMEMultipart() msg['Subject'] = 'Test Email' msg['From'] = '[email protected]' msg['To'] = '[email protected]' msg.add_header('X-Custom-Header', 'Custom Value') msg.attach(MIMEText('Hello, this is a test email.')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login('[email protected]', 'password') server.send_message(msg) server.quit()In the above example, we added a custom header to the email message using the add_header method of MIMEMultipart. The header was added in the format "Header-Name: Header-Value". The email was then sent using the SMTP server. Overall, Python email.MIMEMultipart package library provides an easy and convenient way to create and send complex email messages with multiple parts and custom headers.