Но когда я запустил программу, она не завершилась через 5 минут, хотя я ограничился только одним изображением для тестирования. поэтому мне все время приходилось отменять. Есть идеи? Спасибо.
Мой код (адаптировано из: https://stackoverflow.com/a/73001568/22028468):
from email.message import EmailMessage
from email.utils import make_msgid
import smtplib
import os
import ssl
import requests
import imghdr
import io
import time
start_time = time.time()
# Define these once; use them twice!
email_sender = 'chris@gmail.com'
email_receiver = 'chris@gmail.com'
email_password = 'aaaa aaaa aaaa aaaa'
subject = 'Test run HTML multiple images using URLs'
folder_path = r'C:\Users\chris\OneDrive\My Computer\Reddit API\cats\images'
# create a dict called plots containing image name and location
plots = {}
# [:1] to limit to 1 image for now
for file_name in os.listdir(folder_path)[:1]:
file_path = os.path.join(folder_path, file_name)
plots[file_name] = file_path
print(f'{file_name}. {file_path}')
# empty list to host dict of each image info - name, content, type, content id
imgs = []
# generate name, the content and the id
for image_name, image_location in plots.items():
with open(image_location, 'rb') as img:
image_data = img.read()
if image_name.endswith('png'):
image_type = 'png'
elif image_name.endswith('jpeg') or image_name.endswith('jpg'):
image_type = 'jpg'
imgs.append({
"name": image_name,
"data": image_data,
"type": image_type,
"cid": make_msgid().strip("")
})
# create html content template for the subsequent msg base
html = """\
Plots
Your Plots
Dear Victim,
Here are today's plots.
- """
for img in imgs:
html += f' -
[img]cid:{img[[/img]
\n'
html += """\
"""
msg = EmailMessage()
msg['Subject'] = subject #time
msg['From'] = email_sender
msg['To'] = email_receiver
msg.set_content(html, subtype="html")
# add image content to the msg base
for img in imgs:
msg.add_related(
img["data"], "image", img['type'],
cid=f'')
# send the email
# with smtplib.SMTP(host) as s:
# s.send_message(msg)
context = ssl.create_default_context()
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context = context) as smtp:
smtp.login(email_sender, email_password)
smtp.sendmail(email_sender, email_receiver, msg)
print('Email sent successfully')
except Exception as e:
print(f'Failed to send due to {e}')
end_time = time.time()
print(f'The script runs for {(end_time - start_time)/3600} hours.')
Подробнее здесь: https://stackoverflow.com/questions/787 ... super-long