Example #1
0
    def send(self):
        #Create the weekmail content and send it.
        html_parser = html.parser.HTMLParser()
        content = {'weekmail': html_parser.unescape(self)}
        mail_content_txt = render_to_string('communication/weekmail.txt',
                                            content)
        mail_content_html = render_to_string('communication/weekmail.html',
                                            content)

        #You can change the weekmail recipients here.
        recipients = settings.WEEKMAIL_RECIPIENTS
        sender = settings.DEFAULT_FROM_EMAIL
        try:
            mail = EmailMultiAlternatives()
            mail.subject = _('[Weekmail] %s') % (self.subject)
            mail.body = mail_content_txt
            mail.from_email = sender
            mail.to = recipients
            mail.cc = [sender,]
            mail.attach_alternative(mail_content_html, "text/html")
            for attachment in self.attached.all():
                mail.attach_file(attachment.file.path)
            mail.send()
            self.sent_date = timezone.now()
            self.save()
            return True
        except SMTPException:
            return False
        return False
Example #2
0
def notify_by_email(sender,
                    to,
                    subject,
                    message_content,
                    cc=False,
                    attachment=False,
                    template='default.txt'):
    from django.core.mail import EmailMessage
    from django.core.mail import EmailMultiAlternatives
    is_array = lambda var: isinstance(var, (list, tuple))

    if not sender: sender = settings.EMAILS['sender']['default']
    email = EmailMultiAlternatives(subject=str(settings.EMAILS['tag']) + " " +
                                   str(subject),
                                   from_email=sender,
                                   to=[to])
    #  email.esp_extra = {"sender_domain": settings.EMAIL_SENDER_DOMAIN}
    if template:
        message_content['FOOTER'] = settings.EMAILS['footer']
        email.body = render_to_string(template, message_content)
    else:
        email.body = str(message_content)
    if attachment:
        if is_array(attachment):
            for a in attachment:
                attach_to_email(email, a)
        else:
            attach_to_email(email, attachment)
    if cc: email.cc = [cc]

    try:
        email.send()
        return True
    except:
        return False
Example #3
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, self.from_address
            text_content = self.content

            msg = EmailMultiAlternatives(subject, text_content, from_email)

            if self.reply_to:
                msg.reply_to = [email.strip() for email in self.reply_to.split(',')
                                if email.strip()]

            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")

            msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()]
            msg.cc = [email.strip() for email in self.cc_address.split(',') if email.strip()]
            msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                path = attachment.file_attachment.path
                if os.path.isfile(path):
                    with open(path, 'rb') as f:
                        content = f.read()
                    msg.attach(attachment.original_filename, content, None)
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
Example #4
0
File: mail.py Project: La0/coach
  def build(self, context, headers=None):

    # Activate language
    translation.activate(self.language)

    # Render template
    site = get_current_site(None)
    message = u'Envoyé via %s' % site
    context.update({
      'site' : site,
    })
    mail_html = render_to_string(self.template, context)
    if settings.DEBUG:
      self.dump(mail_html)

    # Configure mail
    mail = EmailMultiAlternatives(self.subject, message, headers=headers)
    mail.to = self.to
    mail.cc = self.cc

    # Attach the rendered html
    mail.attach_alternative(mail_html, 'text/html')

    # Do not send, it's responsability of caller
    return mail
 def send_mail(self, sender, recipients, context=None, cc=None, bcc=None, sender_name="", attachments=None):
     """
     This method sends the mail with the given parameters, replacing any variable fields with those in the context
     """
     if isinstance(recipients, basestring):
         recipients = [recipients]#To avoid exceptions in case there is a single recipient
     if cc is None:
         cc = [] 
     if bcc is None:
         bcc = [] 
     if attachments is None:
         attachments = {}
     plainBody = Template(self.email_object.plainBody).render(Context(context))
     htmlBody = Template(self.email_object.htmlBody).render(Context(context))
     email = EmailMultiAlternatives()
     email.subject = Template(self.email_object.subject).render(Context(context))
     email.body = plainBody
     email.attach_alternative(htmlBody, 'text/html')
     email.from_email="%s <%s>" %(sender_name, sender)
     email.to = recipients
     email.cc = cc
     email.bcc = bcc
     for attachment in self.email_object.attachments.all():
         email.attach("%s.%s" % (attachment.name, attachment.fileAttachment.file.name.split(".")[-1]), attachment.fileAttachment.file.read())
     for attachment in attachments:
         email.attach(attachment['filename'].encode('ascii', 'ignore'), attachment['data'])
     return email.send()
