2016-11-01 2 views
4

나는 smtplib을 통해 Python으로 보낼 때 반송 된 모든 전자 메일을 잡으려고합니다. 나는 예외 포수를 추가 할 것을 제안한 similar post을 보았으나, 나의 sendmail 함수는 가짜 이메일 주소에 대해서도 예외를 던지지 않는다는 것을 알아 차렸다.Python에서 반송 된 전자 메일 smtplib을 감지합니다.

여기 내 send_email 기능은 smtplib입니다.

def send_email(body, subject, recipients, sent_from="[email protected]"): 
    msg = MIMEText(body) 

    msg['Subject'] = subject 
    msg['From'] = sent_from 
    msg['To'] = ", ".join(recipients) 

    s = smtplib.SMTP('mySmtpServer:Port') 
    try: 
     s.sendmail(msg['From'], recipients, msg.as_string()) 
    except SMTPResponseException as e: 
     error_code = e.smtp_code 
     error_message = e.smtp_error 
     print("error_code: {}, error_message: {}".format(error_code, error_message)) 
    s.quit() 

샘플 전화 : 나 자신, 내 보낸 사람의받은 편지함에서 이메일 바운스 보고서를 수신 할 수 있어요 나는 사람이 보낸 사람을 설정 때문에

send_email("Body-Test", "Subject-Test", ["[email protected]"], "[email protected]") 

:

<[email protected]>: Host or domain name not found. Name service error 
    for name=jfdlsaf.com type=A: Host not found 

Final-Recipient: rfc822; [email protected] 
Original-Recipient: rfc822;[email protected] 
Action: failed 
Status: 5.4.4 
Diagnostic-Code: X-Postfix; Host or domain name not found. Name service error 
    for name=jfdlsaf.com type=A: Host not found 

방법이 있나요 파이썬을 통해 바운스 메시지를 얻으려면?

+0

이 문제에 해결책이 있었습니까? –

+0

반송 보고서를 보낼 전자 메일 상자를 열 때 poplib을 사용할 수 있습니까? – alex

답변

0
import poplib 
from email import parser 

#breaks with if this is left out for some reason (MAXLINE is set too low by default.) 
poplib._MAXLINE=20480 

pop_conn = poplib.POP3_SSL('your pop server',port) 
pop_conn.user(username) 
pop_conn.pass_(password) 
#Get messages from server: 
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] 

# Concat message pieces: 
messages = ["\n".join(mssg[1]) for mssg in messages] 
#Parse message intom an email object: 
messages = [parser.Parser().parsestr(mssg) for mssg in messages] 
for message in messages: 
    if "Undeliverable" in message['subject']: 

     print message['subject'] 
     for part in message.walk(): 
      if part.get_content_type(): 
       body = str(part.get_payload(decode=True)) 

       bounced = re.findall('[a-z0-9-_\.][email protected][a-z0-9-\.]+\.[a-z\.]{2,5}',body) 
       if bounced: 

        bounced = str(bounced[0].replace(username,'')) 
        if bounced == '': 
         break 

        print bounced 

희망이 도움이됩니다. 그러면 배달 할 수없는 보고서가 있는지 사서함의 내용을 검사하고 반송 된 전자 메일 주소를 찾기 위해 메시지를 읽습니다. 그러면 결과가 인쇄됩니다.

관련 문제