PYTHON实现自动发送邮件

纯个人记录使用,如有侵权请联系我删除

会用到smtplib 跟email,因为具体使用方法可以百度

源码

def send_eamil(receiver):
    global msg
    sender = '***@163.com'
    psd = '***'    #是授权密码不是邮箱登录密码
    mail_host='smtp.163.com'
    subject='资源'
    to_addrs=receiver.split(',')
    #创建带附件的实例
    msg=MIMEMultipart()
    msg['Subject']=Header(subject,'utf-8')
    msg['from']=Header(sender,'utf-8')
    msg['To']=",".join(to_addrs)      #多个收件人
    #创建正文,把文本添加到msg类中
    msg.attach(MIMEText('资源,请查看附件','plain','utf-8'))
    #构造附件
    file_path='文件路径'
    att1=MIMEText(open(file_path,'rb').read(),
                  'base64','utf-8')
    #att1["Content-Type"]='application/octet-stream;name=%s'%Header(filename,'utf-8').encode('utf-8')         #与下边功能一致
    #att1["Content-Disposition"]='attachment;file_name=%s'%Header('%s'%filename,'utf-8').encode('utf-8')      #与下边功能一致
    att1.add_header('Content-Disposition', 'attachment', filename=名字随便起)#没有这三行会出现文件结尾变成bin现象
    att1.add_header('Content-ID', '<0>')
    att1.add_header('X-Attachment-Id', '0')
    msg.attach(att1)#将附件添加到类文件
    try:
        smtp=smtplib.SMTP()
        smtp.set_debuglevel(1)  #显示发送过程
        smtp.connect(mail_host)
        smtp.login(sender,psd)
        smtp.sendmail(sender,to_addrs,msg.as_string())
        smtp.quit()
        print('发送成功')
    except Exception as result:
        print('发送失败,异常为%s'%result)

if __name__ == '__main__':
    make_excel()
    send_eamil('***@qq.com,*@126.com')

遇到的问题

1.出现554错误:由于网易机制问题,需要开启授权码,设置好就行了

2.发出的附件出现后缀为bin的现象是因为没加header以下是例子,代码也有标注,两种方式都行,个人喜欢简短一些的

name.add_header('Content-Disposition', 'attachment', file_name='C:/Users/yue.sun/Desktop/自己/py/工作/逸云节点.xls')

name.add_header('Content-ID','<0>')

name.add_header('X-Attachment-Id', '0')

代码内容借鉴这位的

https://blog.csdn.net/u012209894/article/details/78414638

猜你喜欢

转载自blog.csdn.net/dhshttgb/article/details/85070921