2017-02-14 23 views
0

По какой-то причине, которая ускользает от меня, всякий раз, когда я пытаюсь отправить это письмо, вызывая функцию, в письме отсутствует предмет, отсутствует «To:», а тело электронной почты компенсируется четырьмя пробелами. Однако, когда точно такой же код запускается непосредственно внутри тела скрипта, все отформатировано отлично.Python: smtplib неправильно форматирует электронную почту, когда внутри функции, но правильно ее форматирует, когда один и тот же код запускается извне функции

import smtplib 

def send_email(): 
    sender = '[email protected]' 
    receivers = ['[email protected]'] 

    message_header = """From: Me <[email protected]> 
    To: Me <[email protected]> 
    Subject: This is the messages's subject 

    """ 

    message_body = 'This is the message\'s body' 

    message = message_header + message_body 

    try: 
     smtpObj = smtplib.SMTP('server_name', 25) 
     smtpObj.sendmail(sender, receivers, message) 
     print("Successfully sent email") 
    except OSError: 
     print("Error: unable to send email") 

send_email() 

ответ

1

(Это показывает вам, как исправить свой текущий код, мой other answer показывает вам правильный путь для реализации этого.)


Каждая строка message_header, но первым предшествует 4 пробела, включая тело после того, как вы соедините две строки:

>>> repr(message_header) 
'"From: Me <[email protected]>\\n To: Me <[email protected]>\\n Subject: This is the messages\'s subject\\n\\n "' 

(Я тестировал это в среде UNIX, поэтому здесь отображается \n. . Я предполагаю, что вы используете файл с символами конца строки DOS, которая уже использует \r\n, что ожидает SMTP)

Либо устранить их самостоятельно:

def send_email(): 
    sender = '[email protected]' 
    receivers = ['[email protected]'] 

    message_header = """From: Me <[email protected]> 
To: Me <[email protected]> 
Subject: This is the messages's subject 

""" 

, которая некрасиво, или использовать textwrap.dedent:

def send_email(): 
    sender = '[email protected]' 
    receivers = ['[email protected]'] 

    message_header = textwrap.dedent(
     """From: Me <[email protected]> 
      To: Me <[email protected]> 
      Subject: This is the messages's subject 

     """) 

Это удаляет такое же количество пробелов из каждой строки в качестве аргумента:

dedent(text) 
    Remove any common leading whitespace from every line in `text`. 

    This can be used to make triple-quoted strings line up with the left 
    edge of the display, while still presenting them in the source code 
    in indented form. 

    Note that tabs and spaces are both treated as whitespace, but they 
    are not equal: the lines " hello" and " hello" are 
    considered to have no common leading whitespace. (This behaviour is 
    new in Python 2.5; older versions of this module incorrectly 
    expanded tabs before searching for common leading whitespace.) 

Еще лучше, используйте '\r\n'.join, чтобы построить строку для вас.

def send_email(): 
    sender = '[email protected]' 
    receivers = ['[email protected]'] 

    headers = [ 
     'From: Me <[email protected]>', 
     'To: Me <[email protected]>', 
     "Subject: This is the message's subject" 
    ] 

    message_body = 'This is the message\'s body' 

    message = '\r\n'.join(headers + ['', ''] + [message_body]) 
1
def send_email(): 
    ... 
    message_header = """From: Me <[email protected]> 
____To: Me <[email protected]> 
____Subject: This is the messages's subject 

____""" 

против:

message_header = """From: Me <[email protected]> 
To: Me <[email protected]> 
Subject: This is the messages's subject 

""" 

Обратите внимание, что есть пробелы в вашей функции, потому что они с отступом. Я выделил их с подчеркиваниями для вас.

Вы можете исправить это с помощью:

def send_email(): 
    ... 
    message_header = """From: Me <[email protected]> 
To: Me <[email protected]> 
Subject: This is the messages's subject 

""" 
2

Мой другой ответ в сторону, вы должны использовать email пакет для создания сообщения, а не пытаться построить его вручную.

def send_email(): 
    sender = '[email protected]' 
    receivers = ['[email protected]'] 

    message_body = 'This is the message\'s body' 

    msg = email.MIMEText(message_body) 
    msg['Subject'] = "This is the message's subject" 
    msg['From'] = 'Me <%s>' % (sender,) 
    msg['To'] = ', '.join(receivers) 


    try: 
     smtpObj = smtplib.SMTP('server_name', 25) 
     smtpObj.sendmail(sender, receivers, msg.as_string()) 
     print("Successfully sent email") 
    except OSError: 
     print("Error: unable to send email")