我已经查看了许多教程,以及有关堆栈溢出的其他问题,文档和说明至少是,只是无法解释的代码.我想发送一个我已压缩的文件,并将其作为附件发送.我已经尝试复制和粘贴提供的代码,但它不起作用,因此我无法解决问题.
所以我要问的是,如果有人知道谁解释smtplib以及电子邮件和MIME库如何协同发送文件,更具体地说,如何使用zip文件.任何帮助,将不胜感激.
这是每个人都提到的代码:
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
def send_file_zipped(the_file, recipients, sender='you@you.com'):
myzip = zipfile.ZipFile('file.zip', 'w')
# Create the message
themsg = MIMEMultipart()
themsg['Subject'] = 'File %s' % the_file
themsg['To'] = ', '.join(recipients)
themsg['From'] = sender
themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(zf.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment',
filename=the_file + '.zip')
themsg.attach(msg)
themsg = themsg.as_string()
# send the message
smtp = smtplib.SMTP()
smtp.connect()
smtp.sendmail(sender, recipients, themsg)
smtp.close()
Run Code Online (Sandbox Code Playgroud)
我怀疑问题是这个代码也拉链了一个文件.我不想拉链,因为我已经有了一个我想发送的压缩文件.在任何一种情况下,这个代码都没有很好的文档和python库本身,因为它们没有提供任何过去的img文件和文本文件的洞察力.
更新:我现在得到的错误.我还用上面的代码更新了我文件中的内容
Traceback (most recent call last):
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 100, in <module>
send_file_zipped('hw5.zip', 'avaldez@oswego.edu')
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 32, in send_file_zipped
msg.set_payload(myzip.read())
TypeError: read() takes at least 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
我真的没有看到问题.只需省略创建zip文件的部分,而只需加载您拥有的zip文件即可.
基本上,这部分在这里
msg = MIMEBase('application', 'zip')
msg.set_payload(zf.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment',
filename=the_file + '.zip')
themsg.attach(msg)
Run Code Online (Sandbox Code Playgroud)
创建附件.该
msg.set_payload(zf.read())
Run Code Online (Sandbox Code Playgroud)
设置,以及从文件中读取的附件的有效负载zf(可能意味着zip文件).
只需事先打开您的zip文件,然后从中读取该行.
| 归档时间: |
|
| 查看次数: |
15166 次 |
| 最近记录: |