Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.conf import settings
- from django.utils.html import strip_tags, strip_spaces_between_tags
- from email.MIMEMultipart import MIMEMultipart
- from email.MIMEText import MIMEText
- from email.Header import Header
- import smtplib, rfc822
- class BadHeaderError(ValueError):
- pass
- class SafeMIMEMultipart(MIMEMultipart):
- def __setitem__(self, name, val):
- "Forbids multi-line headers, to prevent header injection."
- if '\n' in val or '\r' in val:
- raise BadHeaderError, "Header values can't contain
- newlines (got %r for header %r)" % (val, name)
- if name == "Subject":
- val = Header(val, settings.DEFAULT_CHARSET)
- MIMEText.__setitem__(self, name, val)
- def send_mass_mail(datatuple, fail_silently=False,
- auth_user=settings.EMAIL_HOST_USER,
- auth_password=settings.EMAIL_HOST_PASSWORD):
- """
- Given a datatuple of (subject, message, from_email, recipient_list), sends
- each message to each recipient list. Returns the number of e-mails sent.
- If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
- If auth_user and auth_password are set, they're used to log in.
- """
- # We prepare the server to send messages.
- try:
- server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)
- if auth_user and auth_password:
- server.login(auth_user, auth_password)
- except:
- #print 'Server preparation did not work'
- if fail_silently:
- return
- raise
- num_sent = 0
- # We prepare the message to be sent.
- for subject, message, from_email, recipient_list in datatuple:
- if not recipient_list:
- continue
- from_email = from_email or settings.DEFAULT_FROM_EMAIL
- # Create the root message and fill in the basic headers
- msgRoot = MIMEMultipart('related')
- msgRoot['Subject'] = subject
- msgRoot['From'] = from_email
- msgRoot['To'] = ', '.join(recipient_list)
- msgRoot['Date'] = rfc822.formatdate()
- msgRoot.preamble = 'This is a multi-part message in MIME format.'
- # Encapsulate the plain and HTML versions of the message body in an
- # 'alternative' part, so message agents can decide which they
- want to display.
- msgAlternative = MIMEMultipart('alternative')
- msgRoot.attach(msgAlternative)
- # This is the html message.
- msgText = MIMEText(message, 'html', settings.DEFAULT_CHARSET)
- msgAlternative.attach(msgText)
- # This is the alternative plain text message.
- msgText =
- MIMEText(strip_spaces_between_tags(strip_tags(message)), 'plain',
- settings.DEFAULT_CHARSET)
- msgAlternative.attach(msgText)
- # We send the actual message
- try:
- server.sendmail(from_email, recipient_list, msgRoot.as_string())
- num_sent += 1
- except:
- if not fail_silently:
- raise
- # We quit elegantly
- try:
- server.quit()
- except:
- if fail_silently:
- return
- raise
- return num_sent
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement