Ticket #1541: multipart_mail.diff

File multipart_mail.diff, 2.1 KB (added by bruce@…, 18 years ago)

mail.py patch

  • mail.py

     
    22
    33from django.conf.settings import DEFAULT_FROM_EMAIL, EMAIL_HOST, EMAIL_SUBJECT_PREFIX, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
    44from email.MIMEText import MIMEText
     5from email.MIMEMultipart import MIMEMultipart
    56import smtplib
    67
    78class BadHeaderError(ValueError):
    89    pass
    910
     11class SafeMIMEMultipart(MIMEMultipart):
     12    def __setitem__(self, name, val):
     13        "Forbids multi-line headers, to prevent header injection."
     14        if '\n' in val or '\r' in val:
     15            raise BadHeaderError, "Header values can't contain newlines (got %r for header %r)" % (val, name)
     16        MIMEMultipart.__setitem__(self, name, val)
     17
    1018class SafeMIMEText(MIMEText):
    1119    def __setitem__(self, name, val):
    1220        "Forbids multi-line headers, to prevent header injection."
     
    1826    """
    1927    Easy wrapper for sending a single message to a recipient list. All members
    2028    of the recipient list will see the other recipients in the 'To' field.
     29    Note that the message parameter can be either text or one of the SafeMIMExxx methods listed above.
    2130    """
    2231    return send_mass_mail([[subject, message, from_email, recipient_list]], fail_silently, auth_user, auth_password)
    2332
     
    2837
    2938    If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
    3039    If auth_user and auth_password are set, they're used to log in.
     40    Note that the message parameter can be either text or one of the SafeMIMExxx methods listed above.
    3141    """
    3242    try:
    3343        server = smtplib.SMTP(EMAIL_HOST)
     
    4252        if not recipient_list:
    4353            continue
    4454        from_email = from_email or DEFAULT_FROM_EMAIL
    45         msg = SafeMIMEText(message)
     55
     56        if isinstance(message, SafeMIMEText) or isinstance(message, SafeMIMEMultipart):
     57            msg = message
     58        else:
     59            msg = SafeMIMEText(message)
     60
    4661        msg['Subject'] = subject
    4762        msg['From'] = from_email
    4863        msg['To'] = ', '.join(recipient_list)
Back to Top