質問

I'm working on a script in Python that checks an IP address against a blacklist and sends an email only if the IP shows up on the list. The script will be setup to be run every 15 minutes, but I only want it to send an email if the IP is on the list and an email hasn't been sent in the last 24 hours. Current code:

import sys
import subprocess
import smtplib
import datetime
username = ''
password = ''
fromaddr = ''
toaddr = ''
server = smtplib.SMTP(host=,port=)
server.starttls()
server.ehlo()
server.esmtp_features["auth"] = "LOGIN PLAIN"
server.login(username,password)
sentFolder = server.select("SENT",readonly=TRUE)
recentSent = sentFolder["Date"]
OneDayAgo = date.today()-timedelta(days=1)
msg = ''
staticIPAddress = ''
dnsHostname = staticIPAddress + ".bl.spamcop.net"
p = subprocess.check_output("nslookup " + dnsHostname1,stderr=subprocess.STDOUT,shell=False)
if ('Non-existent' not in str(p) and recentSent < OneDayAgo):
 server.sendmail(fromaddr, toaddrs, msg)

The error I run into occurs at:
sentFolder = server.select("SENT",readonly=TRUE)

The error code is: AttributeError: 'SMTP' object has no attribute 'select'

I've tested the rest of the script (without that piece and without the recentSent < OneDayAgo pieces) and it seems to work fine.

Any help in figuring out how to make the "only send if not sent within the last 24 hours" piece work would be really appreciated.

役に立ちましたか?

解決

In order to know if you've sent email in the previous 24 hours, you'll need to make a record of sending the email. You might store that information in a text file, an IMAP folder, a database, through a web app, or many other ways. How you store that data is your design decision.

Here is one possibility, in which the timestamp is stored in the modification date of a local file.

#UNTESTED EXAMPLE CODE
def create_timestamp():
    with open("tsfile", "w") as fp:
        fp.write("now")

def time_since_last_timestamp():
    return time.time() - os.path.getmtime("tsfile")


...
if 'Non-existent' not in str(p) and time_since_last_timestamp() > 86400:
    server.sendmail(...)
    create_timestamp()

他のヒント

To determine whether or not an email has been sent in the last 24 hours, you might want to program your script to examine the mail server logs. You didn't mention which MTA you are using, but all that I know of log messages in and out.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top