我想定期发送电子邮件从我的覆盆子圆周率与一个小的附加excel文件。为此,我使用我的gmail帐户。我可以发电子邮件,但不能用附加的东西。
以下几行是错误的: SendMail.prepareMail(…)part.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 = '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")发布于 2020-05-07 07:53: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"])传递列表中附件的值。因此,在附件中处理文件时,文件的值将等于所需的位置字符串。
https://stackoverflow.com/questions/61651914
复制相似问题