email is a django.core.mail.EmailMessage object
972921
def email_embed_image(email, img_content_id, img_data):
    
    img = MIMEImage(img_data)
    img.add_header('Content-ID', '<%s>' % img_content_id)
    img.add_header('Content-Disposition', 'inline')
    email.attach(img)
1226879
def send_all():
    
    # The actual backend to use for sending, defaulting to the Django default.
    # To make testing easier this is not stored at module level.
    EMAIL_BACKEND = getattr(
        settings,
        "MAILER_EMAIL_BACKEND",
        "django.core.mail.backends.smtp.EmailBackend"
    )

    acquired, lock = acquire_lock()
    if not acquired:
        return

    start_time = time.time()

    deferred = 0
    sent = 0

    try:
        connection = None
        for message in prioritize():
            try:
                if connection is None:
                    connection = get_connection(backend=EMAIL_BACKEND)
                logging.info("sending message '{0}' to {1}".format(
                    message.subject,
                    ", ".join(message.to_addresses))
                )
                email = message.email
                if email is not None:
                    email.connection = connection
                    if not hasattr(email, 'reply_to'):
                        # Compatability fix for EmailMessage objects
                        # pickled when running < Django 1.8 and then
                        # unpickled under Django 1.8
                        email.reply_to = []
                    ensure_message_id(email)
                    email.send()

                    # connection can't be stored in the MessageLog
                    email.connection = None
                    message.email = email  # For the sake of MessageLog
                    MessageLog.objects.log(message, RESULT_SUCCESS)
                    sent += 1
                else:
                    logging.warning("message discarded due to failure in converting from DB. Added on '%s' with priority '%s'" % (message.when_added, message.priority))  # noqa
                message.delete()

            except (socket_error, smtplib.SMTPSenderRefused,
                    smtplib.SMTPRecipientsRefused,
                    smtplib.SMTPDataError,
                    smtplib.SMTPAuthenticationError) as err:
                message.defer()
                logging.info("message deferred due to failure: %s" % err)
                MessageLog.objects.log(message, RESULT_FAILURE, log_message=str(err))
                deferred += 1
                # Get new connection, it case the connection itself has an error.
                connection = None

            # Check if we reached the limits for the current run
            if _limits_reached(sent, deferred):
                break

            _throttle_emails()

    finally:
        release_lock(lock)

    logging.info("")
    logging.info("%s sent; %s deferred;" % (sent, deferred))
    logging.info("done in %.2f seconds" % (time.time() - start_time))
228534
def email_verifier(self, email, raw=False):
        
        params = {'email': email, 'api_key': self.api_key}

        endpoint = self.base_endpoint.format('email-verifier')

        return self._query_hunter(endpoint, params, raw=raw)
168808
def Email(
        self,
        From,
        To,
        Cc=None,
        Bcc=None,
        Subject=None,
        Tag=None,
        HtmlBody=None,
        TextBody=None,
        Metadata=None,
        ReplyTo=None,
        Headers=None,
        TrackOpens=None,
        TrackLinks="None",
        Attachments=None,
    ):
        
        return Email(
            manager=self,
            From=From,
            To=To,
            Cc=Cc,
            Bcc=Bcc,
            Subject=Subject,
            Tag=Tag,
            HtmlBody=HtmlBody,
            TextBody=TextBody,
            Metadata=Metadata,
            ReplyTo=ReplyTo,
            Headers=Headers,
            TrackOpens=TrackOpens,
            TrackLinks=TrackLinks,
            Attachments=Attachments,
        )
260974
def turn_emails_off(view_func):
    """"""

    # Dummy email backend so no emails are sent.
    EMAIL_BACKEND_DUMMY = 'django.core.mail.backends.dummy.EmailBackend'

    def decorated(request, *args, **kwargs):
        orig_email_backend = settings.EMAIL_BACKEND
        settings.EMAIL_BACKEND = EMAIL_BACKEND_DUMMY

        response = view_func(request, *args, **kwargs)
        settings.EMAIL_BACKEND = orig_email_backend
        return response

    return decorated
