Python嵌入HTML图片发送邮件耗时过长问题及解决方法
Python嵌入图片发送邮件卡顿问题解决
问题场景
作为Python新手,我需要实现读取指定文件夹内的图片并将其嵌入邮件发送的功能。但测试仅处理1张图片时,程序运行5分钟仍未完成,只能手动终止。
解决方案
在smtp.sendmail()函数的第三个参数msg后添加.as_string()方法,将EmailMessage对象转换为字符串格式后再发送,解决了程序卡顿的问题。
完整代码
from email.message import EmailMessage from email.utils import make_msgid import smtplib import os import ssl import requests import io import time start_time = time.time() # 配置邮箱信息 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' plots = {} for file_name in os.listdir(folder_path)[:3]: file_path = os.path.join(folder_path, file_name) plots[file_name] = file_path print(f'{file_name}. {file_path}') # 收集图片数据、类型和CID imgs = [] 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("<>") }) # 构建HTML邮件内容,嵌入图片占位符 html = """\ <html><head><title>Plots</title></head> <body> <h1>Your Plots</h1> <p>Dear Victim,</p> <p>Here are today's plots. <ul> """ for img in imgs: html += f' <li><img src="cid:{img["cid"]}" style="max-width: 500px; height: auto;" alt="{img["name"]}" /></li>\n\n' html += """\ </ul> </p> <p>Plot to take over the world!</p> </body> </html> """ print('\n\nhtml template:\n\n') print(html) # 创建邮件对象并配置内容 msg = EmailMessage() msg['Subject'] = subject msg['From'] = email_sender msg['To'] = email_receiver msg.set_content(html, subtype="html") # 将图片添加为邮件关联内容 for img in imgs: msg.add_related( img["data"], "image", img['type'], cid=f'<{img["cid"]}>') # 发送邮件 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.as_string()) 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)/60} minutes.')
内容的提问来源于stack exchange,提问作者chris nguyen
相关产品推荐
相关产品推荐