Example #6
0
def notify_by_email(sender,to,subject,message_content,cc=False,attachment=False,template='default.txt'):
  from django.core.mail import EmailMessage
  from django.core.mail import EmailMultiAlternatives
  is_array = lambda var: isinstance(var, (list, tuple))

  if not sender: sender = settings.EMAILS['sender']['default']
  email = EmailMultiAlternatives(
                subject=str(settings.EMAILS['tag']) + " " + str(subject),
                from_email=sender,
                to=[to]
          )
#  email.esp_extra = {"sender_domain": settings.EMAIL_SENDER_DOMAIN}
  if template:
    message_content['FOOTER'] = settings.EMAILS['footer']
    email.body = render_to_string(template,message_content)
  else: email.body = str(message_content)
  if attachment:
    if is_array(attachment):
      for a in attachment: attach_to_email(email,a)
    else: attach_to_email(email,attachment)
  if cc: email.cc=[cc]

  try:
    email.send()
    return True
  except:
    return False
 def sendMail(self, mailFrom='*****@*****.**', mailTo=None, mailCC=None, mailBCC=None, replyTo=None, subject=None, bodyHTML=None, bodyText=None):
     surpress = (EmailSuppression.objects.filter(suppression_date=date.today()).count() > 0)
     
     if surpress:
         log.warn("Surpressing e-mail")
         return
         
     if bodyText and bodyHTML:
         message = EmailMultiAlternatives()
         message.body = bodyText
         message.attach_alternative(transform(bodyHTML), "text/html")
         
     elif bodyText:
         message = EmailMessage()
         message.body = bodyText
         
     elif bodyHTML:
         message = EmailMessage()
         message.body = transform(bodyHTML)
         message.content_subtype = "html"
     else:
         raise TypeError("bodyHTML or bodyText must be set")
     
     if not (mailTo or mailCC or mailBCC):
         raise TypeError("Message must have at least one recipient")
     
     if subject:
         message.subject = subject
     
     
     overrideEmail = None
     
     #Try to get override email from settings
     try:
          overrideEmail = [settings.ENRICHMENT_OVERRIDE_EMAIL]
     except AttributeError:
         pass
     
     #Take presidence on the parameter
     if self.overrideEmail:
         overrideEmail = self.overrideEmail
     
     if not overrideEmail:
         if mailTo:
             message.to = list(mailTo)
 
         if mailCC:
             message.cc = list(mailCC)
 
         if mailBCC:
             message.bcc = list(mailBCC)
     else:
         message.to = overrideEmail
     
     if replyTo:
         message.reply_to = list(replyTo)
     
             
     message.from_email = mailFrom
     message.send()
Example #8
0
    def build(self, context, headers=None):

        # Activate language
        translation.activate(self.language)

        # Render template
        site = get_current_site(None)
        message = u'Envoyé via %s' % site
        context.update({
            'site': site,
        })
        mail_html = render_to_string(self.template, context)
        if settings.DEBUG:
            self.dump(mail_html)

        # Configure mail
        mail = EmailMultiAlternatives(self.subject, message, headers=headers)
        mail.to = self.to
        mail.cc = self.cc

        # Attach the rendered html
        mail.attach_alternative(mail_html, 'text/html')

        # Do not send, it's responsability of caller
        return mail
