-2

i am make a python3 script that send the screenshoot to my mail after specific interval of time . But i am receiving the screenshoot in form of bsee64 not in png/jpg .pls Add that functionality to my code

Code is Here

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)
emma juila
  • 147
  • 1
  • 1
  • 11

1 Answers1

1

You are recieving the image as base64 encoded text because you have given the data in the message parameter which is where the body of the email is supposed to go.

I rewritten the code, and this should work for you without a problem :)

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)

Source: https://medium.com/better-programming/how-to-send-an-email-with-attachments-in-python-abe3b957ecf3

Siddharth Dushantha
  • 1,391
  • 11
  • 28
  • yes that works thanks.But it sending the screenshoot with previous attatchemnet also. mean to say email1(screenshoot1) email2(screenshoot1,screenshoot2) – emma juila May 23 '20 at 11:48