【问题标题】:Add email send at specified interval to python script将指定间隔的电子邮件发送添加到 python 脚本
【发布时间】:2018-12-29 11:59:05
【问题描述】:

我有两个独立工作的 python 脚本。一个将一些数据记录到日志文件中,另一个将电子邮件发送到指定的电子邮件地址。我需要将这两个脚本组合在一起,以便电子邮件以指定的时间间隔发送日志文件。

我已经设法让两个脚本都在其中运行,但不知道如何将它们组合成一个工作脚本。

脚本 1

def get_titles():
    current_title = None
    while True:
        moment2 = datetime.datetime.now().strftime("%d-%b-%Y [ %H:%M:%S ]")
        new_title = GetWindowText(GetForegroundWindow())
        if new_title != current_title:
           if len(new_title) > 0:
                #logging.info(" Moved to : " + new_title)
                current_title = new_title
                time.sleep(0.1)
                #print(new_title)
                ff= (moment2 + " : " +  "Moved T0 : "+ new_title + '\n')
                #print (ff)
                with open('logfile.txt', 'a+') as f:
                  f.write(ff)

脚本 2

body = "Please see attatched file for info"
msg.attach(MIMEText(body, 'plain'))

filename = "logfile.txt"
attachment = open("logfile.txt", "rb")

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)

msg.attach(part)

server = smtplib.SMTP('smtpname', 587)
server.starttls()
server.login(fromaddr, password)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

【问题讨论】:

  • 我已经设法使用 threading.Timer(300, send_msg).start() 让它工作。但现在只是一个小问题,一旦脚本运行,它会在记录任何详细信息之前向电子邮件发送一个空白日志文件,但在 300 秒间隔后它会发送一个带有附加信息的日志文件。有什么办法可以停止发送第一个空白文件?

标签: python email smtplib


【解决方案1】:

创建 2 个类然后调用适当的方法?下面是一个粗略的模板。

class LogData:
    def __init__():
        print("Initilized!")

    def get_titles():
        #write to log file
        ...
        ...
        ...
        return log_file_name

class SendEmail:
    def __init__(data_file):
        self.data_file = data_file

    def send_email():
        #read self.data_file and send email
        ...
        ...
        ...

if __name__ == '__main__':
    log = LogData()
    log_file = log.get_titles()
    email_handler = SendEmail(log_file)
    email_handler.send_email()

【讨论】:

  • 我已将电子邮件脚本添加到日志记录脚本的同一文件中,所以这会比调用另一个 self.data_file 更容易吗?怎么可能每小时发送一次电子邮件?
猜你喜欢
  • 1970-01-01
  • 2013-01-01
  • 2011-09-16
  • 1970-01-01
  • 2020-11-03
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多