Example #9
0
    def _send(self):
        if not self.sent:
            self.last_attempt = timezone.now()

            subject, from_email = self.subject, self.from_address
            text_content = self.content

            msg = EmailMultiAlternatives(subject, text_content, from_email)

            if self.reply_to:
                msg.extra_headers.update({"reply-to": self.reply_to})

            if self.html_content:
                html_content = self.html_content
                msg.attach_alternative(html_content, "text/html")

            msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()]
            msg.cc = [email.strip() for email in self.cc_address.split(',') if email.strip()]
            msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()]

            # Add any additional attachments
            for attachment in self.attachment_set.all():
                path = attachment.file_attachment.path
                if os.path.isfile(path):
                    with open(path, 'rb') as f:
                        content = f.read()
                    msg.attach(attachment.original_filename, content, None)
            try:
                msg.send()
                self.sent = True
            except Exception as e:
                self.do_not_send = True
                logger.error('Mail Queue Exception: {0}'.format(e))
            self.save()
Example #10
0
 def _setup_email(self):
     msg = EmailMultiAlternatives(self.get_rendered_subject(),
                                  self.get_plain_text_body(),
                                  self.from_address,
                                  self._normalize_to_iterable(self.to))
     if self.cc:
         msg.cc = self._normalize_to_iterable(self.cc)
     full_bcc = self._get_bcc_with_debugging_copy()
     if full_bcc:
         msg.bcc = self._normalize_to_iterable(full_bcc)
     msg.attach_alternative(self.get_rendered_html_body(), "text/html")
     return msg
def _convert_to_django_msg(msg):
    body, alternatives = _get_content(msg)
    if alternatives:
        email = EmailMultiAlternatives(body=body, alternatives=alternatives)
    else:
        email = EmailMessage(body=body)
    email.subject = _parse_header(msg["Subject"])
    email.to = _parse_header(msg["To"])
    email.cc = _parse_header(msg.get("Cc", None))
    email.bcc = _parse_header(msg.get("Bcc", None))
    email.from_email = _parse_header(msg["From"])
    return email
Example #12
0
def _convert_to_django_msg(msg):
    body, alternatives = _get_content(msg)
    if alternatives:
        email = EmailMultiAlternatives(body=body, alternatives=alternatives)
    else:
        email = EmailMessage(body=body)
    email.subject = _parse_header(msg['Subject'])
    email.to = _parse_header(msg['To'])
    email.cc = _parse_header(msg.get('Cc', None))
    email.bcc = _parse_header(msg.get('Bcc', None))
    email.from_email = _parse_header(msg['From'])
    return email
Example #13
0
    def send_email_html(self, template, context):
        html_content = render_to_string(template, context)
        text_content = strip_tags(html_content).strip()
        email = EmailMultiAlternatives()
        if self.email_subject:
            email.subject = self.email_subject
        if self.email_to:
            email.to = [x.strip() for x in self.email_to.split(',')]
        if self.email_cc:
            email.cc = [x.strip() for x in self.email_cc.split(',')]
        if self.email_bcc:
            email.bcc = [x.strip() for x in self.email_bcc.split(',')]
        if self.email_reply_to:
            email.reply_to = [
                x.strip() for x in self.email_reply_to.split(',')
            ]
        # if self.email_msg:
        #     email.body = msg

        email.body = html_content
        email.attach_alternative(text_content, 'text/plain')

        email.content_subtype = "html"
        email.mixed_subtype = 'related'

        fp = open('static/image/logo.png', 'rb')
        msg_img1 = MIMEImage(fp.read())
        fp.close()
        msg_img1.add_header('Content-ID', '<{}>'.format("logo.png"))
        email.attach(msg_img1)

        fp = open(context['order'].door_image.image.url.replace('/', '', 1),
                  'rb')
        msg_img2 = MIMEImage(fp.read())
        fp.close()
        msg_img2.add_header('Content-ID', '<{}>'.format("door.png"))
        email.attach(msg_img2)

        fp = open(context['order'].frame_image.image.url.replace('/', '', 1),
                  'rb')
        msg_img3 = MIMEImage(fp.read())
        fp.close()
        msg_img3.add_header('Content-ID', '<{}>'.format("frame.png"))
        email.attach(msg_img3)

        fp = open(context['order'].handle.image.url.replace('/', '', 1), 'rb')
        msg_img4 = MIMEImage(fp.read())
        fp.close()
        msg_img4.add_header('Content-ID', '<{}>'.format("handle.png"))
        email.attach(msg_img4)

        return email.send(fail_silently=True)
