1

我是一名新程序员,已开始在 raspberry pi 4 4gb 上学习 python 代码。我目前正在尝试让 Pi 向我发送一封附有图片的电子邮件。该代码当前发送文本但不会发送文件。我附上了将发送电子邮件的代码。第 8 行在实际代码中有我的电子邮件密码,但为了我的帐户安全,我已经替换了它。这段代码是用 python 3.7.3 编写的。任何帮助将不胜感激。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

email_user = 'APResearch.test@gmail.com'
email_password = 'passsword goes here'
email_send = 'APResearch.test@gmail.com'

subject = 'subject'

msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject

body = 'Hi there, sending this email from Python!'
msg.attach(MIMEText(body,'plain'))

filename= '/home/pi/Desktop/intruder.jpg'
attachment  =open(filename,'rb')

part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)

msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login('APResearch.test@gmail.com','apresearch1')


server.sendmail('APResearch.test@gmail.com','APResearch.test@gmail.com','motion detected')
server.quit()
4

0 回答 0