2012-08-09 4 views
0

이메일을 처리하고 csv 파일에 저장하는 다음과 같은 스크립트가 있습니다. 다른 웹 인터페이스에서 추가 처리를 위해 추출 된 전자 메일 데이터를 처리하기 위해 mechanize lib를 사용할 스크립트가 발전 할 것입니다. 이제는 문제가없는 특정 이메일을 잡아낼 수 있지만 수동으로 처리하거나 문제가있는 것을 볼 수있는 다른 주소로 트래핑 된 이메일을 전달할 수있는 방법이 있습니까? 우리 모두가 POP3는 검색을 위해 단독으로 사용된다는 것을 알다시피poplib을 사용하여 캡처 한 전자 메일 메시지를 다른 전자 메일 주소로 전달하는 방법은 무엇입니까?

다음은 스크립트

import ConfigParser 
import poplib 
import email 
import BeautifulSoup 
import csv 
import time 

DEBUG = False 
CFG = 'email' # 'email' or 'test_email' 


#def get_config(): 
def get_config(fnames=['cron/orderP/get_orders.ini'], section=CFG): 
    """ 
    Read settings from one or more .ini files 
    """ 
    cfg = ConfigParser.SafeConfigParser() 
    cfg.read(*fnames) 
    return { 
     'host': cfg.get(section, 'host'), 
     'use_ssl': cfg.getboolean(section, 'use_ssl'), 
     'user': cfg.get(section, 'user'), 
     'pwd':  cfg.get(section, 'pwd') 
    } 

def get_emails(cfg, debuglevel=0): 
    """ 
    Returns a list of emails 
    """ 
    # pick the appropriate POP3 class (uses SSL or not) 
    #pop = [poplib.POP3, poplib.POP3_SSL][cfg['use_ssl']] 

    emails = [] 
    try: 
     # connect! 
     print('Connecting...') 
     host = cfg['host'] 
     mail = poplib.POP3(host) 
     mail.set_debuglevel(debuglevel) # 0 (none), 1 (summary), 2 (verbose) 
     mail.user(cfg['user']) 
     mail.pass_(cfg['pwd']) 

     # how many messages? 
     num_messages = mail.stat()[0] 
     print('{0} new messages'.format(num_messages)) 

     # get text of messages 
     if num_messages: 
      get = lambda i: mail.retr(i)[1]     # retrieve each line in the email 
      txt = lambda ss: '\n'.join(ss)     # join them into a single string 
      eml = lambda s: email.message_from_string(s) # parse the string as an email 
      print('Getting emails...') 
      emails = [eml(txt(get(i))) for i in xrange(1, num_messages+1)] 
     print('Done!') 
    except poplib.error_proto, e: 
     print('Email error: {0}'.format(e.message)) 

    mail.quit() # close connection 
    return emails 

def parse_order_page(html): 
    """ 
    Accept an HTML order form 
    Returns (sku, shipto, [items]) 
    """ 
    bs = BeautifulSoup.BeautifulSoup(html) # parse html 

    # sku is in first <p>, shipto is in second <p>... 
    ps = bs.findAll('p')     # find all paragraphs in data 
    sku = ps[0].contents[1].strip()   # sku as unicode string 
    shipto_lines = [line.strip() for line in ps[1].contents[2::2]] 
    shipto = '\n'.join(shipto_lines)  # shipping address as unicode string 

    # items are in three-column table 
    cells = bs.findAll('td')      # find all table cells 
    txt = [cell.contents[0] for cell in cells] # get cell contents 
    items = zip(txt[0::3], txt[1::3], txt[2::3]) # group by threes - code, description, and quantity for each item 

    return sku, shipto, items 

def get_orders(emails): 
    """ 
    Accepts a list of order emails 
    Returns order details as list of (sku, shipto, [items]) 
    """ 
    orders = [] 
    for i,eml in enumerate(emails, 1): 
     pl = eml.get_payload() 
     if isinstance(pl, list): 
      sku, shipto, items = parse_order_page(pl[1].get_payload()) 
      orders.append([sku, shipto, items]) 
     else: 
      print("Email #{0}: unrecognized format".format(i)) 
    return orders 

def write_to_csv(orders, fname): 
    """ 
    Accepts a list of orders 
    Write to csv file, one line per item ordered 
    """ 
    outf = open(fname, 'wb') 
    outcsv = csv.writer(outf) 
    for poNumber, shipto, items in orders: 
     outcsv.writerow([])  # leave blank row between orders 
     for code, description, qty in items: 
     outcsv.writerow([poNumber, shipto, code, description, qty]) 
     # The point where mechanize will come to play 

def main(): 
    cfg = get_config() 
    emails = get_emails(cfg) 
    orders = get_orders(emails) 
    write_to_csv(orders, 'cron/orderP/{0}.csv'.format(int(time.time()))) 

if __name__=="__main__": 
    main() 
+0

POP3는 전자 메일을 보내거나 전달하지 않습니다. 전자 메일을 보내려면 SMTP와 [smtplib] (http://docs.python.org/library/smtplib.html#smtp-example)을 사용할 수 있지만 SMTP 서버가 필요합니다. –

+0

smtplib을 사용하여 캡처 한 전자 메일 메시지를 보낼 수 있습니까? smtplib을 사용하는 동안 메시지를 수정해야합니까, 아니면 캡처 한 그대로 보낼 수 있습니까? –

+1

일반적으로 예, 메시지 본문을 "있는 그대로"보낼 수 있습니다. 그러나 일부 SMTP 서버는 처리되는 메시지에 대해 다른 제한 사항을 적용합니다. –

답변

0

입니다 그래서 메시지를 보내는을 위해 POP3를 사용하여 아무 소용이 없다 (알거나 이메일이 어떻게 작동하는지 생각을 가진 사람들) 왜 내가 언급 한 poplib로 캡처 한 전자 메일 메시지를 다른 전자 메일 주소로 전달할 수 있습니까? 질문으로.

완전한 대답은 입니다. poplib가 캡처 한 전자 메일 메시지를 전달하기 위해 smtplib를 사용할 수 있습니다. 메시지 본문을 캡처하고 원하는 전자 메일 주소로 smtplib을 사용하여 보내면됩니다. 또한 Aleksandr Dezhin이 인용 한 것처럼 일부 SMTP 서버는 처리되는 메시지에 대해 서로 다른 제한을 가하는 것에 동의합니다.

유닉스 시스템에 있다면 sendmail을 사용하여이를 달성 할 수 있습니다.

관련 문제