def send_email(  # pylint: disable=too-many-arguments,too-many-locals,bad-continuation
    name: str,
    email: str,
    subject: str,
    message: str,
    obj: object = None,
    cc_list: list = None,
    template: str = EMAIL_TEMPLATE,
    template_path: str = EMAIL_TEMPLATE_PATH,
):
    """
    Send a generic email.

    :param name: name of person
    :param email: email address to send to
    :param subject: the email's subject
    :param message: the email's body text
    :param obj: the object in question
    :param cc_list: the list of email address to "CC"
    :param template: the template to use
    """
    context = {
        "name": name,
        "subject": subject,
        "message": message,
        "object": obj,
        "SITE": Site.objects.get_current(),
    }
    email_subject = render_to_string(
        f"{template_path}/{template}_email_subject.txt",
        context).replace("\n", "")
    email_txt_body = render_to_string(
        f"{template_path}/{template}_email_body.txt", context)
    email_html_body = render_to_string(
        f"{template_path}/{template}_email_body.html",
        context).replace("\n", "")

    subject = email_subject
    from_email = settings.DEFAULT_FROM_EMAIL
    to_email = f"{name} <{email}>"
    text_content = email_txt_body
    html_content = email_html_body
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
    if cc_list:
        msg.cc = cc_list
    msg.attach_alternative(html_content, "text/html")

    return msg.send(fail_silently=True)
Example #15
0
    def message(self):
        m = EmailMultiAlternatives(self.subject, self.body)
        m.to = self.to
        m.cc = self.cc
        m.bcc = self.bcc
        m.from_email = self.from_email

        m.alternatives = \
            [(att.content, att.mimetype) for att in self.alternatives()]
        for attachment in self.attachments():
            m.attach(attachment.filename, attachment.content.read(),
                     attachment.mimetype)

        m.extra_headers = self.extra_headers

        return m
Example #16
0
def _convert_to_django_msg(msg):

    from django.core.mail import EmailMessage, EmailMultiAlternatives

    body, alternatives = _get_content(msg)
    if alternatives:
        email = EmailMultiAlternatives(body=body,
                                       alternatives=alternatives)
    else:
        email = EmailMessage(body=body)
    email.subject = _parse_header(msg['Subject'])
    email.to = _parse_header(msg['To'])
    email.cc = _parse_header(msg.get('Cc', None))
    email.bcc = _parse_header(msg.get('Bcc', None))
    email.from_email = _parse_header(msg['From'])
    return email
Example #17
0
def send_email(  # pylint: disable=too-many-arguments, too-many-locals
        name: str, email: str, subject: str, message: str, obj: object = None,
        cc_list: list = None, template: str = 'generic'):
    """
    Sends a generic email

    :param name: name of person
    :param email: email address to send to
    :param subject: the email's subject
    :param message: the email's body text
    :param obj: the object in question
    :param cc_list: the list of email address to "CC"
    :param template: the template to use
    """
    context = {
        'name': name,
        'subject': subject,
        'message': message,
        'object': obj,
        'SITE': Site.objects.get_current()
    }
    email_subject = render_to_string(
        f'small_small_hr/email/{template}_email_subject.txt',
        context).replace('\n', '')
    email_txt_body = render_to_string(
        f'small_small_hr/email/{template}_email_body.txt', context)
    email_html_body = render_to_string(
        f'small_small_hr/email/{template}_email_body.html', context
        ).replace('\n', '')

    subject = email_subject
    from_email = settings.DEFAULT_FROM_EMAIL
    to_email = f'{name} <{email}>'
    text_content = email_txt_body
    html_content = email_html_body
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
    if cc_list:
        msg.cc = cc_list
    msg.attach_alternative(html_content, "text/html")

    return msg.send(fail_silently=True)
