68 lines
3.0 KiB
Python
68 lines
3.0 KiB
Python
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 = """
|
|
<html>
|
|
<head>
|
|
<title>Happy Halloween!</title>
|
|
</head>
|
|
<body style="font-family: Arial, sans-serif; background-color: #1a1a1a; color: #f0f0f0; margin: 0; padding: 20px; text-align: center;">
|
|
<div style="max-width: 600px; margin: auto; background-color: #2c2c2c; padding: 30px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.5);">
|
|
<h2 style="color: #ff6600;">🎃 Happy Halloween! 🎃</h2>
|
|
<p style="font-size: 16px; line-height: 1.6;">
|
|
Thank you for your interest in the
|
|
<a href="https://buffteks.org" target="_blank" rel="noopener" style="color: #ff8533; text-decoration: none;" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';">BuffTeks</a>
|
|
student organization!
|
|
</p>
|
|
<p style="font-size: 16px; line-height: 1.6;">
|
|
Wishing you a spooktacular Halloween!<br>
|
|
Here is your special holiday photo generated just for you.<br>
|
|
Enjoy and have a frightfully fun day!
|
|
</p>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
"""
|
|
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)}") |