Use Python scripts to automatically take pictures after the computer wakes up, take screenshots and send email notifications

This article was last updated on: February 7, 2024 pm

background

The background is this, my home desktop is perennial dormancy, and configured Wake On Lan (WOL) Easy to wake up and use remotely.

But I found that occasionally the desktop would wake up by other situations, which I didn’t know at this time, and ended up running for days in vain, wasting a lot of power.

So my needs are this:

🤔 The computer wakes upAfter (it may be booted, it may be woken up from hibernation), it automatically does the following:

  1. Camera to take pictures (to determine if someone is using it)
  2. Screenshot (to determine if someone is using it)
  3. Generate an email telling me “Computer is started” with photos and screenshots;
  4. Send to my mailbox.

Concrete implementation

📷️ Camera to take pictures

✨ Overview:

Pass opencv-python Package implementation.

The specific package name is: opencv-python

depend numpy

So the installation command is:

1
2
python -m pip install numpy
python -m pip install opencv-python

Then the import statement is: import cv2

The source code is as follows:

1
2
3
4
5
6
7
8
9
# 打开摄像头并拍照 
cap = cv2.VideoCapture(0) # 0 表示打开 PC 的内置摄像头(若参数是视频文件路径则打开视频)
# 按帧读取图片或视频
# ret,frame 是 cap.read() 方法的两个返回值。
# 其中 ret 是布尔值,如果读取帧是正确的则返回 True,如果文件读取到结尾,它的返回值就为 False。
# frame 就是每一帧的图像,是个三维矩阵。
ret, frame = cap.read() # 按帧读取图片
cv2.imwrite('p1.jpg', frame) # 保存图像
cap.release() # 释放(关闭) 摄像头

🎨 Screenshot

✨ Overview:

Pass pyautogui Package implementation.
Reference Documentation: 4 ways to get screenshots in Python

pyautogui is relatively simple, but you can’t specify the window to get the program, so the window can’t be occluded, but you can specify the location of the screenshot, 0.04s a screenshot, slightly slower than PyQt, but also fast.

1
2
3
4
5
6
7
import pyautogui
import cv2


# 截图
screen_shot = pyautogui.screenshot()
screen_shot.save('screenshot.png')

📧 Write a message

✨ Overview:

Pass email Package implementation.

MIMEMultipart type

The different types of content in MIME messages are stored in segments, and the arrangement of each segment and location information are passed Content-Type domain multipart type to define. multipart There are three main subtypes of types:

  • mixed :annex
  • alternative : Plain text and hypertext content
  • related : Inline resources. For example, when sending email content in HTML format, an image may be used as the background of HTML, and HTML text will be stored alternative section, and the image as the background is stored related A segment of the type definition

The specific source code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage


sender = '[email protected]' # 发件人
receivers = '[email protected]' # 收件人
pw = 'p@ssw0rd' # 三方客户端登录邮箱授权码
subject = ' 电脑已启动拍照并发送 ' # 邮件主题
text = ' 您好,您的电脑已开机,并拍摄了如下照片:' # 邮件正文

msg = MIMEMultipart('mixed') # 定义含有附件类型的邮件
msg['Subject'] = subject # 邮件主题
msg['From'] = sender # 发件人
msg['To'] = receivers # 收件人
# MIMEText 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
# 构造一个文本邮件对象, plain 原格式输出; html html 格式输出
text = MIMEText(text, 'plain', 'utf-8')
msg.attach(text) # 将文本内容添加到邮件中

for i in ('p1.jpg', 'screenshot.png'):
sendImg = open(i, 'rb').read() # 读取刚才的图片
img = MIMEImage(sendImg) # 构造一个图片附件对象
# 指定下载的文件类型为:附件, 并加上文件名
img['Content-Disposition'] = 'attachment; filename={}'.format(i)
msg.attach(img) # 将附件添加到邮件中

msg_tsr = msg.as_string() # 将 msg 对象变为 str

📤️ Send an email

✨ Overview:

Pass smtplib Package implementation.

The source code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import smtplib


# 发送邮件
try:
smtp = smtplib.SMTP() # 定义一个 SMTP(传输协议) 对象
smtp.connect('smtp.example.com', 25) # 连接到邮件发送服务器, 默认 25 端口
smtp.login(sender, pw) # 使用发件人邮件及授权码登陆
smtp.sendmail(sender, receivers, msg_tsr) # 发送邮件
smtp.quit() # 关闭邮箱,退出登陆
except Exception as e:
print('\033[31;1m 出错了:%s\033[0m' % (e))
else:
print(' 邮件发送成功!')

⏰ A Python script is triggered after the desktop wakes up

🗔 Windows scripts

The Windows bat script is as follows:

1
2
3
4
@echo off
timeout /T 15 /NOBREAK # sleep 15s
cd /d D:\scripts\auto_send_email
python auto_email.py # 执行 py 文件

⏰ Task scheduler

enter Computer management -> System tools -> Task scheduler. Add the following task schedule:

  • Security options:
    • ✔️Check: 不管用户是否登录都要运行
    • ✔️Check: 使用最高权限运行
  • Trigger:
    • 发生事件时
    • Log: 系统
    • Source: Power-Troubleshooter
    • Event ID: 1
  • Action: Start the program: D:\scripts\auto_email.bat

🎉🎉🎉Finish!

最终效果展示


Use Python scripts to automatically take pictures after the computer wakes up, take screenshots and send email notifications
https://e-whisper.com/posts/4384/
Author
east4ming
Posted on
September 27, 2021
Licensed under