python脚本实现定时发送邮件

# -*-encoding: utf-8 -*-
"""
@version: 3.6
@time: 2018/6/9 10:16
@author: SunnyYang
"""
import os,sys
import datetime
import smtplib
import traceback

from email.header import Header
from email.utils import parseaddr,formataddr
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders



# 对名字前面的中文进行处理
def _format_addr(s):
    name,addr = parseaddr(s)
    print(name)  #Python爱好者ii
    print(addr)   #[email protected]
    return formataddr((Header(name,'utf-8').encode(),addr))

def send_email(to_str_in,file_path):
    #配置邮件的发送和接受人
    from_str = 'Wan***@163.com'   #发送邮件人的邮箱地址
    password = '******'  #邮箱的客户端授权码,不是邮箱的登录密码
    smtp_server = 'smtp.163.com' #163邮箱的服务器地址
    to_addr = to_str_in    #邮件的接收人
    to_addr = to_addr.split(',')  #多个邮件接收人用逗号分隔

    #邮件发送人和接受人信息
    msg = MIMEMultipart()
    msg['From'] = _format_addr('张雪<%s>' % from_str)
    msg['To'] = ",".join(to_addr)
    msg['Subject'] = Header('hi,zhangxue','utf-8').encode()

    #邮件的内容和附件添加
    filepath = file_path
    r = os.path.exists(filepath)
    if r is False:
        msg.attach(MIMEText('No file','plain','utf-8'))
    else:
        msg.attach(MIMEText('send with file','plain','utf-8'))
        pathdir = os.listdir(filepath)
        for alldir in pathdir:
            child = os.path.join(filepath,alldir)
            print(alldir)
            print(child)  #F:\automailtest\test.txt
            # if os.path.splitext(child)[1] == '.txt':
            # print(child.decode('gbk'))  #解决中文显示乱码的问题
#添加附件,就是加一个MIMEBase
            # mime = MIMEBase('file','txt',filename='shujutuwen')
            mime = MIMEBase('application', 'octet-stream')
#这三行是必须要加上的,否则附件的名字就会以.bin的形式存在,而不是原来文件的名字
            mime.add_header('Content-Disposition', 'attachment', filename=alldir)  #alldir是附件的名字
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            mime.set_payload(open(child,'rb').read()) #读取附件内容
            encoders.encode_base64(mime) #编码方式
            msg.attach(mime)
    current_time = datetime.datetime.now().weekday()+1   #周一是0,周五是4
    if current_time == 5:   #设置如果是周五的话就发送邮件
        try:
            server = smtplib.SMTP(smtp_server, 25)
            server.set_debuglevel(1)  # 用于显示邮件发送的执行步骤
            server.login(from_str, password)
            server.sendmail(from_str, to_addr, msg.as_string())
            server.quit()
        except Exception as e:
            print('send failed')
            print(traceback.format_exc())

if __name__ == '__main__':
    send_email('[email protected],[email protected]', 'F:\\automailtest')
   #参考  https://www.cnblogs.com/changbo/p/5372932.html

猜你喜欢

转载自blog.csdn.net/WxyangID/article/details/80633534