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

2024-04-25 04:47:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

以下线路有故障: SendMail.prepareMail(…) 和 part.set_有效负载(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 = '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")

Tags: tofromimportselfserverosemailmsg
1条回答
网友
1楼 · 发布于 2024-04-25 04:47:48

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

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

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

相关问题 更多 >