V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Ctry
V2EX  ›  Python

python3 SMTP 发送邮件时用到的 email 模块的一个疑问,求大神指教!

  •  
  •   Ctry · 2018-01-23 15:59:26 +08:00 · 2949 次点击
    这是一个创建于 2257 天前的主题,其中的信息可能已经有所发展或是发生改变。

    首先导入各模块: import smtplib from email.mime.text import MIMEText from email.header import Header

    然后创建 MIMEText 对象: msg = MIMEText('Python3 邮件发送测试', 'plain', 'utf-8')

    之后是设置三个头部信息:From、To、Subject。

    最后创建 SMTP 对象后使用 SMTP.sendmail(sender, receivers, msg.as_string())方法发送。

    问题就是: 发送邮件时使用了 msg.as_string()方法将 MIMEText 对象转化成字符串。但是 as_string()方法是 Message 类定义的方法,为什么这里 MIMEText 对象也可以使用该方法?我查询后并没有直接的继承关系。

    有没有知道的大神,指教一下,万分感谢!

    11 条回复    2018-01-24 10:49:13 +08:00
    Ctry
        1
    Ctry  
    OP
       2018-01-23 16:16:38 +08:00
    有没有人了解的,或者知道相关资料的?感谢告知!
    cxh116
        2
    cxh116  
       2018-01-23 16:17:06 +08:00
    import email.mime.text
    import inspect
    print(inspect.getmro(email.mime.text.MIMEText))


    (<class 'email.mime.text.MIMEText'>, <class 'email.mime.nonmultipart.MIMENonMultipart'>, <class 'email.mime.base.MIMEBase'>, <class 'email.message.Message'>, <class 'object'>)


    其实直接翻源码最快. /usr/lib/python3.6/email
    cxh116
        3
    cxh116  
       2018-01-23 16:19:29 +08:00
    用 inspect 模块分析, 没有直接继承,但有间接.

    源码地址 https://github.com/python/cpython/blob/master/Lib/email/mime/text.py
    keithszc
        4
    keithszc  
       2018-01-23 16:23:57 +08:00
    用 pycharm 查了一下,3 次继承就到了 Message 类
    Ctry
        5
    Ctry  
    OP
       2018-01-23 16:25:34 +08:00
    @cxh116 感谢感谢!我知道了,原来是 mro 列表中有 Message 类。哎,自己不知道 inspect 模块相关用法,学习了。谢谢!
    Ctry
        6
    Ctry  
    OP
       2018-01-23 16:26:42 +08:00
    @keithszc 感谢!我知道了
    zhengxiaowai
        7
    zhengxiaowai  
       2018-01-23 16:56:58 +08:00
    smtplib 这种古董到老掉牙的库,接口及其难用,快放弃。

    使用 yagmail 优美的发送邮件
    Ctry
        8
    Ctry  
    OP
       2018-01-23 17:31:59 +08:00
    @zhengxiaowai 可以,我先把标准库了解了解,然后去学习第三方库。
    weyou
        9
    weyou  
       2018-01-23 21:27:19 +08:00 via Android
    @zhengxiaowai 这个只能发 Gmail 吧
    MyDaLin
        10
    MyDaLin  
       2018-01-24 09:16:20 +08:00
    我是来学习的
    Ctry
        11
    Ctry  
    OP
       2018-01-24 10:49:13 +08:00
    @MyDaLin 一起学习。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2780 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:31 · PVG 20:31 · LAX 05:31 · JFK 08:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.