2017-05-19 16 views
0

imaplibを使用してGmailの受信トレイをチェックし、特定の件名に一致しないメールを別のメールに転送するプログラムを作成する必要があります。私はstmplibを使用してこれを行うことができますが、転送する必要があり、削除する必要がある電子メールに添付ファイルが含まれている場合、どうすればよいのかわかりません。添付ファイル付きの電子メールを処理できるように更新する必要があるコードは次のとおりです。Pythonを使用して添付ファイル付きのメールを転送する方法

# Connect and login to email 
imap = imaplib.IMAP4_SSL('imap.gmail.com') 
imap.login('[email protected]','password') 
imap.list() 
imap.select('inbox') 

smtp = smtplib.SMTP_SSL('smtp.gmail.com') 
smtp.login('[email protected]','password') 

try: 
    #Search and return sequential ids 
    result, data = imap.search(None,'ALL') 
    ids_list = data[0].split() 
    #print 'Total emails: '+str(len(ids_list)) 
    latest_id = ids_list[-1] 

    #Process each email in inbox 
    for i in ids_list: 
     t, d = imap.fetch(i, '(RFC822)') 
     for res_part in d: 
      if isinstance(res_part, tuple): 
       text = res_part[1] 
       msg = email.message_from_string(text) 
       subject = msg['subject'] 
       #print 'Subject: '+subject 
       message = get_txt(msg) #Retrieves email body text 
       #print message 
       if subject != 'The subject I\'m looking for': #Junk email 
        #print 'Sending to another email...' 
        smtp.sendmail('[email protected]', '[email protected]', message) 
        imap.store(i, '+FLAGS', '\\Deleted') 
        imap.expunge() 
       else: #Email we need to process 
        #print 'Process this email' 

except IndexError: 
    #Inbox is empty 

誰かが私にこれを達成するための適切な方法を示すことができますか?ありがとう!

+0

@abccd私は現在のコードを更新しました。私は電子メールの添付ファイルを処理できるようにする必要がありますが、現在は電子メールの本文のみを処理しています。 – McFizz

答えて

0

このライブラリを使用するには、有効なSMTPサーバーが必要です。あなたはあなたの電子メールプロバイダの1つを使用することができます、またはあなた自身のために1つをセットアップすることができます。

これを実行した後は、ファイルが配置されているFTPサーバーの例としてリンクすることはできません。これはPOPでもサポートされるべきです。

関連する問題