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
scienhub
V2EX  ›  Python

Python SMTP 使用 gmail 发信问题

  •  
  •   scienhub · 8 天前 · 785 次点击

    在使用 Python SMTP 模块发送邮件时候遇到奇怪的问题,请求大家帮助。

    通过网上搜索,找到两种方法:

    第一种方法:

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.ehlo()
    server.login('[email protected]', 'xxxyyyxxx')
    
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "ScienHub: free LaTeX collaboration platform"
    msg['From'] = formataddr((str(Header('ScienHub', 'utf-8')), '[email protected]'))
    
    server.sendmail(from_addr=msg.get('From'), to_addrs=[e], msg=msg.as_string())
    

    这种方法可以发信,但是收件人并没有在 Header 中的 to 中,而是被 Bcc 的。如下图所示,收件人邮箱地址并没有出现在 To 中。

    Imgur

    第二种方法

    # 前面代码都一样
    msg["To"] = formataddr((str(Header([email protected], 'utf-8')), [email protected]))
    server.send_message(msg)
    

    这种方法收信人邮箱地址会出现在 To 中,但是给一部分邮件地址发件时,会报这个错

    (550, b'5.7.1 This message is not RFC 5322 compliant. There are multiple To headers.\n5.7.1 To reduce the amount of spam sent to Gmail, this message has been\n5.7.1 blocked. For more information, go to\n5.7.1 https://support.google.com/mail/?p=RfcMessageNonCompliant and review\n5.7.1 RFC 5322 specifications. 41be03b00d2f7-6fede16ae31sm239645a12.28 - gsmtp')

    因为并不是给所有收件人发信都有这个错,因此我猜测这个是跟收件人相关的,而不是 Google 的 smtp 服务器报的错?

    看报错信息"reduce the amount of spam sent to Gmail"似乎是发给 gmail 的, 但是奇怪的是,此时的收件人并不是 gmail ,而是一个基于 outlook 的企业邮箱。

    所以说用 Python 发信时,有没有既能保证收件人地址出现在正确位置,又能保证送达率的方法呢?

    7 条回复    2024-06-13 16:33:09 +08:00
    renmu
        1
    renmu  
       7 天前 via Android
    尝试换一个成熟的三方库
    Sawyerhou
        2
    Sawyerhou  
       7 天前 via Android
    在方法一里加个 msg["to"] 试试?
    Sawyerhou
        3
    Sawyerhou  
       7 天前
    @Sawyerhou 同时把列表去掉,to_addrs=e ,如果只有一个收件人的话。
    ttttttttt
        4
    ttttttttt  
       7 天前
    stdlib 的没用过。用过一个第三方的 https://github.com/kootenpv/yagmail 还挺好。
    scienhub
        5
    scienhub  
    OP
       7 天前
    @Sawyerhou 我也试过这样子,但是依然会报错说有‘multiple To headers’。
    scienhub
        6
    scienhub  
    OP
       7 天前
    @ttttttttt 好的,我试试这个库。
    scienhub
        7
    scienhub  
    OP
       7 天前
    @ttttttttt 感谢!这个确实有用。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3653 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 05:17 · PVG 13:17 · LAX 22:17 · JFK 01:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.