2008-10-03 184 views

回答

20

可以使用zipfile模塊使用zip標準來壓縮文件時, email模塊創建附件的電子郵件,smtplib模塊發送它 - 全部只使用標準庫。

Python的 - 有電池

如果你不喜歡編程,寧願問上stackoverflow.org一個問題,而不是,或(如意見提出)不放過homework標籤,那麼,它在這裏是:

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='[email protected]'): 
    zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip') 
    zip = zipfile.ZipFile(zf, 'w') 
    zip.write(the_file) 
    zip.close() 
    zf.seek(0) 

    # 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() 

有了這個功能,你可以做:

send_file_zipped('result.txt', ['[email protected]']) 

不客氣。

+1

這是一個答案。 – 2008-10-04 00:51:59

1

查看zipfile壓縮文件夾及其子文件夾。

查看電子郵件客戶端的smtplib

0

您可以使用zipfile附帶Python和here你可以找到帶有附件與標準的smtplib發送電子郵件的例子