I have a script that runs main() and at the end I want to send the contents it has by e-mail. I don't want to write new files nor anything. Just have the original script be unmodified and at the end just send the contents of what it printed. Ideal code:
main()
send_mail()
I tried this:
def main():
  print('HELLOWORLD')
def send_email(subject='subject', message='', destination='me@gmail.com', password_path=None):
    from socket import gethostname
    from email.message import EmailMessage
    import smtplib
    import json
    import sys
    server = smtplib.SMTP('smtp.gmail.com', 587)
    smtplib.stdout = sys.stdout # <<<<<-------- why doesn't it work?
    server.starttls()
    with open(password_path) as f:
        config = json.load(f)
        server.login('me@gmail.com', config['password'])
        # craft message
        msg = EmailMessage()
        #msg.set_content(message)
        msg['Subject'] = subject
        msg['From'] = 'me@gmail.com'
        msg['To'] = destination
        # send msg
        server.send_message(msg)
if __name__ == '__main__':
    main()
    send_mail()
but it doesn't work.
I don't want to write other files or change the original python print statements. How to do this?
I tried this:
def get_stdout():
    import sys
    print('a')
    print('b')
    print('c')
    repr(sys.stdout)
    contents = ""
    #with open('some_file.txt') as f:
    #with open(sys.stdout) as f:
    for line in sys.stdout.readlines():
        contents += line
    print(contents)
but it does not let me read sys.stdout because it says its not readable. How can I open it in readable or change it to readable in the first place?
I checked all of the following links but none helped:
- How to send output from a python script to an email address
- https://www.quora.com/How-can-I-send-an-output-from-a-Python-script-to-an-email-address
- https://bytes.com/topic/python/answers/165835-email-module-redirecting-stdout
- Redirect stdout to a file in Python?
- How to handle both `with open(...)` and `sys.stdout` nicely?
- Capture stdout from a script?
