smtp ssl模式邮件发送与附件添加

#!/usr/bin/python3
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header


def main():

    sender='1932390299@qq.com'
    receiverList=['1932390299@qq.com','1148750911@qq.com']
    user='1932390299@qq.com'
    emailPwd='gyuagsqxsnonhbhd' #授权码开启
    smtpServer='smtp.qq.com'
    commonPort=465
    emailTitle='Hello,World!'
    htmlPath=r'F:/eclipse/readme/readme_eclipse.html'
    attachPathList=[r'C:\Users\Administrator\PycharmProjects\Supro\src\logs\Info\20190328.log']
    emailChanel(sender,receiverList,user,emailPwd,smtpServer,commonPort,emailTitle,htmlPath,attachPathList)


def emailChanel(sender,receiverList,user,emailPwd,smtpServer,commonPort,emailTitle,htmlPath=None,attachPathList=None):
    multiPart=MIMEMultipart()
    multiPart['From']=sender
    multiPart['To']=','.join(receiverList)
    subject=emailTitle
    multiPart['Subject']=Header(subject,"utf-8")
    if os.path.isfile(htmlPath):
        if os.path.exists(htmlPath):
            pass
        else:
            raise IOError("htmlPath not exist")
    else:
        raise IOError("html path is not file..")
    emailBody=MIMEText(_text=open(htmlPath,'rb').read(),_subtype='html',_charset="utf-8")
    multiPart.attach(emailBody)
    if isinstance(attachPathList,list):
            for attachPath in attachPathList:
                if os.path.exists(attachPath):
                    pass
                else:
                    raise  IOError("attachPath not exist")
    else:
        raise TypeError("expected type is list,but get {}".format(type(attachPathList).__name__))
    for attachPath in attachPathList:
        attach=MIMEText(open(attachPath, 'rb').read(), 'base64', 'utf-8')
        attach["Content-Type"] = 'application/octet-stream'
        attach["Content-Disposition"] = 'attachment; filename="dailyLog.log"' # filename not strict
        multiPart.attach(attach)
    
    # ssl 协议安全发送
    smtp=smtplib.SMTP_SSL(host=smtpServer,port=commonPort)
    try:
    
        smtp.login(user,emailPwd)
        smtp.sendmail(sender,receiverList,multiPart.as_string())
    except smtplib.SMTPException as e:
        print("send fail",e)
    else:
        print("success")
    finally:
        try:
            smtp.quit()
        except smtplib.SMTPException:
            print("quit fail")
        else:
            print("quit success")
if __name__ == '__main__':
    main()

  

转载于:https://www.cnblogs.com/SunshineKimi/p/10629342.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值