把当前工作目录中的内容压缩成ZIP文件发送给别人,可以快速和朋友共享文件。
如果设备中没有安装任何邮件服务器,需要安装一个本地邮件服务器,例如postfix。
在Debian/Ubuntu系统中可以使用apt-get的默认设置安装,如下面的命令所示:
$ sudo apt-get install postfix
首先要压缩当前目录,然后创建一封电子邮件。电子邮件可通过外部的SMTP主机发送,也可使用本地电子邮件服务器发送。发件人和收件人信息都从命令行参数中获取。
import os
import argparse
import smtplib
import zipfile
import tempfile
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
def email_dir_zipped(sender, recipient):
zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')
zip = zipfile.ZipFile(zf, 'w')
print("Zipping current dir: {}".format(os.getcwd()))
for file_name in os.listdir(os.getcwd()):
zip.write(file_name)
zip.close()
zf.seek(0)
# Create the message
print("Creating email message...")
email_msg = MIMEMultipart()
email_msg['Subject'] = 'File from path {}'.format( os.getcwd()))
email_msg['To'] = ', '.join(recipient)
email_msg['From'] = sender
email_msg.preamble = 'Testing email from Python.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(zf.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=os.getcwd()[-1] + '.zip')
email_msg.attach(msg)
email_msg = email_msg.as_string()
# send the message
print("Sending email message...")
try:
smtp = smtplib.SMTP('localhost')
smtp.set_debuglevel(1)
smtp.sendmail(sender, recipient, email_msg)
except Exception as e:
print("Error: {}".format(str(e)))
finally:
smtp.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Email Example')
parser.add_argument('--sender', action="store", dest="sender", default='you@you.com')
parser.add_argument('--recipient', action="store", dest="recipient")
given_args = parser.parse_args()
email_dir_zipped(given_args.sender, given_args.recipient)