【问题标题】:Python: when sending email, always blocked in the clause: smtpserver = smtplib.SMTP("smtp.gmail.com",587)Python:发送电子邮件时,总是在子句中被阻止:smtpserver = smtplib.SMTP("smtp.gmail.com",587)
【发布时间】:2012-08-12 11:48:54
【问题描述】:

我正在编写一个 Python 程序来发送电子邮件。但是每次执行子句时:

smtpserver = smtplib.SMTP("smtp.gmail.com",587)

它会在这里阻塞,一直保持执行状态,没有任何提示和错误。我不知道为什么。谁能帮助我?

代码如下: 导入smtplib

to = 'toemail@gmail.com'
gmail_user = 'user@gmail.com'
gmail_pwd = 'password'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.close()

【问题讨论】:

  • 这就是你的全部代码吗?其余部分在哪里(例如,您登录的部分)。
  • ping smtp.gmail.com 成功。但问题仍然存在,如上所述。
  • telnet smtp.gmail.com 587 有效吗?可能是防火墙问题。

标签: python email smtp gmail


【解决方案1】:

我遇到了类似的问题,上面的答案都不适合我。我的问题是因为我的 smtp 服务器使用 SSL。我需要使用smtplib.SMTP_SSL 而不是smtplib.SMTP。我只是在下面发布我的完整工作代码。 确保在执行前更改reqemail_config 的值。

    req = {
        "email": "to@something.com",
        "subject": "new e-mail from python",
        "body": "Hi,\nI am a bot",
    }

    email_config = {
        "server": "smtp.orange.fr",
        "port": 465,
        "username": "username@orange.fr",
        "password": "mypassword",
        "email": "fromwhichemail@orange.fr",
    }

#!/usr/bin/env python3
import smtplib

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

class Mail(object):
    def __init__(self, email_config):
        self.email = email_config["email"]
        self.password = email_config["password"]
        self.server = email_config["server"]
        self.port = email_config["port"]
        print(f"Logging to {self.server}:{self.port}")
        session = smtplib.SMTP_SSL(self.server, self.port)
        print(f"Calling ehlo")
        session.ehlo()
        print(f"Calling login")
        session.login(self.email, self.password)
        self.session = session

    def send_message(self, subject, to, body, filename):
        # Create a multipart message and set headers
        message = MIMEMultipart()
        message["From"] = self.email
        message["To"] = to
        message["Subject"] = subject
        message["Bcc"] = ""
        # Add body to email
        message.attach(MIMEText(body, "plain"))
        print(f"tot: {to}")
        print(f"subject: {subject}")
        print(f"body: {body}")

        if filename is not None:
            # Open PDF file in binary mode
            with open(filename, "rb") as attachment:
                part = MIMEBase("application", "octet-stream")
                part.set_payload(attachment.read())
            # Encode file in ASCII characters to send by email
            encoders.encode_base64(part)
            # Add header as key/value pair to attachment part
            part.add_header(
                "Content-Disposition",
                f"attachment; filename= {filename}",)
            # Add attachment to message and convert message to string
            message.attach(part)

        # Send e-mail
        print(f"Sending e-mail...")
        self.session.sendmail(self.email, to, message.as_string())

if __name__ == "__main__":
    req = {
        "email": "to@something.com",
        "subject": "new e-mail from python",
        "body": "Hi,\nI am a bot",
    }

    email_config = {
        "server": "smtp.orange.fr",
        "port": 465,
        "username": "username@orange.fr",
        "password": "mypassword",
        "email": "fromwhichemail@orange.fr",
    }
    m = Mail(email_config)
    if "pdf_file" in req:
        m.send_message(req["subject"], req["email"], req["body"], req["pdf_file"])
    else:
        m.send_message(req["subject"], req["email"], req["body"], None)



【讨论】:

    【解决方案2】:

    也许我迟到了 4 年,但这对我有用,可能会帮助其他人!

    server = smtplib.SMTP("smtp.gmail.com", 587, None, 30)
    

    【讨论】:

      【解决方案3】:

      作为参考,cpython smtplib 正在阻塞。也就是说,它在连接时会阻塞 GIL(即 Python)。尽管声称 GIL 在 I/O 上发布,但它仅在某些 I/O 上发布,而 SMTP 连接并非如此。 要使其异步,您需要将邮件发送到另一个进程或线程,具体取决于您的情况。

      【讨论】:

        【解决方案4】:

        连接可能存在一些问题(可能它被您的代理或防火墙阻止?)并且超时可能非常大,您看不到它进一步发展。

        The documentation of smtplib.SMTP 说:

        class smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])

        (...) 如果指定的 host 没有正确响应,则会引发 SMTPConnectError。可选的timeout 参数指定连接尝试等阻塞操作的超时(以秒为单位)(如果未指定,将使用全局默认超时设置)。

        尝试自己指定超时时间:

        smtpserver = smtplib.SMTP("smtp.gmail.com", 587, timeout=30)
        

        【讨论】:

        • 对不起,问题仍然存在。
        • @Bryant:其他人已经问过这个问题,但是您是否在脚本之外 ping 服务器?换句话说:你能到达服务器吗?另外:您是否等待至少 40 秒以查看脚本的行为方式以及它是否会在该行之后执行任何操作?似乎问题不在这里,因为如果无法连接,则必须在 30 秒后超时。
        猜你喜欢
        • 2014-10-18
        • 2015-08-22
        • 2012-01-26
        • 1970-01-01
        • 2019-04-15
        • 1970-01-01
        • 1970-01-01
        • 2019-01-21
        • 2019-03-01
        相关资源
        最近更新 更多