Sending part of a page as the body of an email

K

Kun

I currently have a python-cgi script that extracts data from a mysql
table. I would like to save this data as a string and send it to a
recipient via email.

I know how to send email using the smtp lib, but what I do not know his
how to save a portion of the page as a string. Any pointers?
 
J

Jesse Hager

Kun said:
I currently have a python-cgi script that extracts data from a mysql
table. I would like to save this data as a string and send it to a
recipient via email.

I know how to send email using the smtp lib, but what I do not know his
how to save a portion of the page as a string. Any pointers?

#At the top of your CGI script import these
import sys
import StringIO

#Create a StringIO object to hold output
string_io = StringIO.StringIO()
#Save the old sys.stdout so we can go back to it later
old_stdout = sys.stdout

#Normal output goes here



#To start capturing output replace sys.stdout with the StringIO object
sys.stdout = string_io

#Captured output goes here

#To finish capturing
sys.stdout = old_stdout

#To get the captured text from the StringIO object do:
captured_text = string_io.getvalue()

#To output the captured text to the original sys.stdout
#If this is omitted, the captured_text will not be sent to the browser
old_stdout.write(captured_text)

#You can repeat this capturing section several times and the output
#will accumulate in the StringIO object. To clear the contents of the
#StringIO object between sections do:
#string_io.truncate(0)



#More normal output goes here
#Do whatever you want with captured_text here...


#When finished with string_io, close it to free up the memory buffers
string_io.close()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top