正在通过 python 从我的 raspberry pi 发送电子邮件

Sending an email via python from my raspberry pi

id 喜欢定期从我的 raspberry pi 发送带有一个小附加 excel 文件的电子邮件。为此,我使用我的 gmail 帐户。我可以发送电子邮件,但不能附加任何内容。

以下这些行是错误的: SendMail.prepareMail(…) 和 part.set_payload(os.open(file), "rb").read()) -> 这是我得到的错误“IsADirectoryError: [Errno 21] Is a directory: '/' 我希望你能帮助我

import sys, smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders

class SendMail(object):
  mailadress = 'teststand@gmail.com'
  smtpserver = 'smtp.googlemail.com'
  username = 'xxx'
  password = 'xxx'

def send(self, files):
  # Gather information, prepare mail
  to = self.mailadress
  From = self.mailadress
  #Subject contains preview of filenames
  if len(files) <= 3: subjAdd = ','.join(files)
  if len(files) > 3: subjAdd = ','.join(files[:3]) + '...'
  subject = 'Dateiupload: ' + subjAdd
  msg = self.prepareMail(From, to, subject, files)

#Connect to server and send mail
  server = smtplib.SMTP(self.smtpserver)
  server.ehlo() #Has something to do with sending information
  server.starttls() # Use encrypted SSL mode
  server.ehlo() # To make starttls work
  server.login(self.username, self.password)
  failed = server.sendmail(From, to, msg.as_string())
  server.quit()

def prepareMail(self, From, to, subject, attachments):
    msg = MIMEMultipart()
    msg['From'] = From
    msg['To'] = to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

# The Body message is empty
msg.attach( MIMEText("") )

for file in attachments:
  #We could check for mimetypes here, but I'm too lazy
  part = MIMEBase('application', "octet-stream")
  part.set_payload( open(os.open(file),"rb").read() )
  Encoders.encode_base64(part)
  part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
  msg.attach(part)
  #Delete created Tar
return msg

if __name__ == '__main__':
  mymail = SendMail()
  # Send all files included in command line arguments
  mymail.send(sys.argv[1:])

SendMail.prepareMail("teststand@gmail.com", "teststand@gmail.com", "empfanger@gmx.de", "Titel 1", "/home/pi/Desktop/Teststand/export/protokoll/Protokoll04_May_2020.xlsx")

您正在使用 for 循环遍历变量附件,它是一个字符串。所以现在对于附件中的文件意味着文件将包含字符串附件中的每个字符。
尝试:

SendMail.prepareMail("teststand@gmail.com", "teststand@gmail.com", "empfanger@gmx.de", "Titel 1", ["/home/pi/Desktop/Teststand/export/protokoll/Protokoll04_May_2020.xlsx"])

传递列表中附件的值。因此,当您对附件中的文件执行操作时,文件的值将等于所需的位置字符串。