2016-09-27 36 views
0

使用文本文件搜索字符串,然後通過電子郵件發送nex幾行。搜索文本文件和電子郵件結果

我有搜索工作,並打印正確的線 電子郵件發送成功,但它僅包含輸出

任何思考的最後一行?

FILE.TXT

first 
second 
thrid 
------------------------------------------------------------------------------ 
after first 
after second 
after thrid 
after forth 
after fifth 
after sixth 

我的代碼

import smtplib 

from email.mime.text import MIMEText 

from_address = "[email protected]" 
to_address = "[email protected]" 


with open("file.txt", "r") as f: 
    searchlines = f.readlines() 
    for i, line in enumerate(searchlines): 
     if "------------------------------------------------------------------------------" in line: 
      for l in searchlines[i:i+6]: print l, 
      output = l 

      msg = MIMEText(output) 
      msg['Subject'] = "Test email" 
      msg['From'] = from_address 
      msg['To'] = to_address 

      body = output 

      # Send the message via local SMTP server. 
      s = smtplib.SMTP('smtp.domain.com', '8025') 

      s.sendmail(from_address, to_address, msg.as_string()) 

      s.quit() 

通過打印輸出:

------------------------------------------------------------------------------ 
after first 
after second 
after thrid 
after forth 
after fifth 

電子郵件只包含在身體

after fifth 

回答

-1

你的for循環打印出所有的線,但隨後的循環結束,L是設置在環路中的最後一項:後第五

,那麼你的電子郵件是最後L個

0

你的縮進是靠不住的。循環應該收集這些行,然後當你收集所有行時你應該發送一封電子郵件。

with open("file.txt", "r") as f: 
    searchlines = f.readlines() 
# <-- unindent; we don't need this in the "with" 
for i, line in enumerate(searchlines): 
    # Aesthetics: use "-" * 78 
    if "-" * 78 in line: 
     for l in searchlines[i:i+6]: 
      print l, 
     # collect all the lines in output, not just the last one 
     output = ''.join(searchlines[i:i+6]) 
     # if you expect more than one result, this is wrong 
     break 

# <-- unindent: we are done when the for loop is done 
# Add an explicit encoding -- guessing here which one to use 
msg = MIMEText(output, 'plain', 'utf-8') 
msg['Subject'] = "Test email" 
msg['From'] = from_address 
msg['To'] = to_address 

# no point in assigning body and not using it for anything 

# Send the message via local SMTP server. 
s = smtplib.SMTP('smtp.domain.com', '8025') 
s.sendmail(from_address, to_address, msg.as_string()) 
s.quit() 

真正的錯誤是output = l只會收集l的最後一個值的最裏面for l循環之後,但重組程序無法做到的事情在一個循環時,他們應該只發生一次(反之亦然!)希望更清楚。

如果可能有多個結果,只是刪除break將不夠 - 這將以不同的形式恢復原始錯誤,其中只有最後一個匹配的六行將被髮送。如果您需要支持多個結果,您的代碼需要以某種方式將它們組合成一條消息。

+0

啊我確定我看到了,所以收集結果中的輸出。原始代碼('ascii') AttributeError:'list'對象沒有屬性'encode' – Adam

+0

我錯過了創建MIMEText正文部分的地方 - 更新了答案。 – tripleee

+0

完美,謝謝 – Adam

相關問題