zoukankan      html  css  js  c++  java
  • python模块----yagmail模块、smtplib模块 (电子邮件)

    yagmail模块

    python标准库发送电子邮件的模块比较复杂,so,许多开源的库提供了更加易用的接口来发送电子邮件,其中yagmail是使用比较广泛的开源项目,yagmail底层依然使用smtplib和email模块,但是提供了更好的接口,并具有更好的易读性。

    第一步:安装yagmail模块

    pip install yagmail
    

    第二步:发邮件

    #导入yagmail模块
    import yagmail
    
    #1.实例化出来一个yagmail对象
    yag = yagmail.SMTP(user='xxxx@163.com',password='xxxx',host='smtp.163.com')
    
    ##(可选)编写内容(其实contents就是一个变量)
    contents='hello world!!!'
    
    #2.发送邮件操作
    yag.send(to='接收端@163.com',subject=None,contents=contents)
    
    ##3.断开连接
    yag.close()
    

    拓展1:发送多个用户

    yag.send(to=['xx1.@163.com','xx2.@162.com'],subject=subject,contents)
    

    拓展2:发送附件

    contents=['邮件内容','附件路径']
    

    smtplib模块

    python发送邮件(不带附件)

    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    sender = 'xxxx@163.com'
    receiver = 'xxxxxx@126.com'
    subject = '报警'
    username = 'xxxx@163.com'
    password = 'xxxx'
    msg = MIMEText(strs, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = 'Tim<xxxx@163.com>'
    msg['To'] = "xxxxxx@126.com"
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    

    python发送邮件(带附件)

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.application import MIMEApplication
    
    USER = 'xxxx@163.com'
    PASSWORD = 'xxxxxx'
    # 如名字所示: Multipart就是多个部分
    msg = MIMEMultipart()
    HOST = 'smtp.163.com'
    msg['subject'] = 'test email from python'
    msg['to'] = 'xxxx@126.com'
    msg['from'] = 'xxxxxx@163.com'
    text = MIMEText('我是纯文本')
    msg.attach(text)
    #添加附件1
    xlsxpart = MIMEApplication(open('test1.xlsx', 'rb').read())
    xlsxpart.add_header('Content-Disposition', 'attachment', filename='test1.xlsx')
    msg.attach(xlsxpart)
    #添加附件2
    xlsxpart2 = MIMEApplication(open('test2.xlsx', 'rb').read())
    xlsxpart2.add_header('Content-Disposition', 'attachment', filename='test2.xlsx')
    msg.attach(xlsxpart2)
    #开始发送邮件
    client = smtplib.SMTP()
    client.connect(HOST)
    client.login(USER, PASSWORD)
    client.sendmail('xxxxx@163.com', ['xxxx@126.com'], msg.as_string())
    client.quit()
    print('发送成功........')
    
  • 相关阅读:
    GL线程
    Texture,TextureRegion,Sprite,SpriteBatch
    设置壁纸
    CentOS7下安装MySQL,修改端口
    读《大道至简》有感
    课程作业01汇总整理
    读《大道至简》有感(伪代码)
    01实验性问题总结归纳
    oracle日期时间的加减法
    C# 根据年、月、周、星期获得日期等
  • 原文地址:https://www.cnblogs.com/du-z/p/12834718.html
Copyright © 2011-2022 走看看