Search code examples
pythonmime-typessmtplibtext-processing

Collect Python output till current execution and assign it to variable for sending email


I am doing text processing using Python in which I am looking for a specific text in a console log and printing every matched line. This is accomplished by a function called:

get_matched_log_lines(url, search_pattern, print_pattern) where url = from which I get my log, search_pattern = my target search pattern, print_pattern = the way I want to print my output(its, %s.%s)

How do I send this entire output of function get_matched_log_lines() via email? Emailing function code is already written by me in Python.

Here is what I think/attempted so far:

email_content = get_matched_log_lines(url, search_pattern, print_pattern)
TO = 'recipient email address'
FROM ='sender email address'

#emailing function - py_mail
py_mail("Test email subject", email_content, TO, FROM) 

This provides me an empty email.


Solution

  • Here is my answer based on the suggestions by PyNEwbie:

       def get_matched_log_lines(url, search_pattern, print_pattern):
            out = open("output_file.txt", "w")
            for something in somthings:
                  test = print_pattern % matched_line
                  print >>out, test
                out.close()
    

    ^^ just a general example (syntax maybe incorrect). The idea is to open the file in write mode and then dumping the output in it.

    fp = open("output_file.txt", 'r')
        # Create a text/plain message
        msg = fp.read()
        fp.close()
        email_content = msg
    

    Then open the same file in read mode and store its output to some var (in my case email_content)

    Finally send an email with that email_content,

     email_content = get_matched_log_lines(url, search_pattern, print_pattern)
        TO = 'recipient email address'
        FROM ='sender email address'
    
    #emailing function - py_mail
    py_mail("Test email subject", email_content, TO, FROM)