Example #18
0
 def send_mail(self,
               sender,
               recipients,
               context=None,
               cc=None,
               bcc=None,
               sender_name="",
               attachments=None):
     """
     This method sends the mail with the given parameters, replacing any variable fields with those in the context
     """
     if cc is None:
         cc = []
     if bcc is None:
         bcc = []
     if attachments is None:
         attachments = {}
     plainBody = Template(self.email_object.plainBody).render(
         Context(context))
     htmlBody = Template(self.email_object.htmlBody).render(
         Context(context))
     email = EmailMultiAlternatives()
     email.subject = Template(self.email_object.subject).render(
         Context(context))
     email.body = plainBody
     email.attach_alternative(htmlBody, 'text/html')
     email.from_email = "%s <%s>" % (sender_name, sender)
     email.to = recipients
     email.cc = cc
     email.bcc = bcc
     for attachment in self.email_object.attachments.all():
         email.attach(
             "%s.%s" % (attachment.name,
                        attachment.fileAttachment.file.name.split(".")[-1]),
             attachment.fileAttachment.file.read())
     for attachment in attachments:
         email.attach(attachment['filename'].encode('ascii', 'ignore'),
                      attachment['data'])
     email.tags = map(unicode.strip, self.email_object.tags.split(','))
     email.track_clicks = True
     return email.send()
def send_messages(data,
                  template,
                  sheet_title,
                  data_index=None,
                  email_to=None,
                  email_column=None,
                  bcc_column=None,
                  email_splitter=',',
                  email_settings=None):
    heads = data[0]

    if email_settings:
        smtp_host = email_settings['smtp_host']
        smtp_port = email_settings['smtp_port']
        smtp_username = email_settings['smtp_username']
        smtp_password = email_settings['smtp_password']

        mail_backend = EmailBackend(host=smtp_host,
                                    port=smtp_port,
                                    password=smtp_password,
                                    username=smtp_username,
                                    use_tls=True,
                                    timeout=10)
    else:
        mail_backend = None
    if data_index != None:
        data = data[1:][data_index]
        current_task.update_state(state='PROGRESS',
                                  meta={
                                      'current': 0,
                                      'total': 1
                                  })
        html_template = generate_email_template(template, heads, data)
        if email_settings:
            pass
            from_email = email_settings['smtp_from_email']
        else:
            from_email = settings.DEFAULT_FROM_EMAIL
        if email_to:
            sended = send_mail(sheet_title,
                               message=strip_tags(html_template),
                               html_message=html_template,
                               recipient_list=(email_to, ),
                               from_email=from_email,
                               connection=mail_backend)
            current_task.update_state(state='PROGRESS',
                                      meta={
                                          'current': 1,
                                          'total': 1
                                      })
    else:
        data = data[1:]
        data_size = len(data)
        current_task.update_state(state='PROGRESS',
                                  meta={
                                      'current': 0,
                                      'total': data_size
                                  })

        if email_column:
            email_column_index = heads.index(email_column)
        else:
            email_column_index = None

        if bcc_column:
            bcc_column_index = heads.index(bcc_column)
        else:
            bcc_column_index = None

        for i, el_data in enumerate(data):
            sleep(1)
            email_to = el_data[email_column_index]
            html_template = generate_email_template(template, heads, el_data)
            if email_settings:
                from_email = email_settings['smtp_from_email']
            else:
                from_email = settings.DEFAULT_FROM_EMAIL
            msg = EmailMultiAlternatives(subject=sheet_title,
                                         body=strip_tags(html_template),
                                         from_email=from_email)
            msg.attach_alternative(html_template, 'text/html')
            if bcc_column_index:
                msg.bcc = el_data[bcc_column_index].split(email_splitter)
            if email_column_index:
                msg.cc = el_data[email_column_index].split(email_splitter)
            if mail_backend:
                msg.connection = mail_backend

            msg.send()

            current_task.update_state(state='PROGRESS',
                                      meta={
                                          'current': i,
                                          'total': data_size
                                      })
