美文网首页小资料工程师乐园
python: smtplib使用实例

python: smtplib使用实例

作者: luffynoonepiece | 来源:发表于2020-11-12 14:38 被阅读0次

    导入依赖

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.application import MIMEApplication
    from email.header import Header
    

    正文及寄送和接收者

    msg = MIMEMultipart()
    text = '正文'
    sender = 'XXX@YY.com'
    receivers = ['XXXX@YY.com']
    content = MIMEText(text)
    
    msg['From'] = Header(sender, 'utf-8')
    msg['To'] = Header('XXXX', 'utf-8') # 这里是信件里收件者栏位的内容,并非显示真实的收件者
    subject = '主题'
    msg['Subject'] = Header(subject, 'utf-8')
    
    # 下面是文字部分,也就是纯文本
    puretext = MIMEText(text)
    msg.attach(puretext)
    
    # 添加Excel附件
    xlsxpart = MIMEApplication(open(path, 'rb').read())
    xlsxpart["Content-Type"] = 'application/octet-stream'
    xlsxpart.add_header('Content-Disposition', 'attachment', filename=path)
    msg.attach(xlsxpart)
    

    寄送信件

    try:
        client = smtplib.SMTP()
        client.connect('xxx@yy.com', 25) # 参数是SMTP 服务器主机以及默认端口25
        # 注意:有些服务器需要login
        client.sendmail(sender, receivers, msg.as_string())
        client.quit()
        print('带有各种附件的邮件发送成功。')
    except smtplib.SMTPRecipientsRefused:
        print('Recipient refused')
    except smtplib.SMTPAuthenticationError:
        print('Auth error')
    except smtplib.SMTPSenderRefused:
        print('Sender refused')
    except smtplib.SMTPException as e:
        print(e) 
    
    蟹蟹.jpg

    相关文章

      网友评论

        本文标题:python: smtplib使用实例

        本文链接:https://www.haomeiwen.com/subject/hvhpbktx.html