2008-10-03 17 views
7

मैं एक फ़ोल्डर और उसके सभी उप-फ़ोल्डर/फ़ाइलों को संपीड़ित करना चाहता हूं, और ज़िप फ़ाइल को अनुलग्नक के रूप में ईमेल करना चाहता हूं। पायथन के साथ इसे हासिल करने का सबसे अच्छा तरीका क्या होगा?मैं एक फ़ोल्डर को कैसे संकुचित कर सकता हूं और पाइथन में संपीड़ित फ़ाइल को ईमेल कर सकता हूं?

उत्तर

20

आप जिप मानक का उपयोग कर फ़ाइल को संपीड़ित करने zipfile मॉड्यूल का उपयोग कर सकते हैं, अनुलग्नक के साथ ईमेल बनाने के लिए email मॉड्यूल, और smtplib मॉड्यूल इसे भेजने के लिए - सभी केवल मानक लाइब्रेरी का उपयोग करते हैं।

अजगर - बैटरियों शामिल

आप प्रोग्रामिंग की तरह महसूस नहीं करते हैं और नहीं बल्कि 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

यह एक उत्तर का नरक है। –

+0

क्या होगा यदि प्रश्नकर्ता होमवर्क टैग को छोड़ देता है? –

+0

चूंकि आपको उत्तर देने में परेशानी हो रही है, इसलिए ज़िप में एक निर्देशिका पेड़ जोड़ने के लिए अपना उत्तर संपादित करें, केवल एक फ़ाइल नहीं। – tzot

1

किसी फ़ोल्डर और उसके उपफोल्डर्स को संपीड़ित करने के लिए zipfile पर देखें।

ईमेल क्लाइंट के लिए smtplib पर देखें।

0

आप zipfile कि अजगर के साथ जहाजों का उपयोग कर सकते हैं, और here आप मानक smtplib साथ अनुलग्नकों के साथ एक ईमेल भेजने के लिए एक उदाहरण मिल सकते हैं

संबंधित मुद्दे