【问题标题】:Error with sending emails with python using smtplib, ssl and bottle.py [duplicate]使用 smtplib、ssl 和 bottle.py 使用 python 发送电子邮件时出错 [重复]
【发布时间】:2021-05-30 19:07:58
【问题描述】:

所以我使用https://realpython.com/python-send-email/#sending-a-plain-text-email

我正在使用这段代码

import smtplib, ssl

port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "my@gmail.com"  # Enter your address
receiver_email = "your@gmail.com"  # Enter receiver address
password = input("Type your password and press enter: ")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)

我已经更改了一些我需要的东西的密码和邮件,但是当我发送电子邮件时,我收到了这个错误

File "main.py", line 32, in sendmail
    with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
TypeError: __init__() got an unexpected keyword argument 'context'

当我在一个普通的 .py 文件中尝试此代码时,它可以工作,但是当我将它与 bottle.py 一起使用时,它给了我这个错误,我不认为它是因为其他包,任何帮助都会非常感激

【问题讨论】:

  • 你试过只用context而不是context=context
  • 如果我这样做,我会得到这个imgur.com/MXN25U6
  • 山姆的回答是正确的。使用context 而不是context=context。您的后续错误是您的代码的一个新问题,您应该提出一个新问题。 (当你这样做时,请在该问题中包含整个堆栈跟踪。)
  • 这里正确的做法是根本不传递context 参数,因为SMTP_SSL 直到Python 3.3 才使用上下文,而提问者使用的是Python 2.7。

标签: python email bottle


【解决方案1】:

@Sam H 的评论是正确的:使用 context 作为位置参数,而不是将其作为关键字参数与 context=context 一起传递。

with smtplib.SMTP_SSL(smtp_server, port, context) as server:

【讨论】:

  • 其实正确的答案是完全不通过context。在 Python SMTP_SSL 实例的 local_hostname 属性(至少,这是我在 Python2.7 上测试时发生的情况)。从他们在 cmets 中留下的图像中,我们可以看到提问者正在使用 Python 2.7。
  • @snakecharmerb 你完全正确。如果与 TLS/SSL 一起使用,则必须创建上下文,但会“自动传递”给 smtplib,它从不期望上下文参数。详情见我的回答。
  • 其他答案在上面的链接中stackoverflow.com/questions/54697813/…
【解决方案2】:

我认识的人今天为我做了这件事,他做了什么,但它起作用了,当我做 'context' 而不是 'context=context' 时,它又给了我一个错误,但现在很好

【讨论】:

    猜你喜欢
    • 2023-02-11
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 2014-01-31
    • 2021-12-01
    • 2015-02-21
    相关资源
    最近更新 更多