How to Send an HTML Email with a JPG Image Attachment in Python with Gmail
It's useful sometimes to have the output of your Python scripts sent via email. The bellow script does just that using Gmail. Note that the gmal_app_password is not the actual password to the Gmail account you want to use for sending. It is actually, an App Password, that can be generated in the Account Security section of your Google account.
Here is the Python code to send an HTML email with a JPG image attachment with Gmail:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage # Set the email parameters to_addr = 'recipient@example.com' from_addr = 'user@gmail.com' gmail_app_password = 'abcdefghijklmnopqrstuvwxyz' # Create the message msg = MIMEMultipart() msg['To'] = to_addr msg['From'] = from_addr msg['Subject'] = 'Test Email' # Set the message body html = """ <html> <body> <p>This is a test email with an image attached.</p> </body> </html> """ msg.attach(MIMEText(html, 'html')) # Read the image file and attach it to the email with open('image.jpg', 'rb') as f: image = MIMEImage(f.read()) msg.attach(image) # Send the email server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login(from_addr, gmail_app_password) server.send_message(msg) server.quit() print('Email sent!')
Comments
Post a Comment