使用树莓派发送电子邮件时,您需要注册一个电子邮件账户并获取SMTP授权码,然后将其填写到相应的属性中。关于SMTP授权码的更多信息,请百度查询。使用此方法只需指定收件人电子邮件地址和要发送的内容即可。如果您想发送附件,请取消代码中注释的部分,将要发送的文件路径替换为您的文件路径,然后运行代码即可。代码如下:

import smtplib
import os
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

SMTP_SERVER = 'smtp.邮箱服务商.com'
SMTP_PORT = 587
SMTP_USERNAME = '您的邮箱账户'
SMTP_PASSWORD = '您的SMTP授权码'

def send_email(recipient, subject, body, attachment=None):
    msg = MIMEMultipart()
    msg['To'] = recipient
    msg['From'] = SMTP_USERNAME
    msg['Subject'] = subject
    msg.attach(MIMEText(body))
    if attachment:
        with open(attachment, 'rb') as f:
            att = MIMEApplication(f.read(), _subtype='octet-stream')
            att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment))
            msg.attach(att)
    server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    server.starttls()
    server.login(SMTP_USERNAME, SMTP_PASSWORD)
    server.sendmail(SMTP_USERNAME, recipient, msg.as_string())
    server.quit()

# 示例用法
recipient = 'recipient@example.com'
subject = '这是一封测试邮件'
body = '这是测试邮件的正文。'
attachment = '/home/pi/Desktop/2022Study/wifi.txt'
send_email(recipient, subject, body, attachment)