You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

74 lines
2.5 KiB

from email.utils import format_datetime
import requests
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils import timezone
def get_logs(limit, date, subject):
r = requests.get(
"https://api.mailgun.net/v3/%s/events" % settings.ANYMAIL['MAILGUN_SENDER_DOMAIN'],
auth=("api", settings.ANYMAIL['MAILGUN_API_KEY']),
params={"begin": format_datetime(date),
"ascending": "yes",
"limit": limit,
"pretty": "yes", })
print(r)
if r.status_code != 200:
print('r.content', r.content)
return
messages = r.json()
try:
print("len(messages['items'])", len(messages['items']))
no_attach = list(filter(
lambda i: 'message' in i and i['message']['headers']['subject'] == subject and not len(
i['message']['attachments']), messages['items']))
print("len(no_attach)", len(no_attach))
emails = [m['message']['headers']['to'] for m in no_attach]
return emails, datetime.utcfromtimestamp(sorted(no_attach, key=lambda i: i['timestamp'], reverse=True)[0]['timestamp'])
except Exception as e:
print('r.content', r.content)
print(e)
class Command(BaseCommand):
help = 'Get animail logs'
def add_arguments(self, parser):
# Named (optional) arguments
parser.add_argument(
'--limit',
type=int,
dest='limit',
help='Limit',
)
parser.add_argument(
'--date_start',
dest='date_start',
help='Date start',
)
parser.add_argument(
'--date_end',
dest='date_end',
help='Date end',
)
parser.add_argument(
'--subject',
dest='subject',
help='Subject',
)
def handle(self, *args, **options):
emails = []
date_start = datetime.strptime(options.get('date_start'), '%Y-%m-%d')
date_end = datetime.strptime(options.get('date_end'), '%Y-%m-%d') + timedelta(hours=23, minutes=59) \
if options.get('date_end') else timezone.now()
while date_start <= date_end:
e, date_start = get_logs(options.get('limit') or 300, date_start, options.get('subject'))
if not e:
break
emails += e
print(set(emails))
print(date_start)