Fork me on github

python 自动打包,发送邮件(包括附件)至多个收件人(qq邮箱,163邮箱)

 

-----------------------------打包部分----------------------------------

 

```
import zipfile

def zipDir(dirpath, outFullName):
    zip = zipfile.ZipFile(outFullName, 'w', zipfile.ZIP_DEFLATED)
    for path, dirnames, filenames in os.walk(dirpath):
        this_path = os.path.abspath('.')
        fpath = path.replace(this_path, '')
        for filename in filenames:
            zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
    zip.close()
    
```

  

----------------------------发送邮件部分----------------------------------

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase #附件
from email.mime.text import MIMEText
from email import encoders #转码

def server_pre(msg):
    '''邮件服务器基础设置'''
    print('connecting :::::::::::::::')
    server = smtplib.SMTP_SSL('smtp.qq.com')
    # server.starttls()
    fromAddr = 'XXXXXXXX@qq.com'  # 发件人地址
    myPass = 'password'  # 发件人密码
    print('login :::::::::::::::')
    server.login(fromAddr, myPass)
    print('sending :::::::::::::::')
    server.sendmail(msg['From'], msg['To'].split(','),msg.as_string())
    print('quiting :::::::::::::::')
    server.quit()

def send_listing(zippedFn,subject,sendFn,to_adress_list):
    '''发送邮件'''
    global msg_list
    msg_list = MIMEMultipart()
    msg_list['From'] = 'YYYYYYYYYYY@qq.com'
    msg_list['To'] = ','.join(to_adress_list)
    print(msg_list['To'])
    msg_list['Subject'] = subject
    body = ''send py python'
    msg_list.attach(MIMEText(body))
    print('period 1 :::::::::::::::')
    with open(zippedFn,'rb') as f:
        #这里附件的MIME和文件名
        mime = MIMEBase('zip','zip',filename=sendFn)
        #加上必要的头信息
        mime.add_header('Content-Disposition','attachment',filename=('gb2312', '', sendFn))
        mime.add_header('Content-ID','<0>')
        mime.add_header('X-Attachment-Id','0')
        #把附件的内容读进来
        mime.set_payload(f.read())
        #用Base64编码
        encoders.encode_base64(mime)
        msg_list.attach(mime)
    print('period 2 :::::::::::::::')
    server_pre(msg_list)
    print(">> email send successfully !!")

  

posted @ 2020-04-20 18:47  斩羚_HermioneX  阅读(766)  评论(0编辑  收藏  举报