1

I'm very to new to this python and some other technologies, can someone suggest better ideas here very appreciated!

I have two python scripts when i ran both scripts, i'm able to create log files with timestamp every time i ran

so that log files i need to send outlook mail automatically once my python scripts completed

once i ran scripts when it completes i need to send outlook mail with attachment of log files automatically

i heard about smptplib library to send mails, but i need to send mail with log files once task completed

please suggest your ideas here

lets assume below example division.py file

 import logging
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    f  =  logging.Formatter('%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s')
            now = datetime.datetime.now()
            filename = now.strftime('new_logfile_%Y-%m-%d--%H-%M-%S.log')
            fh = logging.FileHandler(filename)
            fh.setFormatter(f)
            logger.addHandler(fh)
        a = 5
        b = 0
        try:
          c = a / b
logger.info(c)
        except Exception as e:
          logger.exception("Exception occurred")

when i ran above .py file it creates log file, so i need to add mail functionality in same program so when i ran program once it is completed i need to send log files to mail automatically

  • 2
    Does this answer your question? [How to send email attachments?](https://stackoverflow.com/questions/3362600/how-to-send-email-attachments) (second answer, for Python3, not the accepted one) – h4z3 Jun 20 '23 at 10:12
  • Or if it's in Azure, then it has some API to call to send messages, rather than having to "log in" smtp. https://learn.microsoft.com/en-us/azure/communication-services/quickstarts/email/send-email?pivots=programming-language-python – h4z3 Jun 20 '23 at 10:17

2 Answers2

1

I have suggestions, they are not complete decisions, because it's not enough context.

One possible way is to create other python script, which would always work in background like a daemon and monitor the directory for new log files. Watchdog library https://pypi.org/project/watchdog/ seems relevant for this task.

Other way is to make upper level python script, which will call your target script inside and after its completion send email. Probably using python multiprocessing.Process to run script.

As far as I can see, first option is preferred, but more difficult to implement.

You still need a library to send emails of course.

1

The answers here: How to send email attachments? help to send emails from python, also including attachments. Below is an example script, that I wrote, that sends itself as a file attachment as an email, if you save it as send_email.py.

import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate

def send_email(send_from, send_to, subject, text, files=None,
              server="127.0.0.1"):
    # message
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    # attachment
    msg.attach(MIMEText(text))
    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)

    # send the mail
    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
    
# create the message, including an attachment file

message_text = 'Test mail, sent from python, including this script as attachment.'
files = ['send_email.py']
    
send_email(send_from='noreply', 
           send_to='testbox@trash-mail.com',
           subject='Test', 
           text=message_text,
           files=files,
           server='localhost')

Be aware, that your firewall settings can prevent such scripts from working, which will almost always be the case if you are within a company network.

R. C.
  • 651
  • 5
  • 8
  • Hi @R. C., Thanks for you answer but my question is little different, lets assume below example i'm checking division so if it correct or not the result will be stored in log file so i need to send log to mail, when i ran this program it automatically send log results to mail once task finished import logging a = 5 b = 0 try: c = a / b except Exception as e: logging.exception("Exception occurred") – lAkShMipythonlearner Jun 21 '23 at 05:11
  • Hi! Just add send_email(... files=[filename] ...) to the end of the script, then it sends the log file to you once the script has ended. But I am not 100% sure that I understand the problem here. – R. C. Jun 21 '23 at 11:08
  • Thanks for responding! is this method used for outlook mail? and where can i use password method on above code @R. C. – lAkShMipythonlearner Jun 21 '23 at 11:38
  • 1
    No, this script acts as a small mail server, the sender's email address is in this case noreply@yourcomputer.something. Responding to such mail would obviously not work. Since this can be used for spam mails easily, it is likely that your IT will not allow it in the sense that the python script will not be able to send the mail. Try out the script in your setup first, using the correct target email address. If that works, you can move on. – R. C. Jun 21 '23 at 12:14