0

我用 Python 编写了一个简单的“POP3S to Secure SMTP over TLS”MRA 脚本(见下文)。

它工作正常,但有时它在尝试通过 SMTP 发送时返回“连接意外关闭”。再次运行脚本将成功传递该消息。

请给我一些建议,为什么它有时会无法传递消息,但在下一次运行时它会成功传递此消息!?

#! /usr/bin/env python

import poplib
import email

def forward_pop3_smtp( smtp_credentials, pop3_credentials, forward_address):
    pop3_server = pop3_credentials[0]
    pop3_port = pop3_credentials[1]
    pop3_user = pop3_credentials[2]
    pop3_password = pop3_credentials[3]

    message_recipient = forward_address

    server = poplib.POP3_SSL( pop3_server, pop3_port)
    server.user( pop3_user)
    server.pass_( pop3_password)

    for messages_iterator in range( len( server.list()[1])):
        message_list = server.retr( messages_iterator + 1)[1]

        message_string = ''
        for message_line in message_list:
            message_string += message_line + '\n'

        message_message = email.message_from_string( message_string)
        message_message_as_string = message_message.as_string()
        message_sender = message_message[ 'From']
        print( 'message_sender = ' + message_sender)

        smtp_return = send_smtp( smtp_credentials, message_sender, message_recipient, message_message_as_string)
        print( 'smtp_return = ' + str(smtp_return))
        if smtp_return == 0:
            print( 'Deleting message ' + message_message[ 'Subject'] + ':\n')
            return_delete = server.dele( messages_iterator + 1)
            print( 'return_delete = \n' + str(return_delete))
            print( '\n')
    server.quit()

def send_smtp( smtp_credentials, message_sender, message_recipient, message_message_as_string):
    smtp_server = smtp_credentials[0]
    smtp_port = smtp_credentials[1]
    smtp_user = smtp_credentials[2]
    smtp_password = smtp_credentials[3]

    import smtplib
    exception = 0
    try:
        server = smtplib.SMTP( smtp_server)
        server.starttls()
        server.login( smtp_user, smtp_password)
        smtp_sendmail_return = server.sendmail( message_sender, message_recipient, message_message_as_string)
        server.quit()
    except Exception, e:
        exception = 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return)
    return exception

if __name__ == '__main_':
    print( 'This module needs to be imported!\n')
    quit()
4

1 回答 1

0

将端口 587 用于 TLS。我没有看到脚本使用 smtp_port

使用喜欢,

server = smtplib.SMTP( smtp_server, int(smtp_port)

对于安全 SMTP (SMTP + SSL),使用 smtplib.SMTP_SSL

于 2012-12-14T10:56:53.553 回答