私は多くのチュートリアルと、スタックオーバーフローに関する他の質問に目を通しました。ドキュメントと説明は少なくとも、説明のつかないコードです。圧縮済みのファイルを添付ファイルとして送信したいと考えています。提供されたコードをコピーして貼り付けようとしましたが、機能しないため、問題を修正できません。
だから私が尋ねているのは、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()
問題は、このコードがファイルも圧縮していることだと思います。送信したい圧縮ファイルが既にあるので、何も圧縮したくありません。どちらの場合も、このコードは、過去の img ファイルやテキスト ファイルに関する洞察を提供しないため、Python ライブラリ自体と同様に文書化が不十分です。
更新: エラーが発生しています。上記のコードでファイルの内容も更新しました
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)