python 邮件备份脚本

由于用了个新 vps,需要重新设置备份,此前的香港 vps 一直不知为何发不出去邮件,只好用百度云同步,但是这次偶然发现 python 的邮件类库比 php 要好用得多,于是尝试了一下 python 来做这个工作。

不过有一点美中不足是附件如果是中文名,则在 qq 邮箱的网页版会显示为乱码,相当费解(在 Foxmail 客户端以及 163 的网页版都显示正常)

直接上代码吧,一切尽在不言中。

mark 1: http://www.cnblogs.com/lonelycatcher/archive/2012/02/09/2343480.html mark 2: http://www.douban.com/group/topic/40848076/

import smtplib import sys import os from email.header import Header from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email import encoders

def send_mail(to_list, sub, content): me=mail_user+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEMultipart('related') msg['Subject'] = sub msg['From'] = me msg['To'] = to_list msg.attach(MIMEText(content, 'plain')) for att_path in attaches: if os.path.exists(att_path):

        fp = open(att_path, 'rb') 
        attach = MIMEBase('application', "octet-stream") 
        attach.set_payload(fp.read()) 
        fp.close() 
        encoders.encode_base64(attach) 
        basename=os.path.basename(att_path) 
        attach.add_header("Content-Disposition","attachment",filename=basename) 
        msg.attach(attach)
        continue

        fname = os.path.basename(att_path)
        attach = MIMEText(open(att_path, 'rb').read(), 'base64', 'utf-8')
        attach["Content-Type"] = 'application/octet-stream'
        attach.add_header("Content-Disposition", "attachment", filename = fname)
        msg.attach(attach)
try:
    s = smtplib.SMTP()
    s.connect(mail_host)
    s.login(mail_user,mail_pass)
    #print(msg.as_string())
    s.sendmail(me, to_list, msg.as_string())
    s.close()
    print('The mail was sent successfully!')
    return True
except Exception as e:
    print('It seemed some error occured.')
    print(str(e))
    return False

""" Configuration part """

sender configuration

mail_host="smtp.163.com" mail_user="ldsvc02" mail_pass="mypass" mail_postfix="163.com"

attachment list

attaches = ( #'d:/backup/data/vps_20140208.rar', sys.argv[2], )

target emails

receivers = ( 'backup201301@163.com', #'ycloud01@163.com', #'ldsvc01@163.com', )

action

if name == 'main': for rcv in receivers: print('Attempting to send to %s' % rcv) subj = 'python backup' if len(sys.argv) > 1: subj = sys.argv[1] send_mail(rcv, subj, 'vps backup')


【转载请附】愿以此功德,回向 >>

原文链接:http://www.huangwenchao.com.cn/2014/02/py-mail-backup.html【python 邮件备份脚本】

发表评论

邮箱地址不会被公开。 必填项已用*标注