Example #1
0
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', '*****@*****.**', ['*****@*****.**'])
        email.encoding = 'iso-8859-1'
        message = email.message()
        self.assertMessageHasHeaders(message, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/plain; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable'),
            ('Subject', 'Subject'),
            ('From', '*****@*****.**'),
            ('To', '*****@*****.**')})
        self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.')

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = 'Firstname Sürname is a great guy.'
        html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
        msg = EmailMultiAlternatives('Subject', text_content, '*****@*****.**', ['*****@*****.**'])
        msg.encoding = 'iso-8859-1'
        msg.attach_alternative(html_content, "text/html")
        payload0 = msg.message().get_payload(0)
        self.assertMessageHasHeaders(payload0, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/plain; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable')})
        self.assertTrue(payload0.as_string().endswith('\n\nFirstname S=FCrname is a great guy.'))
        payload1 = msg.message().get_payload(1)
        self.assertMessageHasHeaders(payload1, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/html; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable')})
        self.assertTrue(payload1.as_string().endswith('\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>'))
Example #2
0
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage("Subject", "Firstname Sürname is a great guy.", "*****@*****.**", ["*****@*****.**"])
        email.encoding = "iso-8859-1"
        message = email.message()
        self.assertTrue(
            message.as_string().startswith(
                'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]'
            )
        )
        self.assertEqual(message.get_payload(), "Firstname S=FCrname is a great guy.")

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = "Firstname Sürname is a great guy."
        html_content = "<p>Firstname Sürname is a <strong>great</strong> guy.</p>"
        msg = EmailMultiAlternatives("Subject", text_content, "*****@*****.**", ["*****@*****.**"])
        msg.encoding = "iso-8859-1"
        msg.attach_alternative(html_content, "text/html")
        self.assertEqual(
            msg.message().get_payload(0).as_string(),
            'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.',
        )
        self.assertEqual(
            msg.message().get_payload(1).as_string(),
            'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>',
        )
Example #3
0
    def subscription_alert(self):
        data = self.cleaned_data
        name = data['name']
        student = data['student']
        age = data['age']

        message = u'''Olá equipe,
        Acabamos de receber uma nova inscrição no Curso de Xadrez.
        {0} inscreveu o aluno {1} de {2} anos.
        Acesse o painel administrativo para mais informações e cheque o estado do pagamento no pagseguro.
        Vamos levar o Xadrez para todos!
        '''.format(name, student, age)

        html_message = u'''
        <p>Olá equipe,</p>
        <p>Acabamos de receber uma nova inscrição no Curso de Xadrez.</p>
        <p><strong>{0}</strong> inscreveu o aluno <strong>{1}</strong> de <strong>{2} anos de idade</strong>.</p>
        <p>Acesse o painel administrativo para mais informações e cheque o estado do pagamento no pagseguro.</p>
        <p>Vamos levar o Xadrez para todos!</p>
        '''.format(name, student, age)

        recipient_list = ["*****@*****.**", ]

        email_ = EmailMultiAlternatives(
            subject=u"Nova inscrição no Curso de Xadrez",
            body=message,
            from_email='*****@*****.**',
            to=recipient_list,
            headers={'Reply-To': "*****@*****.**"}
        )
        email_.encoding = "utf-8"
        email_.attach_alternative(html_message, "text/html")
        email_.send()
        return
Example #4
0
 def send_email(self):
     logger.info('开始发送邮件')
     html = """
     <!DOCTYPE html>
        <html lang="en">
         <head>
             <meta charset="UTF-8">
             <title>楼盘字典统计报表</title>
         </head>
         <body>
         </body
     </html>"""
     from_mail = '*****@*****.**'
     subject = '【楼盘字典数据报表】楼盘字典数据%s' % datetime.datetime.now().strftime(
         '%Y%m%d')
     msg = EmailMultiAlternatives(
         subject,
         html,
         from_mail,
         G_RECIPIENT_LIST,
         headers={'From': '简单家<*****@*****.**>'})
     msg.attach_file(self.report_path)
     msg.content_subtype = 'html'
     msg.encoding = 'utf-8'
     msg.send()
     logger.info('邮件发送结束')
Example #5
0
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage('Subject', 'Firstname Sürname is a great guy.',
                             '*****@*****.**', ['*****@*****.**'])
        email.encoding = 'iso-8859-1'
        message = email.message()
        self.assertTrue(message.as_string().startswith(
            'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]'
        ))
        self.assertEqual(message.get_payload(),
                         'Firstname S=FCrname is a great guy.')

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = 'Firstname Sürname is a great guy.'
        html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
        msg = EmailMultiAlternatives('Subject', text_content,
                                     '*****@*****.**', ['*****@*****.**'])
        msg.encoding = 'iso-8859-1'
        msg.attach_alternative(html_content, "text/html")
        self.assertEqual(
            msg.message().get_payload(0).as_string(),
            'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.'
        )
        self.assertEqual(
            msg.message().get_payload(1).as_string(),
            'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>'
        )
Example #6
0
    def send_mail(self):
        # https://docs.djangoproject.com/en/1.7/topics/class-based-views/generic-editing/
        # https://docs.djangoproject.com/en/1.7/topics/email/
        data = self.cleaned_data
        name = data['name']
        email = data['mail']
        phone = data['phone']
        subject = data['subject']
        message = data['message']
        cc_myself = data['cc_myself']

        html_message = u'''
        ** Contato a partir do Site Institucional feito em {0} ** <br />
        Nome: {1} <br />
        Email: {2} <br />
        Telefone: {3} <br />
        Mensagem: {4} <br />
        '''.format(datetime.now().strftime("%d/%m/%Y"), name, email, phone, message)

        recipient_list = ['*****@*****.**', ]
        if cc_myself:
            recipient_list.append(email)

        email_ = EmailMultiAlternatives(
            subject=subject,
            body=message,
            from_email='*****@*****.**',
            to=recipient_list,
            headers={'Reply-To': email}
        )
        email_.encoding = "utf-8"
        email_.attach_alternative(html_message, "text/html")
        email_.send()
        return
Example #7
0
File: tests.py Project: 6ft/django
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', '*****@*****.**', ['*****@*****.**'])
        email.encoding = 'iso-8859-1'
        message = email.message()
        self.assertMessageHasHeaders(message, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/plain; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable'),
            ('Subject', 'Subject'),
            ('From', '*****@*****.**'),
            ('To', '*****@*****.**')})
        self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.')

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = 'Firstname Sürname is a great guy.'
        html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
        msg = EmailMultiAlternatives('Subject', text_content, '*****@*****.**', ['*****@*****.**'])
        msg.encoding = 'iso-8859-1'
        msg.attach_alternative(html_content, "text/html")
        payload0 = msg.message().get_payload(0)
        self.assertMessageHasHeaders(payload0, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/plain; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable')})
        self.assertTrue(payload0.as_bytes().endswith(b'\n\nFirstname S=FCrname is a great guy.'))
        payload1 = msg.message().get_payload(1)
        self.assertMessageHasHeaders(payload1, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/html; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable')})
        self.assertTrue(payload1.as_bytes().endswith(b'\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>'))
Example #8
0
File: tests.py Project: 6ft/django
 def test_safe_mime_multipart(self):
     """
     Make sure headers can be set with a different encoding than utf-8 in
     SafeMIMEMultipart as well
     """
     headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
     subject, from_email, to = 'hello', '*****@*****.**', '"Sürname, Firstname" <*****@*****.**>'
     text_content = 'This is an important message.'
     html_content = '<p>This is an <strong>important</strong> message.</p>'
     msg = EmailMultiAlternatives('Message from Firstname Sürname', text_content, from_email, [to], headers=headers)
     msg.attach_alternative(html_content, "text/html")
     msg.encoding = 'iso-8859-1'
     self.assertEqual(msg.message()['To'], '=?iso-8859-1?q?S=FCrname=2C_Firstname?= <*****@*****.**>')
     self.assertEqual(msg.message()['Subject'], '=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=')
Example #9
0
 def test_safe_mime_multipart(self):
     """
     Make sure headers can be set with a different encoding than utf-8 in
     SafeMIMEMultipart as well
     """
     headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
     subject, from_email, to = 'hello', '*****@*****.**', '"Sürname, Firstname" <*****@*****.**>'
     text_content = 'This is an important message.'
     html_content = '<p>This is an <strong>important</strong> message.</p>'
     msg = EmailMultiAlternatives('Message from Firstname Sürname', text_content, from_email, [to], headers=headers)
     msg.attach_alternative(html_content, "text/html")
     msg.encoding = 'iso-8859-1'
     self.assertEqual(msg.message()['To'], '=?iso-8859-1?q?S=FCrname=2C_Firstname?= <*****@*****.**>')
     self.assertEqual(msg.message()['Subject'], '=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=')
def send_email_to_cohort(subject, message, students):
    """
    Send email task.
    """
    context = {'subject': subject, 'body': message}
    html_content = render_to_string(
        'rg_instructor_analytics/cohort_email_temolate.html', context)
    text_content = strip_tags(html_content)
    from_address = configuration_helpers.get_value('email_from_address',
                                                   settings.DEFAULT_FROM_EMAIL)
    msg = EmailMultiAlternatives(subject, text_content, from_address, students)
    msg.encoding = 'UTF-8'
    msg.attach_alternative(html_content, "text/html")
    msg.send(fail_silently=False)
Example #11
0
 def test_safe_mime_multipart(self):
     """
     Make sure headers can be set with a different encoding than utf-8 in
     SafeMIMEMultipart as well
     """
     headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
     subject, from_email, to = "hello", "*****@*****.**", '"Sürname, Firstname" <*****@*****.**>'
     text_content = "This is an important message."
     html_content = "<p>This is an <strong>important</strong> message.</p>"
     msg = EmailMultiAlternatives("Message from Firstname Sürname", text_content, from_email, [to], headers=headers)
     msg.attach_alternative(html_content, "text/html")
     msg.encoding = "iso-8859-1"
     self.assertEqual(msg.message()["To"], "=?iso-8859-1?q?S=FCrname=2C_Firstname?= <*****@*****.**>")
     self.assertEqual(msg.message()["Subject"].encode(), u"=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=")
Example #12
0
    def inscription_mail(self):
        data = self.cleaned_data
        name = data['name']
        email = data['email']

        message = u'''Olá {0}, tudo bem?
        Nós recebemos seu pedido de pré-inscrição.
        Lembre-se que a inscrição só será válida após confirmação de pagamento.
        Você poderá verificar o andamento de sua inscrição a qualquer momento em nosso site. (estavos.com)
        O torneio acontecerá no dia 06 de Dezembro de 2015 no SESI de Taguatinga
        (QNF 24 Área Especial - Taguatinga Norte - 72125-740)
        Se tiver qualquer dúvida, não deixe de entrar em contato: [email protected].
        Atenciosamente,
        Bruno Barbosa - Academia ESTAVOS
        '''.format(name, "http://estavos.com/contato/")

        html_message = u'''
        <p>Olá {0}, tudo bem?</p>
        <p>Nós recebemos seu pedido de pré-inscrição.</p>
        <p>Lembre-se que a inscrição só será válida após confirmação de pagamento.</p>
        <p>Você poderá <a href="{2}">verificar o andamento de sua inscrição</a> a qualquer momento em nosso site.</p>
        <p>O torneio acontecerá no dia 06 de Dezembro de 2015 no SESI de Taguatinga</p>
        <p>QNF 24 Área Especial - Taguatinga Norte - 72125-740<p>
        <p>Se tiver qualquer dúvida, não deixe de entrar em <a href="{1}">contato</a>.</p>
        <p>Atenciosamente,</p>
        <p>Bruno Barbosa <br />
        Academia ESTAVOS<br />
        <a href="http://estavos.com">http://estavos.com</a><br />
        [email protected]</p>
        '''.format(
            name,
            "http://estavos.com/contato/",
            "http://estavos.com/torneios/festival-de-xadrez/checar-inscricao/"
        )

        recipient_list = [email, ]

        email_ = EmailMultiAlternatives(
            subject=u"Pré-inscrição recebida - Festival de Xadrez da Família",
            body=message,
            from_email='*****@*****.**',
            to=recipient_list,
            headers={'Reply-To': "*****@*****.**"}
        )
        email_.encoding = "utf-8"
        email_.attach_alternative(html_message, "text/html")
        email_.send()
        return
Example #13
0
def send(emailentry):
    """
    Sends the email entry through the configured email backend.
    @type emailentry: EmailEntry
    """
    plain_body = render_plain(emailentry.kind, emailentry.context)
    rich_body = render_html(emailentry.kind, emailentry.context)

    email = EmailMultiAlternatives(subject=emailentry.subject,
                                   body=plain_body,
                                   to=emailentry.recipients.split(','),
                                   from_email=emailentry.sender,
                                   reply_to=emailentry.reply_to.split(','))
    email.encoding = 'utf-8'

    # Attach HTML alternative
    if rich_body:
        email.attach_alternative(rich_body, 'text/html')

    # Attach already embedded images. Only the actually used ones.
    for img in emailentry.kind.iter_all_images():
        content_id = img.content_id[1:-1]
        if content_id in rich_body:
            image = MIMEImage(img.image.read())
            image.add_header('Content-ID', content_id)
            email.attach(image)

    # Attach regular files
    for att in emailentry.attachments.all():
        email.attach(filename=att.name,
                     content=att.attached_file.read(),
                     mimetype=att.content_type)
        increment(settings.METRIC['SEND_ATTACHS'])

    # Attach fixed metadata and extras provided by the entry
    email.metadata = {
        'customer_id': emailentry.customer_id,
        'kind': str(emailentry.kind),
        'email_id': emailentry.id
    }
    if len(emailentry.metadata) > 0:
        email.metadata.update(emailentry.metadata)

    sent = send_with_backend(email, emailentry)
    if not sent:
        return None
    return email
Example #14
0
    def client_subscription_mail(self):
        data = self.cleaned_data
        name = data['name']
        email = data['email']

        message = u'''Olá {0},
        Parabéns pela excelente escolha! Você verá como o Xadrez pode mudar sua vida para melhor.
        Nós recebemos seu pedido de inscrição e informamos que ele encontra-se em processamento.
        Assim que sua matrícula estiver confirmada nós lhe enviaremos um email avisando.
        Isso pode levar de 1 a 2 dias úteis ok?
        Lembramos que nosso primeiro encontro será no dia 03/10/2015 (sábado) das 9h às 12h no Núcleo de Xadrez da ASCADE.
        O endereço é Setor de Clubes Sul - trecho 2, Conjunto 10, Lote 18 - Asa Sul, Brasília - DF.
        Se tiver qualquer dúvida, não deixe de entrar em <a href="{1}">contato</a>.
        Atenciosamente,
        Bruno Barbosa, Diretor Administrativo - Academia ESTAVOS
        '''.format(name, "http://estavos.com/contato/")

        html_message = u'''
        <p>Olá {0},</p>
        <p>Parabéns pela excelente escolha! Você verá como o Xadrez pode mudar sua vida para melhor.</p>
        <p>Nós recebemos seu pedido de inscrição e informamos que ele encontra-se em processamento.</p>
        <p>Assim que sua matrícula estiver confirmada nós lhe enviaremos um email avisando.</p>
        <p>Isso pode levar de 1 a 2 dias úteis ok?</p>
        <p>Lembramos que nosso primeiro encontro será no dia <strong>03/10/2015 (Sábado)</strong> das <strong>9h às 12h</strong> no <strong>Núcleo de Xadrez do Clube ASCADE</strong><p>
        <p>O endereço é Setor de Clubes Sul - trecho 2, Conjunto 10, Lote 18 - Asa Sul, Brasília - DF.
        <p>Se tiver qualquer dúvida, não deixe de entrar em <a href="{1}">contato</a>.</p>
        <p>Atenciosamente,</p>
        <p>Bruno Barbosa <br />
        <em>Diretor Administrativo</em><br />
        Academia ESTAVOS<br />
        <a href="http://estavos.com">http://estavos.com</a><br />
        [email protected]</p>
        '''.format(name, "http://estavos.com/contato/")

        recipient_list = [email, ]

        email_ = EmailMultiAlternatives(
            subject=u"Inscrição no Curso de Xadrez para Iniciantes",
            body=message,
            from_email='*****@*****.**',
            to=recipient_list,
            headers={'Reply-To': "*****@*****.**"}
        )
        email_.encoding = "utf-8"
        email_.attach_alternative(html_message, "text/html")
        email_.send()
        return
Example #15
0
def mail_confirmed_inscription(name, email, status):
    if status == 'paid':
        message = u'''Olá {0}, tudo bem?
        Sua inscrição foi confirmada.
        Você poderá checar a lista de atletas inscritos a qualquer momento em nosso site. (estavos.com)
        O torneio acontecerá no dia 06 de Dezembro de 2015 no SESI de Taguatinga
        (QNF 24 Área Especial - Taguatinga Norte - 72125-740)
        Se tiver qualquer dúvida, não deixe de entrar em contato: [email protected].
        Atenciosamente,
        Bruno Barbosa - Academia ESTAVOS
        '''.format(name, "http://estavos.com/contato/")

        html_message = u'''
        <p>Olá {0}, tudo bem?</p>
        <p>Sua inscrição foi confirmada</p>
        <p>Você poderá <a href="{2}">checar a lista de atletas inscritos</a> a qualquer momento em nosso site.</p>
        <p>O torneio acontecerá no dia 06 de Dezembro de 2015 no SESI de Taguatinga</p>
        <p>QNF 24 Área Especial - Taguatinga Norte - 72125-740<p>
        <p>Se tiver qualquer dúvida, não deixe de entrar em <a href="{1}">contato</a>.</p>
        <p>Atenciosamente,</p>
        <p>Bruno Barbosa <br />
        Academia ESTAVOS<br />
        <a href="http://estavos.com">http://estavos.com</a><br />
        [email protected]</p>
        '''.format(
            name,
            "http://estavos.com/contato/",
            "http://estavos.com/torneios/festival-de-xadrez/checar-inscricao/"
        )

        recipient_list = [email, ]

        email_ = EmailMultiAlternatives(
            subject=u"Festival de Xadrez da Família - Inscrição confirmada",
            body=message,
            from_email='*****@*****.**',
            to=recipient_list,
            headers={'Reply-To': "*****@*****.**"}
        )
        email_.encoding = "utf-8"
        email_.attach_alternative(html_message, "text/html")
        email_.send()
        return
    return
Example #16
0
    def get(self, request):
        userprofile = UserProfile.objects.get(user_id=request.user.id)
        menbers = UserProfile.objects.filter(group_id=userprofile.group.id).order_by('sorts', 'user__date_joined')

        context, dutyuser, menberstr = {}, None, []
        for menber in menbers:
            menberstr.append(menber.user)
            if menber.duty:
                dutyuser = menber.user
        if not dutyuser:
            dutyuser = menbers[0].user

        context['userprofile'] = userprofile
        context['menber'] = menberstr
        reports = json.loads(request.GET["reports"])
        context['reports'] = reports

        # save meeting
        today = datetime.datetime.today()
        subject = userprofile.departments + '_' + userprofile.group.name + '_MeetingReport_' + today.strftime('%Y%m%d')

        master = userprofile.group.ower
        if request.GET.get("duty"):
            dutyuser = User.objects.get(pk=request.GET["duty"])
            master = dutyuser
        elif request.user.id != dutyuser.id:
            return JsonResponse({
                'success': False,
                'msg': '今天应该【' + dutyuser.username + '】发早会哦~'
            })

        # save meeting
        milestonedate1 = datetime.datetime.strptime(request.GET["milestonedate1"], '%Y-%m-%d')
        milestonedate2 = datetime.datetime.strptime(request.GET["milestonedate2"], '%Y-%m-%d')
        meeting = Meeting(topic=subject, milestone1=request.GET["milestone1"],
                          milestone2=request.GET["milestone2"], milestonedate1=milestonedate1,
                          milestonedate2=milestonedate2, created_time=today,
                          noter_id=dutyuser.id, menber=u' > '.join(o.username for o in menberstr),
                          group_id=userprofile.group.id, master_id=master.id)
        try:
            meeting.save()
        except IntegrityError:
            return JsonResponse({
                'success': False,
                'msg': '今天已经发过早会了哦~'
            })

        # save report
        for value in reports:
            report = Reports(user_id=value.get('user_id'), meeting_id=meeting.id, content=value.get('content'),
                             leave=(value.get('content') == 'leave'))
            report.save()

        # change next user duty
        for index, menber in enumerate(menbers):
            if menber.user.id == dutyuser.id:
                nextuser = menbers[(index + 1) if (index < len(menbers) - 1) else 0]
                nextuser.duty = True
                nextuser.save()
                context['duty'] = nextuser

        context['meeting'] = meeting
        html_content = loader.render_to_string(
            'meeting-reports/mail_template.html', context
        )
        try:
            toemails, ccemails = [], []
            emails = Emails.objects.get(group_id=userprofile.group.id)
            if emails.email:
                toemails.append(emails.email)
            elif emails.contain_menber:
                for menber in menbers:
                    toemails.append(menber.user.email)
            if emails.relist:
                for user in emails.relist.all():
                    toemails.append(user.email)
            if emails.cclist:
                for user in emails.cclist.all():
                    ccemails.append(user.email)
            msg = EmailMultiAlternatives(subject=subject, body=html_content, from_email=settings.EMAIL_HOST_USER,
                                         to=toemails, cc=ccemails)
            # 图片签名(非附件)
            img_data = open('static/img/test.png', 'rb').read()
            html_part = MIMEMultipart(_subtype='related')
            body = MIMEText('', _subtype='html')
            html_part.attach(body)
            img = MIMEImage(img_data, 'jpeg')
            img.add_header('Content-Id', '<email_sign>')
            img.add_header("Content-Disposition", "inline", filename="email_sign")
            html_part.attach(img)
            msg.attach(html_part)

            msg.content_subtype = "html"
            msg.encoding = "utf-8"
            msg.send()
            return JsonResponse({
                'success': True,
                'msg': '操作成功'
            })
        except (RuntimeError, TypeError, NameError):
            return JsonResponse({
                'success': False,
                'msg': 'Unexpected error:' + RuntimeError
            })
        return JsonResponse({
            'success': False,
            'msg': '操作失败'
        })
Example #17
0
def process_mailbox(M):
    rv, data = M.search(None, "ALL")
    if rv != "OK":
        print "Messagens não encontrada !"
        return

    for num in data[0].split():
        rv, data = M.fetch(num, "RFC822")
        if rv != "OK":
            print "Ocorreu algum problema ao recuperar a messagem"
            return

        msg = email.message_from_string(data[0][1])
        decode = email.header.decode_header(msg["Subject"])[0]
        subject = unicode(str(decode[0]).decode("utf-8")).encode("utf-8")
        print "Messagem %s: %s" % (num, subject)

        msg.set_default_type("text/html")
        #        email.encoders.encode_quopri(msg)

        a = {
            "msg.get_content_maintype() :": msg.get_content_maintype(),
            "msg.get_content_type() :": msg.get_content_type(),
            "msg.get_content_subtype() :": msg.get_content_subtype(),
            "msg.get_default_type() :": msg.get_default_type(),
            "msg.is_multipart() :": msg.is_multipart(),
            "msg.get_charsets() :": msg.get_charsets(),
        }

        # print type(a)
        for i in a:
            pass
            # print i, a.get(i)

        # for part in msg.walk():
        #    print part
        # Content-Transfer-Encoding
        # for i in msg.get_payload():
        #     print unicode(i).decode('utf-8').encode('utf-8')

        payload = msg.get_payload()
        body = extract_body(payload)

        print "##########################", body

        corpo = str(body).decode("utf-8").encode("utf-8").split("\x00")[0]

        import urllib2
        import urllib
        import binascii

        s = "BOLA=C3=83"
        # print urllib2.unquote(s)

        ss = "%C3%83".encode("cp1252")

        binascii.unhexlify(b"C383")

        z = body.replace("=", "%")

        urllib2.unquote(z)
        corpo = urllib.unquote_plus(z)
        print corpo

        # print corpo

        # from cStringIO import StringIO
        # from email.generator import Generator
        # fp = StringIO()
        # g = Generator(fp, mangle_from_=True, maxheaderlen=60)
        # g.flatten(msg)
        # text = fp.getvalue()

        # corpo = str(text).split('\x00')

        # print corpo

        # print 'Raw Date:', msg['Date']
        date_tuple = email.utils.parsedate_tz(msg["Date"])
        if date_tuple:
            local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
            # print "Data local:", \
            #    local_date.strftime("%a, %d %b %Y %H:%M:%S")

        msge = EmailMultiAlternatives(
            "TESTEAGORAVAI", corpo, "*****@*****.**", ["*****@*****.**", "*****@*****.**"]
        )
        msge.content_subtype = "html"
        msge.encoding = "UTF-8"
        msge.alternative_subtype = "html"
        msge.body.decode("utf-8").encode("utf-8")
        msge.attach_alternative(body, "text/html")

        msge.send()
Example #18
0
     if bcc is None:
         bcc = []
     while len(bcc) > 0:
         dests.append(bcc[:chunk_size])
         del bcc[:chunk_size]
     for _bcc in dests:
         msg = EmailMultiAlternatives(subject=render_subj,
                                      body=render_body,
                                      from_email=from_email,
                                      headers=headers,
                                      to=[from_email],
                                      cc=None,
                                      bcc=_bcc,
                                      attachments=attachments,
                                      alternatives=render_alternatives)
         msg.encoding = encoding
         msg.extra_headers.update({'Precedence': 'bulk'})
         messages.append(msg)
 else:
     msg = EmailMultiAlternatives(subject=render_subj,
                                  body=render_body,
                                  from_email=from_email,
                                  headers=headers,
                                  to=[from_email],
                                  cc=None,
                                  bcc=bcc,
                                  attachments=attachments,
                                  alternatives=render_alternatives)
     msg.encoding = encoding
     msg.extra_headers.update({'Precedence': 'bulk'})
     messages.append(msg)
Example #19
0
    def get(self, request):
        userprofile = UserProfile.objects.get(user_id=request.user.id)
        menbers = UserProfile.objects.filter(
            group_id=userprofile.group.id).order_by('sorts',
                                                    'user__date_joined')

        context, dutyuser, menberstr = {}, None, []
        for menber in menbers:
            menberstr.append(menber.user)
            if menber.duty:
                dutyuser = menber.user
        if not dutyuser:
            dutyuser = menbers[0].user

        context['userprofile'] = userprofile
        context['menber'] = menberstr
        reports = json.loads(request.GET["reports"])
        context['reports'] = reports

        # save meeting
        today = datetime.datetime.today()
        subject = userprofile.departments + '_' + userprofile.group.name + '_MeetingReport_' + today.strftime(
            '%Y%m%d')

        master = userprofile.group.ower
        if request.GET.get("duty"):
            dutyuser = User.objects.get(pk=request.GET["duty"])
            master = dutyuser
        elif request.user.id != dutyuser.id:
            return JsonResponse({
                'success': False,
                'msg': '今天应该【' + dutyuser.username + '】发早会哦~'
            })

        # save meeting
        milestonedate1 = datetime.datetime.strptime(
            request.GET["milestonedate1"], '%Y-%m-%d')
        milestonedate2 = datetime.datetime.strptime(
            request.GET["milestonedate2"], '%Y-%m-%d')
        meeting = Meeting(topic=subject,
                          milestone1=request.GET["milestone1"],
                          milestone2=request.GET["milestone2"],
                          milestonedate1=milestonedate1,
                          milestonedate2=milestonedate2,
                          created_time=today,
                          noter_id=dutyuser.id,
                          menber=u' > '.join(o.username for o in menberstr),
                          group_id=userprofile.group.id,
                          master_id=master.id)
        try:
            meeting.save()
        except IntegrityError:
            return JsonResponse({'success': False, 'msg': '今天已经发过早会了哦~'})

        # save report
        for value in reports:
            report = Reports(user_id=value.get('user_id'),
                             meeting_id=meeting.id,
                             content=value.get('content'),
                             leave=(value.get('content') == 'leave'))
            report.save()

        # change next user duty
        for index, menber in enumerate(menbers):
            if menber.user.id == dutyuser.id:
                nextuser = menbers[(index + 1) if
                                   (index < len(menbers) - 1) else 0]
                nextuser.duty = True
                nextuser.save()
                context['duty'] = nextuser

        context['meeting'] = meeting
        html_content = loader.render_to_string(
            'meeting-reports/mail_template.html', context)
        try:
            toemails, ccemails = [], []
            emails = Emails.objects.get(group_id=userprofile.group.id)
            if emails.email:
                toemails.append(emails.email)
            elif emails.contain_menber:
                for menber in menbers:
                    toemails.append(menber.user.email)
            if emails.relist:
                for user in emails.relist.all():
                    toemails.append(user.email)
            if emails.cclist:
                for user in emails.cclist.all():
                    ccemails.append(user.email)
            msg = EmailMultiAlternatives(subject=subject,
                                         body=html_content,
                                         from_email=settings.EMAIL_HOST_USER,
                                         to=toemails,
                                         cc=ccemails)
            # 图片签名(非附件)
            img_data = open('static/img/test.png', 'rb').read()
            html_part = MIMEMultipart(_subtype='related')
            body = MIMEText('', _subtype='html')
            html_part.attach(body)
            img = MIMEImage(img_data, 'jpeg')
            img.add_header('Content-Id', '<email_sign>')
            img.add_header("Content-Disposition",
                           "inline",
                           filename="email_sign")
            html_part.attach(img)
            msg.attach(html_part)

            msg.content_subtype = "html"
            msg.encoding = "utf-8"
            msg.send()
            return JsonResponse({'success': True, 'msg': '操作成功'})
        except (RuntimeError, TypeError, NameError):
            return JsonResponse({
                'success': False,
                'msg': 'Unexpected error:' + RuntimeError
            })
        return JsonResponse({'success': False, 'msg': '操作失败'})