最早原型参考骨头的BLOG上的文章,然后东抄西抄,自己整理一下,做备份用
现已改成完全能在linux, win下正常运行的脚本, 还未在FreeBSD下测试

#!/usr/bin/env python

#coding:utf-8

import tarfile
import smtplib
import datetime
import time
import os
import sys
import shutil
from email.Header import Header
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

source = ('iptables/','pf_server_scripts/')


target_dir = "./"

#cp_command = "cp -f %s %s" % (sys.argv[0], source[0])
for _dir in source:
if os.path.isdir(_dir):
print "cp -f %s %s" % (sys.argv[0], _dir)
shutil.copy(sys.argv[0], _dir)
else:
print "%s is not dir" % (_dir, )
#os.system(cp_command)



target = target_dir + "arch_firewall_iptables_" + time.strftime("%Y%m%d_%H%M") + ".tar.gz"
if os.path.exists(target):
print "remove %s" % (target,)
os.remove(target)

# tar_command = "tar -vczf %s %s" % (target, " ".join(source))
#
# if (os.system(tar_command) == 0):
# print "Successful backup to ", target
# #sys.exit(0)
# else:
# print "backup to %s FAILED " % (target,)
# sys.exit(1)
#
# yn= raw_input("need send mail? y or n ")
# if ((yn != "Y") and (yn != "y")):
# print "exit ..."
# sys.exit(0)
tar_gz = tarfile.open(target, "w:gz")
try:
for f in source:
tar_gz.add(f)
tar_gz.close()
except:
print "backup to %s FAILED " % (target,)
sys.exit(1)
print "Successful backup to ", target

now=datetime.datetime.now()
TITLE="iptables arch firewall( os platform = {platform} system type = {sys} {td} ) ".format( platform=sys.platform, sys=os.name, td=now.strftime("%Y-%m-%d %H:%M"))
print TITLE

USER="username"

PASSWD="passwd"
TO="username@163.com"
FROM="username@163.com"
CODEC='gb2312'

#
# print "I love {a}, {b}, and {c}".format(a="eggs", b="bacon", c="sausage")
#
# #msg = "To: %s\r\nFrom: %s\r\nSubject: MultiConf %s\r\n\r\nthis is msg body\r\n".format(TO, FROM, td.strftime("%Y_%m_%d"))
# msg = "To: {to}\r\nFrom: {From}\r\nSubject: MultiConf {date}\r\n\r\nthis is msg body\r\n".format(to=TO, From=FROM, date=td.strftime("%Y_%m_%d"))
# print "msg = ", msg
#
# s=smtplib.SMTP("smtp.163.com")
# s.login(USER, PASSWD)
# s.sendmail(FROM, TO, msg)
# s.quit()

msg = MIMEMultipart()

#FILE="send_mail.py"
FILE=target
att = MIMEText(open(FILE, 'rb').read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="{file_name}"'.format(file_name=FILE)
msg.attach(att)

msg['to'] = TO
msg['from'] = FROM
msg['subject'] = Header(TITLE , CODEC)
server = smtplib.SMTP('smtp.163.com')
server.login(USER, PASSWD)
server.sendmail(msg['from'], msg['to'], msg.as_string())
server.close
print "send mail date = ", now.strftime("%Y-%m-%d %H:%M")