Smtplib:连接意外关闭

2024-06-26 14:15:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下代码:

def mailme():
    print('connecting')
    server = smtplib.SMTP('mail.server.com', 26)
    server.connect("mail.server.com", 465)
    print('connected..')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login('scraper@server.com', "pwd")
    text = 'TEST 123'
    server.sendmail('me@sserver.com', 'me@server2.com', text)
    server.quit()

但它给出了错误:

^{pr2}$

当通过Telnet连接时,它可以工作:

~ telnet mail.zoo00ooz.com 26
Trying 1.2.3.4...
Connected to server.com.
Escape character is '^]'.
220-sh97.surpasshosting.com ESMTP Exim 4.87 #1 Mon, 01 Jan 2018 00:23:02 -0500 
220-We do not authorize the use of this system to transport unsolicited, 
220 and/or bulk e-mail.
^C^C

Tags: to代码textcomserverdefconnectmail
2条回答

我在下面附上了使用Python3.6.0的示例邮件代码

import smtplib as sl
server = sl.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login('sender_mail_id@gmail.com','sender_password')
server.sendmail('sender_mail_id@gmail.com',['first_receiver_mail_id@gmail.com','second_receiver_mail_id@gmail.com','and_so_on@gmail.com'],'data')

你不需要连接两次! 正如documentation所说:

exception smtplib.SMTPServerDisconnected¶

This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server.

您的代码应该更像这样(即使这样,它也有点过于复杂,请参阅文档中的示例代码)

def mailme():
    SERVER_NAME='mail.whatever.com'
    SERVER_PORT=25
    USER_NAME='user'
    PASSWORD='password'
    print('connecting')
    server = smtplib.SMTP(SERVER_NAME, SERVER_PORT)
    print('connected..')
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(USER_NAME, PASSWORD)
    text = 'TEST 123'
    server.sendmail('whoever@whatever.com', 'another@hatever.com', text)
    server.quit()

mailme()

相关问题 更多 >