TimeoutError: [WinError 10060] 连接尝试失败,因为连接方在一段时间后没有正确响应或###

问题描述 投票:0回答:2
  1. 我正在为 'send gamil' 编写一个 python 程序,但我们得到的错误名称为 “TimeoutError: [WinError 10060] 连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机未能响应”

2.程序代码为:

import smtplib as s

ob =s.SMTP("smtp.gamil.com",587)
ob.ehlo()
ob.starttls()
ob.login('[email protected]','#######')
subject="test python"
body="I love python"
massage="subject:{}\n\n{}".format(subject,body)
listadd=['[email protected]']
ob.sendmail('[email protected]',listadd,massage)
print("send mail")
ob.quit()

2.错误如下:

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after 
a period of time, or established connection failed because connected host has failed to respond

请帮忙解决这个问题

python jupyter-notebook smtp gmail timeoutexception
2个回答
0
投票

我编写了以下适合我的实用程序类:

import ssl
import smtplib
from email.message import EmailMessage


class Email:
    def __init__(self, server: str, port: int, address: str, password: str | None):
        self.server = server
        self.port = port
        self.address = address
        self.password = password

    def send_email(
            self, mail_to: str | list, subject: str, body: str, html: bool = False, use_ssl: bool = True
    ) -> None:
        """
        sending the email

        Args:
            mail_to: receiver, can be a list of strings
            subject: the subject of the email
            body: the body of the email
            html: whether the body is formatted with html or not
            use_ssl: whether to use a secure ssl connection and authentication

        Returns:
            None
        """
        if not isinstance(mail_to, str):
            mail_to = ', '.join(mail_to)

        if self.server == 'localhost':
            with smtplib.SMTP(self.server, self.port) as server:
                message = f'Subject: {subject}\n\n{body}'
                server.sendmail(self.address, mail_to, message)
                return None
        else:
            mail = EmailMessage()
            mail['Subject'] = subject
            mail['From'] = self.address
            mail['To'] = mail_to
            if html:
                mail.add_alternative(body, subtype='html')
            else:
                mail.set_content(body)

        if use_ssl:
            with smtplib.SMTP_SSL(self.server, self.port, context=ssl.create_default_context()) as server:
                server.login(self.address, self.password)
                server.send_message(mail)
        else:
            with smtplib.SMTP(self.server, self.port) as server:
                server.send_message(mail)

        return None

你可以这样使用它:

my_email = Email(server='localhost', port=1025, address='[email protected]', password='password')

my_email.send_email(
    mail_to=['[email protected]', '[email protected]'],
    subject='Email Subject',
    body='Email Body',
    html=False,
    use_ssl=False,
)

这是一个使用 python 调试服务器可视化电子邮件的示例,但并未实际发送它们。它对于测试目的非常有用。要启动调试服务器,只需在终端或 Windows cli(例如命令提示符或 powershell)中输入

python -m smtpd -c DebuggingServer -n localhost:1025

要发送真实的电子邮件,只需将参数

server
port
替换为实际值,并可以根据需要使用标志
html
use_ssl


0
投票
import smtplib

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as connection:
        connection.login(user='[email protected]', password='XXXXX')
        connection.sendmail("[email protected]", "[email protected]", "Hello, World!")

实际上这个 smtplib.SMPT_SSL 解决了我的问题。 Gmail 不允许我通过非 SSL 通道进行通信,因此我使用了 smtplib.SMTP_SSL。然后就大功告成啦

© www.soinside.com 2019 - 2024. All rights reserved.