import logging from collections.abc import Iterable from urllib.parse import quote, urlencode from django.conf import settings from django.core import mail from django.db.models.functions import Now from cmsmanage.email import TemplatedMultipartEmail from membershipworks.models import EventExt logger = logging.getLogger(__name__) class EventSurveyEmail(TemplatedMultipartEmail): # TODO: better wording subject = ( "[Claremont MakerSpace] Please fill out a survey for your recent CMS class!" ) from_email = "CMS Classes " template = "membershipworks/email/event_survey.dj.html" @staticmethod def survey_url(event: EventExt, attendee_name: str, attendee_email: str) -> str: return "https://claremontmakerspace.org/class-evaluation-form?" + urlencode( { "event_id": event.eid, "instructor_name": str(event.instructor) if event.instructor else "", "event_name": event.title, "event_date": event.start.strftime("%Y-%m-%d %H:%M:%S"), "participant_name": attendee_name, "participant_email": attendee_email, }, quote_via=quote, ) @classmethod def render_for_event(cls, event: EventExt) -> Iterable[mail.EmailMessage]: for name, email in event.attendees.values_list("name", "email"): sanitized_email = mail.message.sanitize_address( (name, email), settings.DEFAULT_CHARSET ) survey_url = cls.survey_url(event, name, email) yield cls.render( {"event": event, "attendee_name": name, "survey_url": survey_url}, to=[sanitized_email], ) def send_survey_emails(): with mail.get_connection() as conn: for event in EventExt.objects.filter( occurred=True, should_survey=True, survey_email_sent=False, end__lt=Now() ): logger.info("Sending survey messages for event: %s", event) # mark as sent even if we don't finish, to prevent sending duplicates event.survey_email_sent = True event.save() conn.send_messages(list(EventSurveyEmail.render_for_event(event)))