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

问题描述 投票:0回答:1

我想定期从我的raspberry pi发送电子邮件,并附加一个小的excel文件。对于这一点,我使用我的一个Gmail帐户。我可以发送电子邮件,但不是附加的东西。

下面这几行有问题:SendMail.prepareMail(...)andpart.set_payload(os.open(file), "rb").read()) -> 这是我得到的错误 "IsADirectoryError: [Errno 21] 是一个目录:''我希望你能帮助我。

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 = '[email protected]'
  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("[email protected]", "[email protected]", "[email protected]", "Titel 1", "/home/pi/Desktop/Teststand/export/protokoll/Protokoll04_May_2020.xlsx")
python linux email smtp filepath
1个回答
0
投票

你正在使用for循环迭代变量attachments,这是一个字符串。所以现在for file in attachment意味着文件将包含 attachments 字符串中的每个字符。试试。

SendMail.prepareMail("[email protected]", "[email protected]", "[email protected]", "Titel 1", ["/home/pi/Desktop/Teststand/export/protokoll/Protokoll04_May_2020.xlsx"])

把 attachments 的值传给一个列表。所以当你在attachments中执行for file时,file的值将等于所需的位置字符串。

© www.soinside.com 2019 - 2024. All rights reserved.