Example #20
0
    def setUp(self):
        organization, created = Organization.objects.get_or_create(name='Example Corp')

        self.mailbox = Mailbox.objects.create(
            name='test_mailbox',
            uri='maildir://' + MAILDIR_PATH,
            from_email='*****@*****.**'
        )

        # clear any pre-existing messages in the local mailbox
        self.maildir.clear()

        self.team, created = Team.objects.get_or_create(
            name='Example Department',
            slug='example_dept',
            mailbox=self.mailbox
        )

        self.ticket, created = Ticket.objects.get_or_create(
            title='Testing 123 Ticket',
            organization=organization,
            priority=4
        )
        self.ticket.teams.add(self.team)

        self.sender_email = EmailAddress.objects.create(email_address=self._sender_email)
        self.sender = Person.objects.create(
            first_name='sender_first_name',
            last_name='sender_last_name'
        )
        self.sender.email_addresses.add(self.sender_email)

        self.recipient_email = EmailAddress.objects.create(email_address=self._recipient_email)
        self.recipient = Person.objects.create(
            first_name='recipient_first_name',
            last_name='recipient_last_name',
        )
        self.recipient.email_addresses.add(self.recipient_email)

        cc_people, cc_emails = list(), list()
        for addr in self._cc_emails:
            email = EmailAddress.objects.create(email_address=addr)
            person = Person.objects.create(
                first_name='{}_first_name'.format(addr.split('@')[0]),
                last_name='{}_last_name'.format(addr.split('@')[0])
            )
            person.email_addresses.add(email)
            cc_emails.append(email)
            cc_people.append(person)

        self.cc_emails = cc_emails
        self.cc_people = cc_people

        email_message = EmailMultiAlternatives()
        email_message.body = 'Test message testing 123'
        email_message.from_email = self._sender_email
        email_message.to = self._recipient_email,
        email_message.cc = self._cc_emails
        email_message.subject = 'tests message subject'
        email_message.extra_headers['Message-Id'] = 'unique_id_goes_here'
        self.email_message_no_hashid_plain = copy.deepcopy(email_message)

        email_message.attach_alternative(
            '<html><body><p>Test message testing 123</p></body></html>',
            'text/html'
        )
        self.email_message_no_hashid = email_message
