• 邮件模块


    SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

    Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。

    用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息。SMTP协议就是简单的文本命令和响应。

    login()方法用来登录SMTP服务器,sendmail()方法就是发邮件,由于可以一次发给多个人,所以传入一个list,邮件正文是一个str,as_string()把MIMEText对象变成str。

    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    
    sender = 'test@xx.com'
    receiver = ['xx1@126.com','xx2@126.com']
    subject = 'test'
    smtpserver = 'mail.xx.com'
    smtpport = 25
    username = 'user1@xx.com'
    password = 'password123'
    context = 'haha'

    构造MIMEText对象时,第一个参数就是邮件正文,第二个参数是MIME的subtype,传入'plain',最终的MIME就是'text/plain',使用utf-8编码。

    msg = MIMEText(context, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    
    smtp = smtplib.SMTP()
    
    smtp.connect(smtpserver,smtpport)
    smtp.set_debuglevel(1) 
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
  • 相关阅读:
    css 深入理解
    2018 web经典面试题
    CSS 居中布局
    HTTP首部解析
    http状态码有那些?分别代表是什么意思?
    基本HTTP协议流程是什么?
    JS-变量
    javascript基础1
    css3弹性盒模型(Flexbox)
    文字效果和颜色
  • 原文地址:https://www.cnblogs.com/dxnui119/p/13356648.html
Copyright © 2020-2023  润新知