import sys import os from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.core.mail import send_mail, BadHeaderError, EmailMessage import datetime from rowers.models import * from rowsandall_app.settings import BASE_DIR import pandas as pd sys.path.append('$path_to_root_of_project$') sys.path.append('$path_to_root_of_project$/$project_name$') os.environ['DJANGO_SETTINGS_MODULE'] = '$project_name$.settings' def getemails(): rs = Rower.objects.all() firstnames = [r.user.first_name for r in rs] lastnames = [r.user.last_name for r in rs] emails = [r.user.email for r in rs] is_actives = [r.user.is_active for r in rs] df = pd.DataFrame({ 'first_name': firstnames, 'last_name': lastnames, 'email': emails, 'is_active': is_actives}) return df class Command(BaseCommand): def handle(self, *args, **options): email_list = getemails() email_list.to_csv('email_list.csv', encoding='utf-8') fullemail = 'roosendaalsander@gmail.com' subject = "Rowsandall users list" message = "Dear Sander,\n\n" message += "Best Regards, the Rowsandall Team" message += "Users list attached \n\n" email = EmailMessage( subject, message, 'Rowsandall ', [fullemail]) email.attach_file('email_list.csv') os.remove('email_list.csv') _ = email.send()