Example #21
0
def email_order(permanence_id, all_producers=True, closed_deliveries_id=None, producers_id=None):
    from repanier.apps import REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_BOARD, \
        REPANIER_SETTINGS_GROUP_NAME, REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_PRODUCER, \
        REPANIER_SETTINGS_SEND_ABSTRACT_ORDER_MAIL_TO_PRODUCER, \
        REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_CUSTOMER
    cur_language = translation.get_language()
    for language in settings.PARLER_LANGUAGES[settings.SITE_ID]:
        language_code = language["code"]
        translation.activate(language_code)
        permanence = Permanence.objects.get(id=permanence_id)
        config = Configuration.objects.get(id=DECIMAL_ONE)
        filename = "{0}-{1}.xlsx".format(
                        slugify(_("Order")),
                        slugify(permanence)
        )
        group_filename = "{0}-{1}.xlsx".format(
            slugify(REPANIER_SETTINGS_GROUP_NAME),
            slugify(filename)
        )
        sender_email, sender_function, signature, cc_email_staff = get_signature(is_reply_to_order_email=True)
        board_composition, board_composition_and_description = get_board_composition(permanence.id)

        # Orders send to the preparation team
        group_wb = xlsx_order.export_abstract(permanence=permanence, deliveries_id=closed_deliveries_id, wb=None)
        if group_wb is not None:
            abstract_ws = group_wb.get_active_sheet()
        else:
            abstract_ws = None

        if all_producers:
            if group_wb is not None:
                # At least one order

                group_wb = xlsx_order.export_customer_label(
                    permanence=permanence, deliveries_id=closed_deliveries_id, wb=group_wb
                )
                group_wb = xlsx_order.export_preparation(
                    permanence=permanence, deliveries_id=closed_deliveries_id, wb=group_wb
                )
                group_wb = xlsx_stock.export_permanence_stock(
                    permanence=permanence, customer_price=True, wb=group_wb
                )
                group_wb = xlsx_order.export_customer(
                    permanence=permanence, deliveries_id=closed_deliveries_id, deposit=True, wb=group_wb
                )
                group_wb = xlsx_order.export_customer(
                    permanence=permanence, deliveries_id=closed_deliveries_id, wb=group_wb
                )

                to_email_board = []
                for permanence_board in PermanenceBoard.objects.filter(
                        permanence=permanence.id).order_by('?'):
                    if permanence_board.customer:
                        to_email_board.append(permanence_board.customer.user.email)

                try:
                    order_staff_mail = config.order_staff_mail
                except TranslationDoesNotExist:
                    order_staff_mail = EMPTY_STRING
                # order_staff_mail_subject = "%s - %s - %s" % (
                #     _('Permanence preparation list'), permanence, REPANIER_SETTINGS_GROUP_NAME)
                order_staff_mail_subject = "%s - %s" % (REPANIER_SETTINGS_GROUP_NAME, permanence)

                template = Template(order_staff_mail)
                context = TemplateContext({
                    'permanence_link'                  : mark_safe('<a href="http://%s%s">%s</a>' % (
                        settings.ALLOWED_HOSTS[0], reverse('order_view', args=(permanence.id,)), permanence)),
                    'board_composition'                : mark_safe(board_composition),
                    'board_composition_and_description': mark_safe(board_composition_and_description),
                    'signature'                        : mark_safe(
                        '%s<br/>%s<br/>%s' % (signature, sender_function, REPANIER_SETTINGS_GROUP_NAME))
                })
                html_content = template.render(context)
                email = EmailMultiAlternatives(
                    order_staff_mail_subject,
                    strip_tags(html_content),
                    from_email=sender_email,
                    to=to_email_board,
                    cc=cc_email_staff
                )
                if group_wb is not None:
                    email.attach(group_filename,
                                 save_virtual_workbook(group_wb),
                                 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
                email.attach_alternative(html_content, "text/html")

                if not REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_BOARD:
                    email.to = cc_email_staff
                    email.cc = []
                    email.bcc = []
                send_email(email=email)

        # Orders send to our producers
        if REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_PRODUCER:
            producer_set = Producer.objects.filter(
                permanence=permanence.id,
                language=language_code,
            ).order_by('?')
            if producers_id is not None:
                # Do not send order twice
                # all_producers is True if we are sending the order to the last group of selected producers
                producer_set = producer_set.filter(id__in=producers_id)
            for producer in producer_set:
                long_profile_name = producer.long_profile_name if producer.long_profile_name is not None else producer.short_profile_name
                wb = xlsx_order.export_producer_by_product(permanence=permanence, producer=producer, wb=None)
                if wb is None:
                    order_empty = True
                    duplicate = False
                else:
                    order_empty = False
                    if not producer.manage_replenishment:
                        duplicate = True
                        wb = xlsx_order.export_producer_by_customer(
                            permanence=permanence, producer=producer, wb=wb)
                    else:
                        duplicate = False
                try:
                    order_producer_mail = config.order_producer_mail
                except TranslationDoesNotExist:
                    order_producer_mail = EMPTY_STRING
                # order_producer_mail_subject = "%s - %s - %s" % (
                #     _('Permanence preparation list'), permanence, REPANIER_SETTINGS_GROUP_NAME)
                order_producer_mail_subject = "%s - %s" % (REPANIER_SETTINGS_GROUP_NAME, permanence)

                template = Template(order_producer_mail)
                context = TemplateContext({
                    'name'             : long_profile_name,
                    'long_profile_name': long_profile_name,
                    'order_empty'      : order_empty,
                    'duplicate'        : duplicate,
                    'permanence_link'  : mark_safe('<a href="http://%s%s">%s</a>' % (
                        settings.ALLOWED_HOSTS[0], reverse('order_view', args=(permanence.id,)), permanence)),
                    'signature'        : mark_safe(
                        '%s<br/>%s<br/>%s' % (signature, sender_function, REPANIER_SETTINGS_GROUP_NAME))
                })
                html_content = template.render(context)

                producer_invoice = models.ProducerInvoice.objects.filter(
                    producer_id=producer.id, permanence_id=permanence.id
                ).only("total_price_with_tax").order_by('?').first()
                if producer_invoice is not None \
                        and producer_invoice.total_price_with_tax < producer.minimum_order_value:
                    to = cc_email_staff
                    html_content = \
                        order_producer_mail_subject + '<br/><br/>' + html_content
                    cc = []
                    order_producer_mail_subject = _(
                        '/!\ Mail not send to our producer %s because the minimum order value has not been reached.') % long_profile_name
                else:
                    to_email_producer = []
                    if producer.email:
                        to_email_producer.append(producer.email)
                    if producer.email2:
                        to_email_producer.append(producer.email2)
                    if producer.email3:
                        to_email_producer.append(producer.email3)
                    cc = cc_email_staff
                email = EmailMultiAlternatives(
                    order_producer_mail_subject,
                    strip_tags(html_content),
                    from_email=sender_email,
                    to=to_email_producer,
                    cc=cc
                )
                if REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_PRODUCER and wb is not None:
                    if REPANIER_SETTINGS_SEND_ABSTRACT_ORDER_MAIL_TO_PRODUCER:
                        if abstract_ws is not None:
                            wb.add_sheet(abstract_ws, index=0)
                    email.attach(
                        filename,
                        save_virtual_workbook(wb),
                        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    )

                email.attach_alternative(html_content, "text/html")
                send_email(email=email)

        if all_producers:
            # Orders send to our customers only if they don't have already received it
            # ==> customerinvoice__is_order_confirm_send=False
            #     customerinvoice__permanence_id=permanence.id
            if REPANIER_SETTINGS_SEND_ORDER_MAIL_TO_CUSTOMER:
                all_producers_closed = not (ProducerInvoice.objects.filter(
                    permanence_id=permanence_id,
                    status=PERMANENCE_OPENED
                ).order_by('?').exists())
                if all_producers_closed:
                    if closed_deliveries_id is None:
                        customer_set = Customer.objects.filter(
                            represent_this_buyinggroup=False,
                            customerinvoice__is_order_confirm_send=False,
                            customerinvoice__permanence_id=permanence.id,
                            language=language_code
                        ).order_by('?')
                    else:
                        customer_set = Customer.objects.filter(
                            represent_this_buyinggroup=False,
                            customerinvoice__is_order_confirm_send=False,
                            customerinvoice__permanence_id=permanence.id,
                            customerinvoice__delivery_id__in=closed_deliveries_id,
                            language=language_code
                        ).order_by('?')
                    for customer in customer_set:
                        export_order_2_1_customer(
                            customer, filename, permanence, sender_email,
                            sender_function, signature, abstract_ws)
                        # confirm_customer_invoice(permanence_id, customer.id)
                        customer_invoice = CustomerInvoice.objects.filter(
                            customer_id=customer.id,
                            permanence_id=permanence_id
                        ).order_by('?').first()
                        customer_invoice.confirm_order()
                        customer_invoice.save()
    translation.activate(cur_language)