80170
def message(self, do_html=True, custom_email_template=None):
        
        context = {
            'build': self.build,
            'important_metadata': self.important_metadata,
            'metadata': self.metadata,
            'notification': self,
            'previous_build': self.previous_build,
            'regressions_grouped_by_suite': self.comparison.regressions_grouped_by_suite,
            'fixes_grouped_by_suite': self.comparison.fixes_grouped_by_suite,
            'known_issues': self.known_issues,
            'regressions': self.comparison.regressions,
            'fixes': self.comparison.fixes,
            'thresholds': self.thresholds,
            'settings': settings,
            'summary': self.summary,
        }

        html_message = ''
        if custom_email_template:
            text_template = jinja2.from_string(custom_email_template.plain_text)
            text_message = text_template.render(context)

            if do_html:
                html_template = jinja2.from_string(custom_email_template.html)
                html_message = html_template.render(context)
        else:
            text_message = render_to_string(
                'squad/notification/diff.txt.jinja2',
                context=context,
            )
            if do_html:
                html_message = render_to_string(
                    'squad/notification/diff.html.jinja2',
                    context=context,
                )
        return (text_message, html_message)
577951
def email(sender=None, receivers=(), cc=(), bcc=(),
          subject=None, content=None, encoding='utf8',
          attachments=()):
    
    enclosure = [HTML(content, encoding)]
    enclosure.extend(Attachment(k) for k in attachments)
    return Collection(
        *enclosure,
        headers=[
            headers.subject(subject),
            headers.sender(sender),
            headers.to(*receivers),
            headers.cc(*cc),
            headers.bcc(*bcc),
            headers.date(),
            headers.message_id(),
        ]
    )
337169
def send(email, subject, opts = {})
      if email.nil? or subject.nil?
        raise ArgumentError, 'Email Address or Subject is missing'
      else
        message = {
          from_name: Octo.get_config(:email_sender).fetch(:name),
          from_email: Octo.get_config(:email_sender).fetch(:email),

          subject: subject,

          text: opts.fetch('text', nil),
          html: opts.fetch('html', nil),

          to: [{
            email: email,
            name: opts.fetch('name', nil)
          }]
        }
        # Pass the message to resque only when mandrill key is present
        _mandrill_config = ENV['MANDRILL_API_KEY'] || Octo.get_config(:mandrill_api_key)
        if _mandrill_config and !_mandrill_config.empty?
          enqueue_msg(message)
        end
      end
    end
398656
def get(self):
        
        mail = {
            'from': self._get_or_none(self.from_email),
            'subject': self._get_or_none(self.subject),
            'personalizations': [p.get() for p in self.personalizations or []],
            'content': [c.get() for c in self.contents or []],
            'attachments': [a.get() for a in self.attachments or []],
            'template_id': self._get_or_none(self.template_id),
            'sections': self._flatten_dicts(self.sections),
            'headers': self._flatten_dicts(self.headers),
            'categories': [c.get() for c in self.categories or []],
            'custom_args': self._flatten_dicts(self.custom_args),
            'send_at':  self._get_or_none(self.send_at),
            'batch_id': self._get_or_none(self.batch_id),
            'asm': self._get_or_none(self.asm),
            'ip_pool_name': self._get_or_none(self.ip_pool_name),
            'mail_settings': self._get_or_none(self.mail_settings),
            'tracking_settings': self._get_or_none(self.tracking_settings),
            'reply_to': self._get_or_none(self.reply_to),
        }

        return {key: value for key, value in mail.items()
                if value is not None and value != [] and value != {}}
69275
def save_email(self, list_name, email_msg, index):
        """"""

        msg_id = email_msg.get('Message-ID')
        if not msg_id:
            return

        # Update last imported message into the DB
        mailinglist, created = MailingList.objects.get_or_create(
            name=list_name
        )
        mailinglist.last_imported_index = index

        if created:
            # if the mailinglist is newly created it's sure that the message
            #   is not in the DB yet.
            self.create_email(mailinglist, email_msg)

        else:
            # If the message is already at the database don't do anything
            try:
                Message.all_objects.get(
                    message_id=msg_id,
                    thread__mailinglist=mailinglist
                )

            except Message.DoesNotExist:
                self.create_email(mailinglist, email_msg)

        mailinglist.save()
691923
def send_template(self, template, to, reply_to=None, **context):
        
        mail_data = self.parse_template(template, **context)
        subject = mail_data["subject"]
        body = mail_data["body"]
        del(mail_data["subject"])
        del(mail_data["body"])

        return self.send(to=to,
                         subject=subject,
                         body=body,
                         reply_to=reply_to,
                         **mail_data)
923535
def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs):
    

    eft = EmailFromTemplate(name=name)
    eft.subject = subject
    eft.context = ctx_dict
    eft.get_object()
    eft.render_message()
    eft.send_email(send_to=send_to, **kwargs)
