import smtplib import io from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage def send_email_with_attachment(sender_email, password, to_email, subject, image_bytes): """ Sends an email with an image attachment. Args: sender_email (str): The sender's email address. password (str): The sender's email password. to_email (str): The recipient's email address. subject (str): The subject of the email. image_bytes (bytes): The image content as a byte string. """ message = MIMEMultipart('alternative') message['Subject'] = subject message['From'] = sender_email message['To'] = to_email html_content = """ Happy Halloween!

🎃 Happy Halloween! 🎃

Thank you for your interest in the BuffTeks student organization!

Wishing you a spooktacular Halloween!
Here is your special holiday photo generated just for you.
Enjoy and have a frightfully fun day!

""" message.attach(MIMEText(html_content, 'html')) if image_bytes: # The image object is converted to bytes before attaching. img_byte_arr = io.BytesIO() # Assuming image_bytes is a PIL Image object. # Convert to RGB if necessary for JPEG format. if image_bytes.mode in ('RGBA', 'P'): image_bytes = image_bytes.convert('RGB') image_bytes.save(img_byte_arr, format='JPEG') img_byte_arr = img_byte_arr.getvalue() image_part = MIMEImage(img_byte_arr, _subtype="jpeg") image_part.add_header('Content-Disposition', 'attachment', filename="halloween.jpg") message.attach(image_part) try: with smtplib.SMTP('mail.privateemail.com', 587) as server: server.starttls() server.login(sender_email, password) server.send_message(message) print("Email sent successfully!") except Exception as e: print(f"Failed to send email: {str(e)}")