zoukankan      html  css  js  c++  java
  • 邮件模块

    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()
  • 相关阅读:
    HashMap和Hashtable的区别
    装箱以及拆箱
    泛型
    LinkedList和ArrayList异同
    ArrayList的输出方式以及ArrayList的因子增长数
    limit的优化
    mysql五大数据引擎的分别
    ios
    css3(1)
    php
  • 原文地址:https://www.cnblogs.com/dxnui119/p/13356648.html
Copyright © 2011-2022 走看看