649386
def send_email(recipients, subject, text_content=None, html_content=None, from_email=None, use_base_template=True, category=None, fail_silently=False, language=None, cc=None, bcc=None, attachments=None, headers=None, bypass_queue=False, bypass_hijacking=False, attach_files=None):
    
    from django.conf import settings
    if not bypass_queue and hasattr(settings, 'MAILING_USE_CELERY') and settings.MAILING_USE_CELERY:
        from celery.execute import send_task
        return send_task('mailing.queue_send_email',[recipients, subject, text_content, html_content, from_email, use_base_template, category, fail_silently, language if language else translation.get_language(), cc, bcc, attachments, headers, bypass_hijacking, attach_files])
    else:

        header_category_value = '%s%s' % (settings.MAILING_HEADER_CATEGORY_PREFIX if hasattr(settings, 'MAILING_HEADER_CATEGORY_PREFIX') else '', category)
        # Check for sendgrid support and add category header
        # --------------------------------
        if hasattr(settings, 'MAILING_USE_SENDGRID'):
            send_grid_support = settings.MAILING_USE_SENDGRID
        else:
            send_grid_support = False

        if not headers:
            headers = dict()        
        if send_grid_support and category:
            headers['X-SMTPAPI'] = '{"category": "%s"}' % header_category_value

        # Check for Mailgun support and add label header
        # --------------------------------
        if hasattr(settings, 'MAILING_USE_MAILGUN'):
            mailgun_support = settings.MAILING_USE_MAILGUN
        else:
            mailgun_support = False

        if not headers:
            headers = dict()        
        if mailgun_support and category:
            headers['X-Mailgun-Tag'] = header_category_value


        # Ensure recipients are in a list
        # --------------------------------
        if isinstance(recipients, basestring):
            recipients_list = [recipients]
        else:
            recipients_list = recipients

        # Check if we need to hijack the email
        # --------------------------------
        if hasattr(settings, 'MAILING_MAILTO_HIJACK') and not bypass_hijacking:
            headers['X-MAILER-ORIGINAL-MAILTO'] = ','.join(recipients_list)
            recipients_list = [settings.MAILING_MAILTO_HIJACK]

        if not subject:
            raise MailerMissingSubjectError('Subject not supplied')

        # Send ascii, html or multi-part email
        # --------------------------------
        if text_content or html_content:
            if use_base_template:
                prev_language = translation.get_language()
                language and translation.activate(language)
                text_content = render_to_string('mailing/base.txt', {'mailing_text_body': text_content, 'mailing_subject': subject, 'settings': settings}) if text_content else None
                html_content = render_to_string('mailing/base.html', {'mailing_html_body': html_content, 'mailing_subject': subject, 'settings': settings}) if html_content else None
                translation.activate(prev_language)
            msg = EmailMultiAlternatives(subject, text_content if text_content else html_content, from_email if from_email else settings.DEFAULT_FROM_EMAIL, recipients_list, cc=cc, bcc=bcc, attachments=attachments, headers = headers)
            if html_content and text_content:
                msg.attach_alternative(html_content, "text/html")
            elif html_content: # Only HTML
                msg.content_subtype = "html"

            # Attach files through attach_files helper
            # --------------------------------
            if attach_files:
                for att in attach_files:  # attachments are tuples of (filepath, mimetype, filename)
                    with open(att[0], 'rb') as f:
                        content = f.read()
                    msg.attach(att[2], content, att[1])

            # Send email
            # --------------------------------

            msg.send(fail_silently=fail_silently)
        else:
            raise MailerInvalidBodyError('No text or html body supplied.')
409859
def set_email(self, email, _vars=None, lists=None, templates=None, verified=0, optout=None, send=None, send_vars=None):
        
        _vars = _vars or {}
        lists = lists or []
        templates = templates or []
        send_vars = send_vars or []
        data = {'email': email,
                'vars':  _vars.copy(),
                'lists': lists,
                'templates': templates,
                'verified': int(verified)}
        if optout is not None:
            data['optout'] = optout
        if send is not None:
            data['send'] = send
        if send_vars:
            data['send_vars'] = send_vars
        return self.api_post('email', data)
21253
def email(self, comment, content_object, request):
        
        if not self.email_notification:
            return

        send_comment_posted(comment, request)
1244079
def clean_email(self):
        
        if self.cleaned_data['email'].lower() == self.user.email:
            raise forms.ValidationError(_(u"You're already known under "
                                                "this email address."))
        if get_user_model().objects.filter(
                email__iexact=self.cleaned_data['email']).exclude(
                    email__iexact=self.user.email):
            raise forms.ValidationError(_(u'This email address is already '
                        'in use. Please supply a different email address.'))
        return self.cleaned_data['email']
51296
def clean(self):
        
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)