2015-05-18 39 views
0

我不是那種經驗豐富的python,而是爲小型工作做一些python編碼。目前我有一項工作可以打開一個日誌文件並提取任何被認爲是錯誤的記錄。然後將這個錯誤列表添加爲電子郵件通知的一部分。我想要做的是包含列表或通知列表爲空。我已經能夠在控制檯中執行此操作,但不知道如何在電子郵件中將其添加爲參數。Python在輸出中包含If/else的內容不僅僅是打印

if errorlist: 
    print "\n".join(errorlist) 
else: 
    print "No Errors Found" 

# Send Email 
SMTP_SERVER = {SMTP SERVER} 
SMTP_PORT = {SMTP PORT} 

sender = {Sender} 
password = {Password} 
recipient = {Recipient} 
subject = "This is the subject line" 
errorlist = "<br>" "\n".join(errorlist) 

body = "" + errorlist + "" 

headers = ["From: " + sender, 
     "Subject: " + subject, 
     "To: " + ", " .join(recipient), 
     "MIME-Version: 1.0", 
     "Content-Type: text/html"] 
headers = "\r\n".join(headers) 

session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) 

session.ehlo() 
session.starttls() 
session.ehlo 
session.login(sender, password) 

session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) 
session.quit() 
+0

你嘗試使用一個變量? –

回答

0
if errorlist: 
    error_string = "\n".join(errorlist) # assign it to variable 
    print (error_string) # still print it 
else: 
    error_string = "" # assign blank to error_string 
    print ("No Errors Found") # still print "no errors found" 
    . 
    . 
    . 
    body = ""+error_string+"" # 'body = error_string' is the same though 
    . 
    . 
    . 
    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) # this line you could replace "body" with "error_string" because they are pretty much goign to be equivilant because of the previous comment 

你想你的錯誤字符串分配到一個變量,然後構造體時所使用的變量之後。也有是爲了簡化

0

電子郵件在此線路上發送更多的空間:

session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) 

body變量包含您的電子郵件的正文。爲了在電子郵件正文中添加內容,應將其添加到body變量所包含的字符串中。適應你已經添加的代碼(成功地打印您所需的結果),你可以替換此行:

body = "" + errorlist + "" 

與此:

if errorlist: 
    body = "\n".join(errorlist) 
else: 
    body = "No Errors Found" 
相關問題