2013-05-24 3 views
1

Я хочу отправить почту через скрипт python, мне нужно, чтобы предупредить меня о некоторых пропущенных файлах.Python sendmail с содержимым текстового файла

scripy должны читать лог-файл и отправить содержимое этого файла в моей почте, так что я сделал это (* .txt.):

import smtplib, os 
from email.mime.text import MIMEText 


raport_file = open('alert.txt','rb') 
alert_msg = MIMEText(raport_file.read().encode("utf-8"), 'plain', 'utf-8') 
raport_file.close() 




m = smtplib.SMTP() 
m.connect("*****", 25) 
m.sendmail("Check_Files", "*****", alert_msg.as_string()) 
m.quit() 

скрипт запустить, но не почта вообще. Если я заменю alert_msg.as_string() на «любой текст», все будет хорошо.

+2

попробуйте напечатать 'alert_msg.as_string()' и посмотреть, что является выходом? – Amyth

+1

Проверено спам? – Blubber

+0

Проверено ваши лог-файлы? Или вы используете внешний smtp-хост? – Blubber

ответ

0
import smtplib 
import base64 
import os 
import sys 

FROM = '[email protected]' 
TO = '[email protected]' 
MARKER = 'SIMPLE_MARKER_GOES_HERE' 

if __name__ == "__main__": 
    filename = 'name_of_file' 

    # Read a file and encode it into base64 format 
    fo = open(filename, "rb") 
    filecontent = fo.read() 
    encodedcontent = base64.b64encode(filecontent) # base64 
    filename = os.path.basename(filename) 

    body =""" 
Insert whatever message you want here or dynamically create. 
""" 

    # Define the main headers. 
    part1 = """From: Matt Vincent <[email protected]> 
To: %s 
Subject: Sending Attachment 
MIME-Version: 1.0 
Content-Type: multipart/mixed; boundary=%s 
--%s 
""" % (TO, MARKER, MARKER) 

    # Define the message action 
    part2 = """Content-Type: text/plain 
Content-Transfer-Encoding:8bit 

%s 
--%s 
""" % (body, MARKER) 

    # Define the attachment section 
    part3 = """Content-Type: multipart/mixed; name=\"%s\" 
Content-Transfer-Encoding:base64 
Content-Disposition: attachment; filename=%s 

%s 
--%s-- 
""" %(filename, filename, encodedcontent, MARKER) 

    message = part1 + part2 + part3 

    try: 
     smtpObj = smtplib.SMTP('domainhere') 
     smtpObj.sendmail(FROM, TO, message) 
     print "Successfully sent email" 
    except Exception: 
     print "Error: unable to send email" 
Смежные вопросы