2012-01-30 3 views
5

괜찮 았던 사람들, 나는 인터넷을 오래 동안 보았으며 이에 대한 대답을 찾을 수 없었습니다. 나는 많은 제안을 시도했지만 그것이 작동하도록 할 수 없습니다. 파이썬 (smtplib과 이메일 모듈)과 gmail 서비스를 사용하여 이메일을 보내려고합니다. 여기 내 수입 패키지는 : 여기Python 전자 메일 보내기 TypeError : 예상되는 문자열 또는 버퍼

import time, math, urllib2, urllib, os, shutil, zipfile, smtplib, sys 
from email.mime.text import MIMEText 

하고있는 이메일을 보내는 내 데프 문 :

def sendmessage(): 
print('== You are now sending an email to Hoxie. Please write your username below. ==') 
mcusername = str(raw_input('>> Username: ')) 
print('>> Now your message.') 
message = str(raw_input('>> Message: ')) 
print('>> Attempting connection to email host...') 
fromaddr = '[email protected]' 
toaddrs = '[email protected]' 
username = '[email protected]' 
password = '1013513403' 
server = smtplib.SMTP('smtp.gmail.com:587') 
subject = 'Email from',mcusername 
content = message 
msg = MIMEText(content) 
msg['From'] = fromaddr 
msg['To'] = toaddrs 
msg['Subject'] = subject 
try: 
    server.ehlo() 
    server.starttls() 
    server.ehlo() 
except: 
    print('!! Could not connect to email host! Check internet connection! !!') 
    os.system('pause') 
    main() 
else: 
    print('>> Connected to email host! Attempting secure login via SMTP...') 
    try: 
     server.login(username,password) 
    except: 
     print('!! Could not secure connection! Stopping! !!') 
     os.system('pause') 
     main() 
    else: 
     print('>> Login succeeded! Attempting to send message...') 
     try: 
      server.sendmail(fromaddr, toaddrs, msg) 
     except TypeError as e: 
      print e 
      print('Error!:', sys.exc_info()[0]) 
      print('!! Could not send message! Check internet connection! !!') 
      os.system('pause') 
      main() 
     else: 
      server.quit() 
      print('>> Message successfully sent! I will respond as soon as possible!') 
      os.system('pause') 
      main() 

내가 광범위하게 내가 감히 디버깅이 얻을 수있다 :

>> Login succeeded! Attempting to send message... 
TypeError: expected string or buffer 

을 즉, 로그인에 성공했지만 메시지를 보내려고하면 중단되었습니다. 나를 괴롭히는 한 가지는 어디를 가리 키지 않는다는 것입니다. 또한 제 작성법이 그다지 좋지 않으므로 사이버 왕따는 없습니다.

도움이 될 것입니다. 감사. 두 개의 값을 전달하기 때문에

subject = 'Email from',mcusername 

당신이 문자열로 제목을 만들 것으로 예상하는 경우, 그 사실 튜플로 만들어지고 :

답변

3

내 생각 엔 범인이 줄입니다. 당신이 아마하고 싶었던 것은 : 당신이 당신의 예외의 모든 포장과 하나가있는 경우 예외 메시지 (유용한 역 추적을 멀리 던지고 인쇄 디버깅 측면 ... 방법에 대한 또한

subject = 'Email from %s' % mcusername 

,). 당신이 처리하려고하는 특정 예외를 정말로 알기 전까지 모든 것을 래핑하지 않으려 고 시도한 적이 있습니까? 이와 같은 담요 catch-all 예외 처리를 수행하면 구문 버그가있을 때 디버깅이 더 어려워집니다.

6

충돌있어 선은 당신이 그것을 두 개의 문자열과 MimeText는 인스턴스를 제공하고

server.sendmail(fromaddr, toaddrs, msg) 

이다; 그것은 문자열의 형태로 메시지를 원합니다. [나는 그것이 또한 목록의 형태로 주소를 원하는 생각하지만, 특별한 경우 하나의 문자열. 예를 들어, 당신은 example in the docs 볼 수 있습니다 :

s = smtplib.SMTP('localhost') 
s.sendmail(me, [you], msg.as_string()) 
s.quit() 

당신은 문자열로 MimeText는 변환해야 sendmail이 행복하기 때문입니다. @jdi가 지적한 ("AttributeError : 'tuple'객체에 'lstrip'속성이없는 메시지를 생성하는) 버그를 수정하고 msg를 msg.as_string()으로 변경하면 코드가 작동합니다.