Skip to content

Allowing a dynamic email subject #1

Description

@hanne

Hi,

Thanks for posting this, it certainly saved me some time!

I needed the email subject to be a bit more dynamic, so I've modified the code to allow the subject input to be a function which can take the message body text as input and return a string with the resulting subject line. In my case, this function will then count the number of occurrences of certain strings in the message body, and report the numbers in the email subject.

I hope it's useful.

def flush(self):
    if len(self.buffer) > 0:
        try:
            import smtplib
            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            smtp = smtplib.SMTP(self.mailhost, port)
            if isinstance(self.toaddrs, list):  # If toaddrs is a list, then join them as a string
                toaddrs = ','.join(self.toaddrs)
            else:
                toaddrs = self.toaddrs
            msg_body = ""
            for record in self.buffer:
                s = self.format(record)
                msg_body += s + "\r\n"
            if callable(self.subject):
                subject = self.subject(msg_body)
            else:
                subject = self.subject
            msg = "From: {}\r\nTo: {}\r\nSubject: {}\r\n\r\n{}".format(self.fromaddr, toaddrs,
                                                                       subject, msg_body)
            smtp.sendmail(self.fromaddr, self.toaddrs, msg)
            smtp.quit()
        except:
            self.handleError(None)  # no particular record
        self.buffer = []

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions