首页 > 解决方案 > 如何以 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)

标签: pythonpython-3.xpython-requests

解决方案


您将图像作为 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


推荐阅读