I'm trying to write stdout and stderr to a log file and add it as an attachment to an email. As the title says, I suspect that the file buffer is not closed properly and therefore is not found by "mail.Attachments.Add(attachment)". There are similar questions on this topic, but those solutions didn't work for me or I couldn't figure it out how to adapt it to my problem. Thankful for any help. greets (ps I'm using python 3.9 on windows) import sys import os import win32com.client as win32c # I copied Logger class from here: # https://stackoverflow.com/questions/14906764/how-to-redirect-stdout-to-both-file-and-console-with-scripting class Logger: def __init__(self): self.terminal = sys.stdout self.log = open("./logfile.log", "a") def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): # this flush method is needed for python 3 compatibility. # this handles the flush command by doing nothing. # you might want to specify some extra behavior here. pass def send_email(recipient, subject, text, attachment=None, auto=False): outlook = win32c.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = recipient mail.Subject = subject mail.HtmlBody = text # time.sleep(5) if attachment: mail.Attachments.Add(attachment) if auto: mail.Send() else: mail.Display(True) # redirect standard output and standard error output also to logfile sys.stdout = Logger() sys.stderr = sys.stdout print("hello world!\n\n") try: i = 1 / 0 except Exception as e: print(e) sys.stdout.log.flush() os.fsync(sys.stdout.log.fileno()) reci = "abcde@gmail.de" subj = "Log data" txt = "XYZ" attach = "./logfile.log" send_email(reci, subj, txt, attach) print("finished") Continue reading...