2015-01-10 11 views
1

"와"내부 메일을 보내는 것은 실패 이유 코드파이썬 : 나는 궁금 할 때 블록

test = smtplib.SMTP('smtp.gmail.com', 587) 
test.ehlo() 
test.starttls() 
test.ehlo() 
test.login('address','passw') 
test.sendmail(sender, recipients, composed) 
test.close() 

작동하지만이

with smtplib.SMTP('smtp.gmail.com', 587) as s: 
    s.ehlo() 
    s.starttls() 
    s.ehlo() 
    s.login('address','passw') 
    s.sendmail(sender, recipients, composed) 
    s.close() 

처럼 쓸 때 메시지

실패
Unable to send the email. Error: <class 'AttributeError'> 
Traceback (most recent call last): 
    File "py_script.py", line 100, in <module> 
    with smtplib.SMTP('smtp.gmail.com', 587) as s: 
AttributeError: __exit__ 

왜 이런 일이 무엇입니까? (라즈베리 파이에 python3) 들으

답변

3

당신이 파이썬 3.3을 사용하고 있지 않습니다. 귀하의 Python 버전에서 smtplib.SMTP()은 컨텍스트 관리자가 아니며 with 문에서 사용할 수 없습니다. 더 __exit__ method, 컨텍스트 관리자에 대한 요구 사항이 없기 때문에

역 추적

직접 발생합니다. smptlib.SMTP() documentation에서

:

버전 3.3에서 변경하십시오 with 문에 대한 지원이 추가되었습니다.

당신은 @contextlib.contextmanager와 컨텍스트 관리자에서 객체를 래핑 할 수 있습니다

from contextlib import contextmanager 
from smtplib import SMTPResponseException, SMTPServerDisconnected 

@contextmanager 
def quitting_smtp_cm(smtp): 
    try: 
     yield smtp 
    finally: 
     try: 
      code, message = smtp.docmd("QUIT") 
      if code != 221: 
       raise SMTPResponseException(code, message) 
     except SMTPServerDisconnected: 
      pass 
     finally: 
      smtp.close() 

이 같은 출구 동작을 사용 파이썬 3.3에서 추가되었다한다. 다음과 같이 사용하십시오 :

with quitting_smtp_cm(smtplib.SMTP('smtp.gmail.com', 587)) as s: 
    s.ehlo() 
    s.starttls() 
    s.ehlo() 
    s.login('address','passw') 
    s.sendmail(sender, recipients, composed) 

연결이 끊어집니다.

+0

다음이 잘못 (?) http://robertwdempsey.com/python3-email-with-attachments-using-gmail/ – Gerard

+0

그러나 python3에? 내가 버전 3에서 노력하고있어 편집 : 좋아, 파이썬 3.2.3, 고마워요 :) – Gerard

+0

@ 제라드 : 설명서는 그것이 파이썬 3.3에서 컨텍스트 관리자가되었다는 내용의. –