Beispiel #1
0
    def test_alternative_errors(self):
        # Multiple alternatives not allowed
        email = mail.EmailMultiAlternatives('Subject', 'Body',
                                            '*****@*****.**',
                                            ['*****@*****.**'])
        email.attach_alternative("<p>First html is OK</p>", "text/html")
        email.attach_alternative("<p>But not second html</p>", "text/html")
        with self.assertRaises(NotSupportedByMandrillError):
            email.send()

        # Only html alternatives allowed
        email = mail.EmailMultiAlternatives('Subject', 'Body',
                                            '*****@*****.**',
                                            ['*****@*****.**'])
        email.attach_alternative("{'not': 'allowed'}", "application/json")
        with self.assertRaises(NotSupportedByMandrillError):
            email.send()

        # Make sure fail_silently is respected
        email = mail.EmailMultiAlternatives('Subject', 'Body',
                                            '*****@*****.**',
                                            ['*****@*****.**'])
        email.attach_alternative("{'not': 'allowed'}", "application/json")
        sent = email.send(fail_silently=True)
        self.assertFalse(
            self.mock_post.called,
            msg="Mandrill API should not be called when send fails silently")
        self.assertEqual(sent, 0)
Beispiel #2
0
def send_contact_mail(sender, instance, **kwargs):
    site = Site.objects.get_current()
    ctx = Context({
        "instance": instance,
        "site": site
    })
    get_tmpl = loader.get_template
    with mail.get_connection() as connection:
        subject = u"Message from {0}".format(instance.name)
        body_html = get_tmpl("email/contact_us.html").render(ctx)
        body_txt = get_tmpl("email/contact_us.txt").render(ctx)
        msg = mail.EmailMultiAlternatives(
            subject, body_txt, settings.DEFAULT_FROM_EMAIL,
            settings.CONTACT_EMAIL_RECIPIENTS,
            reply_to=[instance.email], connection=connection)
        msg.attach_alternative(body_html, "text/html")
        msg.send()

        auto_reply_subject = u"Acknowledgement from {0}".format(site.name)
        auto_reply_body_html = get_tmpl("email/auto_reply.html").render(ctx)
        auto_reply_body_txt = get_tmpl("email/auto_reply.txt").render(ctx)
        auto_reply = mail.EmailMultiAlternatives(
            auto_reply_subject, auto_reply_body_txt,
            settings.DEFAULT_FROM_EMAIL,
            [instance.email], connection=connection)
        auto_reply.attach_alternative(auto_reply_body_html, "text/html")
        auto_reply.send()
    def send_acti_email(self):
        """
        发送验证邮件
        :return:
        """
        email_valid = EmailValiRecord()
        code = SendEmail.create_random_str()
        email_valid.code = code
        email_valid.email = self.email
        email_valid.send_type = self.send_type
        email_valid.save()

        # 获取主机域名和端口
        ip_port = settings.ALLOWED_HOSTS[0] + ':' + settings.ALLOWED_PORT[0]
        ip_port = ip_port.strip()

        if self.send_type == 'register':
            subject = '网络教育在线注册激活'
            text_content = '请确认邮件后,点击该链接进行账号激活:http://{0}/activate/reg/{1}'.format(ip_port, code)
            html_content = '<h2>请确认邮件后,点击下方链接进行账号激活:</h2><a href="http://{0}/activate/reg/{1}">http://{0}/activate/reg/{1}</a>'.format(
                ip_port, code)
            # mail_status = mail.send_mail(subject=subject, message=text_content,
            #                              from_email='网络教育<{0}>'.format(settings.EMAIL_HOST_USER),
            #                              recipient_list=[self.email])
            try:
                msg = mail.EmailMultiAlternatives(subject=subject, body=text_content,
                                                  from_email='网络教育<{0}>'.format(settings.EMAIL_HOST_USER), to=[self.email])
                msg.attach_alternative(content=html_content, mimetype='text/html')
                mail_status = msg.send()
            except TimeoutError:
                raise Exception('发送邮件失败!请检查:1.网络是否正常;2.邮箱服务器、用户、密码等等是否正确。')

            if mail_status:
                return True
            else:
                return False

        elif self.send_type == 'forget':
            subject = '网络教育在线重置密码'
            text_content = '请确认邮件后,点击该链接进行重置密码:http://{0}/activate/resetpwd/{1}'.format(ip_port, code)
            html_content = '<h2>请确认邮件后,点击下方链接进行重置密码:</h2><a href="http://{0}/activate/forget/{1}">http://{0}/activate/forget/{1}</a>'.format(
                ip_port, code)
            # mail_status = mail.send_mail(subject=subject, message=text_content,
            #                              from_email='网络教育<{0}>'.format(settings.EMAIL_HOST_USER),
            #                              recipient_list=[self.email])
            try:
                msg = mail.EmailMultiAlternatives(subject=subject, body=text_content,
                                                  from_email='网络教育<{0}>'.format(settings.EMAIL_HOST_USER), to=[self.email])
                msg.attach_alternative(content=html_content, mimetype='text/html')
                mail_status = msg.send()
            except TimeoutError:
                raise Exception('发送邮件失败!请检查:1.网络是否正常;2.邮箱服务器、用户、密码等等是否正确。')

            if mail_status:
                return True
            else:
                return False
Beispiel #4
0
 def _wrapper():
     with open(FS_SITE_DIR +\
         "/templates/manage/notification-receipt-monthly.html", 'r') as f:
         template = Template(f.read())
     emails = []
     # for accounts
     for asis in asiss:
         invoice = asis[2]
         if not invoice: # failed to charge user
             continue
         subscription = asis[3]
         account = asis[0]
         store = asis[1]
         timezone.activate(pytz.timezone(store.store_timezone))
         # assumes that subscription's date_last_billed has been 
         # updated prior to this
         # variable names are misleading here ><
         date_30_ago = subscription.date_last_billed +\
             relativedelta(days=-30)
         date_now = subscription.date_last_billed.replace()
         #############
         subject = EMAIL_MONTHLY_SUBJECT
         ctx = get_notification_ctx()
         ctx.update({'store': store, 'invoice': invoice,
             "date_30_ago":date_30_ago, "date_now":date_now,
             "sub_type":sub_type, "subscription":subscription})
         body = template.render(Context(ctx)).__str__()
         timezone.deactivate()
                 
         email = mail.EmailMultiAlternatives(subject,
                     strip_tags(body), EMAIL_FROM,
                     [account.get('email')])
         email.attach_alternative(body, 'text/html')
         emails.append(email)
     # for ORDER_PLACED_EMAILS
     with open(FS_SITE_DIR +\
         "/templates/manage/notification-receipt-monthly-admin.html", 'r') as f:
         template = Template(f.read())
     date = timezone.localtime(timezone.now(),pytz.timezone(TIME_ZONE))
     subject = "Monthly billing results : " + date.strftime("%b %d %Y")
     ctx = get_notification_ctx()
     ctx.update({'asiss': asiss, "date":date, "sub_type":sub_type})
     timezone.activate(pytz.timezone(TIME_ZONE))
     body = template.render(Context(ctx)).__str__()
     timezone.deactivate()
     email = mail.EmailMultiAlternatives(subject,
                 strip_tags(body), EMAIL_FROM,
                 ORDER_PLACED_EMAILS)
     email.attach_alternative(body, 'text/html')
     emails.append(email)
     
     _send_emails(emails, connection)
Beispiel #5
0
    def append(self,
               subject='',
               body_txt='',
               body_html='',
               from_email=None,
               to=None,
               bcc=None,
               attachments=None,
               headers=None,
               alternatives=None,
               cc=None):
        content = render_to_string(
            ['text_email_template.html', 'site/text_email_template.html'],
            {'body': body_txt})
        email = mail.EmailMultiAlternatives(
            subject, content, from_email or settings.DEFAULT_FROM_EMAIL, to,
            bcc, None, attachments, headers, cc)
        if body_html:
            content = render_to_string(
                ['html_email_template.html', 'site/html_email_template.html'],
                {'body': body_html})
            email.attach_alternative(content, 'text/html')

        self.emails.append(email)
        return email
Beispiel #6
0
 def _send_email_notifications(self, email_addresses, context):
     if not email_addresses:
         return
     try:
         text_content = render_to_string('email/notify_run_completed.txt',
                                         context)
         html_content = render_to_string('email/notify_run_completed.html',
                                         context)
         connection = mail.get_connection()
         connection.open()
         email = mail.EmailMultiAlternatives(
             'Loom run %s@%s is %s' %
             (self.name, self.uuid[0:8], self.status.lower()),
             text_content,
             get_setting('DEFAULT_FROM_EMAIL'),
             email_addresses,
         )
         email.attach_alternative(html_content, "text/html")
         email.send()
         connection.close()
     except Exception as e:
         self.add_event("Email notifications failed",
                        detail=str(e),
                        is_error=True)
         raise
     self.add_event("Email notifications sent",
                    detail=email_addresses,
                    is_error=False)
Beispiel #7
0
    def get_queryset(self):
        """
        get_queryset ist die erste Methode die aufgerufen wird
        darum wird die liste emails auch hier generiert
        andere Methoden koennen die Liste dann so bekommen:
        self.object_list = self.get_queryset() #  generiert emails mit: self.emails
        die Emaillistte soll überall zur Verfügung stehen, deswegen wird die nachher ungut umkopiert.
        http://stackoverflow.com/questions/23402047/how-to-combine-two-querysets-when-defining-choices-in-a-modelmultiplechoicefield
        http://stackoverflow.com/questions/5629702/django-queryset-join-across-four-tables-including-manytomany
        """
        def htmlify(text):
            return "<html><body><pre>" + text + "</pre></body></html>"

        mt = MessageText.load()  # load email text and subject
        grussfloskel = "Liebe"

        qs = super(Queuelistview, self).get_queryset()
        print("modify qs when you want to contain only people with querysets!")
        print("Emails werden gesendet von  ", settings.DEFAULT_FROM_EMAIL)
        mas = Mitarbeiter.objects.all()
        self.emails = []
        self.journalName = []
        self.journalQuelle = []
        for idxma, ma in enumerate(mas):
            subscriptions = ma.Subscriptions.filter(
                summaries__SENT=False).distinct()
            if not subscriptions:
                # self.emails.append('')
                pass
            else:
                grussfloskeluse = grussfloskel
                if ma.Sex == 'm':
                    grussfloskeluse = grussfloskel + "r"
                anrede = " ".join(
                    [grussfloskeluse, ma.Anrede, ma.Nachname + ","])
                mailtext = "{0}\r\n\r\n  {1}".format(anrede,
                                                     mt.text) + '\r\n\r\n'
                mailtext = mailtext + "\r\n" + "\r\n" + "Quelle(n):\r\n\r\n"

                tmpmail = mail.EmailMultiAlternatives(
                    mt.subject, mailtext, settings.DEFAULT_FROM_EMAIL,
                    [ma.email])
                for idxsub, subsc in enumerate(
                        subscriptions
                ):  # loop durch die JournalSubscriptions eines Mitarbeiters
                    for summary in iter(subsc.summaries_set.iterator()):
                        if summary.SENT == False:
                            fn = os.path.join(settings.MEDIA_ROOT,
                                              str(summary.Inhaltsverzeichnis))
                            tmpmail.attach_file(fn)
                            journalData = Journals.objects.get(
                                Name=str(summary.Journal.Name))
                            mailtext = mailtext + journalData.Name + " - " + journalData.Quelle + "\r\n"
                mailhtml = htmlify(mailtext)
                tmpmail.attach_alternative(mailhtml, "text/html")
                self.emails.append(tmpmail)
                self.journalName.append(journalData.Name)
                self.journalQuelle.append(journalData.Quelle)

        return qs
Beispiel #8
0
    def make_email_object(self, to, context, **kwargs):
        if not isinstance(to, (list, tuple)):
            to = [to]

        lang = context.get("lang", None) or settings.LANGUAGE_CODE
        with language(lang):
            subject = self._render_message_subject(context)
            body_html = self._render_message_body_as_html(context)
            body_txt = self._render_message_body_as_txt(context)

        if not body_txt and not body_html:
            raise exc.TemplateNotFound("Body of email message shouldn't be empty")

        if body_txt and body_html:
            email = mail.EmailMultiAlternatives(**kwargs)
            email.body = body_txt
            email.attach_alternative(body_html, "text/html")

        elif not body_txt and body_html:
            email = mail.EmailMessage(**kwargs)
            email.content_subtype = "html"
            email.body = body_html

        else:
            email = mail.EmailMessage(**kwargs)
            email.body = body_txt

        email.to = to
        email.subject = subject

        return email
    def make_email_object(self, to, context, **kwargs):
        if not isinstance(to, (list, tuple)):
            to = [to]

        lang = context.get('lang', None) or settings.LANGUAGE_CODE
        with language(lang):
            subject = self._render_message_subject(context)
            body_html = self._render_message_body_as_html(context)
            body_txt = self._render_message_body_as_txt(context)

        if not body_txt and not body_html:
            raise exc.TemplateNotFound(
                "Body of email message shouldn't be empty. "
                "Update '{text}' or '{html}'".format(
                    html=self._get_template_name('html'),
                    text=self._get_template_name('text')))

        if body_txt and body_html:
            email = mail.EmailMultiAlternatives(**kwargs)
            email.body = body_txt
            email.attach_alternative(body_html, 'text/html')

        elif not body_txt and body_html:
            email = mail.EmailMessage(**kwargs)
            email.content_subtype = 'html'
            email.body = body_html

        else:
            email = mail.EmailMessage(**kwargs)
            email.body = body_txt

        email.to = to
        email.subject = subject

        return email
Beispiel #10
0
def notify_newsletter_subscribers(instance):
    connection = mail.get_connection()
    connection.open()
    subscription_settings = Subscription.for_site(instance.get_site())
    recipients = NewsletterSubscription.objects.all()
    subject = subscription_settings.email_subject
    subscription_page = subscription_settings.subscription_page
    messages = []
    for recipient in recipients:
        plaintext = get_template("subscription/message/email.txt")
        html = get_template("subscription/message/email.html")
        if subscription_page:
            unsubscribe_url = subscription_page.specific.get_unsubscribe_url_for(
                recipient)
        else:
            unsubscribe_url = None
        context = {
            "post": instance,
            "unsubscribe_url": unsubscribe_url,
        }
        text_content = plaintext.render(context)
        html_content = html.render(context)

        message = mail.EmailMultiAlternatives(
            subject=subject,
            body=text_content,
            from_email=settings.EMAIL_HOST_USER,
            to=[recipient.email],
            connection=connection,
        )
        message.attach_alternative(html_content, "text/html")
        messages.append(message)

    connection.send_messages(messages)
    connection.close()
Beispiel #11
0
 def senden(self, member: Wichtelmember, request=None):
     subject = f'{self.email_subject_prefix}'
     html_message = render_to_string(self.email_template_html, {
         'member': member,
         'request': request
     })
     plain_message = render_to_string(self.email_template_txt, {
         'member': member,
         'request': request
     })
     logger.debug(plain_message)
     to = f'{member.emailAdresse}'
     with mail.get_connection() as connection:
         try:
             email = mail.EmailMultiAlternatives(subject,
                                                 plain_message,
                                                 to=[to],
                                                 connection=connection)
             email.attach_alternative(html_message, 'text/html')
             email.send(fail_silently=False)
         except SMTPRecipientsRefused as e:
             logger.debug(e)
             return True
         except SMTPException as e:
             logger.debug(e)
             return False
    def send_vali_emailcode(self):
        """
        产生4位数字验证码
        :return:
        """
        email_valid = EmailValiRecord()
        code = SendEmail.create_random_nums()
        email_valid.code = code
        email_valid.email = self.email
        email_valid.send_type = self.send_type
        email_valid.save()

        if self.send_type == 'update_email':
            subject = '网络教育在线修改邮箱'
            text_content = '您的邮箱验证码为(请不要告诉他人):{0}'.format(code)
            html_content = '<h2>您的邮箱验证码为(请不要告诉他人):</h2> {0}'.format(code)
            # mail_status = mail.send_mail(subject=subject, message=text_content,
            #                              from_email='网络教育<{0}>'.format(settings.EMAIL_HOST_USER),
            #                              recipient_list=[self.email])
            try:
                msg = mail.EmailMultiAlternatives(subject=subject, body=text_content,
                                                  from_email='网络教育<{0}>'.format(settings.EMAIL_HOST_USER), to=[self.email])
                msg.attach_alternative(content=html_content, mimetype='text/html')
                mail_status = msg.send()
            except TimeoutError:
                raise Exception('发送邮件失败!请检查:1.网络是否正常;2.邮箱服务器、用户、密码等等是否正确。')

            if mail_status:
                return True
            else:
                return False
Beispiel #13
0
def get_email(to_email,
              subject,
              template,
              from_email=None,
              context={},
              request=None,
              smtp_config_name=None,
              cc=None,
              bcc=None):
    """Instancia un objeto de EmailMultiAlternative a partir de los datos recibidos."""

    if not isinstance(to_email, list) and not isinstance(to_email, dict):
        to_email = [to_email]

    connection = get_connection(smtp_config_name)
    from_email_resolved = get_from_email(from_email, smtp_config_name)

    content = render_content(template, context, request)
    text_content = content["text_content"]
    html_content = content["html_content"]

    msg = mail.EmailMultiAlternatives(subject,
                                      text_content,
                                      from_email_resolved,
                                      to_email,
                                      connection=connection,
                                      cc=cc,
                                      bcc=bcc)
    msg.attach_alternative(html_content, "text/html")

    return msg
Beispiel #14
0
def get_email_from_content(to_email,
                           subject,
                           html_content,
                           text_content,
                           from_email=None,
                           smtp_config_name=None,
                           cc=None,
                           bcc=None):
    """Devuelve una instancia de EmailMultiAlternatives instanciada siendo recibido
	el texto del correo ya renderizado en la llamada a la función.
	
	"""

    if not isinstance(to_email, list) and not isinstance(to_email, dict):
        to_email = [to_email]

    connection = get_connection(smtp_config_name)
    from_email_resolved = get_from_email(from_email, smtp_config_name)
    msg = mail.EmailMultiAlternatives(subject,
                                      text_content,
                                      from_email_resolved,
                                      to_email,
                                      connection=connection,
                                      cc=cc,
                                      bcc=bcc)
    msg.attach_alternative(html_content, "text/html")

    return msg
def create_email_message(to_emails, from_email, subject, text, html):
    """Create the appropriate plaintext or html email object.

    Returns:

       email - an instance of either `django.core.mail.EmailMessage` or
       `django.core.mail.EmailMulitiAlternatives` based on whether or
       not `html_message` is empty.
    """
    if not html:
        email = mail.EmailMessage(
            subject=subject,
            body=text,
            to=to_emails,
            from_email=from_email,
        )
    else:
        email = mail.EmailMultiAlternatives(
            subject=subject,
            body=text,
            to=to_emails,
            from_email=from_email,
        )
        email.attach_alternative(html, 'text/html')
    return email
Beispiel #16
0
def prepare_email(recipient, template, context=None, **kw):
    if not context:
        context = dict()
    context['recipient'] = recipient
    context['url_base'] = URL_BASE

    gig = context.get('gig',None)
    if gig:
        the_from = gig.band.name
    else:
        the_from = DEFAULT_FROM_EMAIL_NAME

    the_from = f'{the_from}<{DEFAULT_FROM_EMAIL}>'

    with translation.override(recipient.language):
        text = render_to_string(template, context).strip()
    if text.startswith(SUBJECT):
        subject, text = [t.strip() for t in text[len(SUBJECT):].split('\n', 1)]
    else:
        subject = DEFAULT_SUBJECT
    html = markdown(text, extensions=['nl2br'])

    message = mail.EmailMultiAlternatives(subject, text, from_email=the_from, to=[recipient.email_line], **kw)
    message.attach_alternative(html, 'text/html')
    return message
Beispiel #17
0
 def save(self):
     from django.core import mail
     from django.template import Context, Template
     with mail.get_connection() as connection:
         for user in self.cleaned_data['users']:
             email_text = ''
             email_text_html = ''
             if self.cleaned_data['personalize']:
                 email_text = ('Dear ' + user.contributor.profile.get_title_display()
                               + ' ' + user.last_name + ', \n\n')
             email_text_html = 'Dear {{ title }} {{ last_name }},<br/>'
             email_text += self.cleaned_data['email_text']
             email_text_html += '{{ email_text|linebreaks }}'
             email_context = {
                 'title': user.contributor.profile.get_title_display(),
                 'last_name': user.last_name,
                 'email_text': self.cleaned_data['email_text'],
             }
             html_template = Template(email_text_html)
             html_version = html_template.render(Context(email_context))
             message = mail.EmailMultiAlternatives(
                 self.cleaned_data['email_subject'],
                 email_text, 'SciPost Admin <*****@*****.**>',
                 [user.email], connection=connection)
             message.attach_alternative(html_version, 'text/html')
             message.send()
Beispiel #18
0
 def send(self, event, users, instance, paths):
     from_address = settings.ASYNC_EMAIL_FROM
     reply_to = {}
     if hasattr(settings, 'ASYNC_EMAIL_REPLY_TO'):
         reply_to = {
             'Reply-To': settings.ASYNC_EMAIL_REPLY_TO,
             'Return-Path': settings.ASYNC_EMAIL_REPLY_TO
         }
     messages = []
     for user, templates in users.items():
         if not self.enabled(event, user, paths) or not user.email:
             continue
         template = self._get_template(templates)
         if template is None:
             continue
         params = self.prepare(template, instance)
         e = mail.EmailMultiAlternatives(subject=params['subject'],
                                         body=params['description'],
                                         from_email=from_address,
                                         to=[
                                             user.email,
                                         ],
                                         headers=reply_to)
         e.attach_alternative(
             markdown2.markdown(
                 params['description'],
                 extras=["link-patterns"],
                 link_patterns=link_registry.link_patterns(request),
                 safe_mode=True), 'text/html')
         messages.append(e)
     if len(messages):
         connection = mail.get_connection()
         connection.send_messages(messages)
Beispiel #19
0
 def save(self):
     """
     Sends the message.
     """
     subject = self.get_subject()
     from_email = self.get_from_email()
     email_recipients = self.get_email_recipients()
     context = self.get_context()
     message_body = render_to_string(self.get_template_names(), context)
     try:
         message = mail.EmailMultiAlternatives(
             subject=subject,
             body=message_body,
             from_email=from_email,
             to=email_recipients,
             headers={'Reply-To': self.cleaned_data['email']})
         if settings.USE_HTML_EMAIL:
             html_body = render_to_string(self.html_template_name, context)
             message.attach_alternative(html_body, "text/html")
         message.send()
         after_send.send(sender=self.__class__, message=message, form=self)
         logger.info(
             _("Contact form submitted and sent (from: %s)") %
             self.cleaned_data['email'])
     except SMTPException:
         logger.exception(_("An error occured while sending the email"))
         return False
     else:
         return True
Beispiel #20
0
def _send_email(
    *,
    subject: str,
    body_text: str,
    from_address: str,
    to_address: str,
    item_id: int,
    item_title: str,
):
    with mail.get_connection() as connection:
        email = mail.EmailMultiAlternatives(
            subject=subject,
            body=body_text,
            from_email=from_address,
            to=[to_address],
            connection=connection,
        )

    email.extra_headers = {
        "X-SMTPAPI": json.dumps(_get_smtp_api_headers(item_id, item_title))
    }

    try:
        email.send(fail_silently=False)
    except smtplib.SMTPException as e:
        raise UnableToSendEmail(str(e))
Beispiel #21
0
    def get_queryset(self):
        queryset = super(SendMailSupraList, self).get_queryset()
        ids = self.request.GET.getlist('ids')
        if ids and len(ids):
            queryset = queryset.filter(id__in=ids)
        # end if
        for nom in queryset:
            if nom.contrato.empleado.email:
                values = {
                    'file_format': 0,
                }
                data = urllib.urlencode(values)
                req = urllib2.Request(
                    "http://" + self.request.get_host() + self.url + "?id=" +
                    str(nom.id), data)
                response = urllib2.urlopen(req)
                result = response.read()

                msg = mail.EmailMultiAlternatives(
                    self.subject, ".", self.sender,
                    [nom.contrato.empleado.email])
                msg.attach_alternative(self.html, "text/html")
                msg.attach(self.attach_name, result, "application/pdf")
                msg.send()
            # end if
        # end for
        return queryset
Beispiel #22
0
    def test_embedded_images(self):
        image_data = self.sample_image_content()  # Read from a png file
        image_cid = make_msgid(
            "img")  # Content ID per RFC 2045 section 7 (with <...>)
        image_cid_no_brackets = image_cid[
            1:-1]  # Without <...>, for use as the <img> tag src

        text_content = 'This has an inline image.'
        html_content = '<p>This has an <img src="cid:%s" alt="inline" /> image.</p>' % image_cid_no_brackets
        email = mail.EmailMultiAlternatives('Subject', text_content,
                                            '*****@*****.**',
                                            ['*****@*****.**'])
        email.attach_alternative(html_content, "text/html")

        image = MIMEImage(image_data)
        image.add_header('Content-ID', image_cid)
        email.attach(image)

        email.send()
        data = self.get_api_call_data()
        self.assertEqual(data['message']['text'], text_content)
        self.assertEqual(data['message']['html'], html_content)
        self.assertEqual(len(data['message']['images']), 1)
        self.assertEqual(data['message']['images'][0]["type"], "image/png")
        self.assertEqual(data['message']['images'][0]["name"], image_cid)
        self.assertEqual(decode_att(data['message']['images'][0]["content"]),
                         image_data)
        # Make sure neither the html nor the inline image is treated as an attachment:
        self.assertFalse('attachments' in data['message'])
Beispiel #23
0
 def _wrapper():
     # need to activate the store's timezone for template rendering!
     timezone.activate(pytz.timezone(store.store_timezone))
     with open(FS_SITE_DIR +\
         "/templates/manage/notification-receipt-monthly-failed.html", 'r') as f:
         template = Template(f.read())
     # variable names are misleading here ><
     date_now = subscription.date_last_billed +\
         relativedelta(days=30)
     #########
     # the 14 day sequence just like passed user limit
     date_disable = date_now + relativedelta(days=14)
     subject = "Repunch Inc. important service notice."
     ctx = get_notification_ctx()
     ctx.update({'store': store, "date_disable":date_disable,
         "date_now":date_now,
         "account_disabled": account_disabled,
         "sub_type":sub_type, "subscription":subscription})
     body = template.render(Context(ctx)).__str__()
             
     email = mail.EmailMultiAlternatives(subject,
                 strip_tags(body), EMAIL_FROM,
                 [account.get('email')])
     email.attach_alternative(body, 'text/html')
         
     _send_emails([email], connection)
Beispiel #24
0
    def test_attached_images(self):
        image_data = self.sample_image_content()

        email = mail.EmailMultiAlternatives('Subject', 'Message',
                                            '*****@*****.**',
                                            ['*****@*****.**'])
        email.attach_file(
            self.sample_image_pathname())  # option 1: attach as a file

        image = MIMEImage(
            image_data
        )  # option 2: construct the MIMEImage and attach it directly
        email.attach(image)

        email.send()
        data = self.get_api_call_data()
        attachments = data['message']['attachments']
        self.assertEqual(len(attachments), 2)
        self.assertEqual(attachments[0]["type"], "image/png")
        self.assertEqual(attachments[0]["name"], self.sample_image_filename)
        self.assertEqual(decode_att(attachments[0]["content"]), image_data)
        self.assertEqual(attachments[1]["type"], "image/png")
        self.assertEqual(attachments[1]["name"],
                         "")  # unknown -- not attached as file
        self.assertEqual(decode_att(attachments[1]["content"]), image_data)
        # Make sure the image attachments are not treated as embedded:
        self.assertFalse('images' in data['message'])
 def send_mail(self):
     subject = self.get_subject()
     from_email = self.get_from_email()
     email_recipients = self.get_email_recipients()
     context = self.get_context()
     message_body = render_to_string(self.get_template_names(), context)
     try:
         message = mail.EmailMultiAlternatives(
             subject=subject,
             body=message_body,
             from_email=from_email,
             to=email_recipients,
             headers={
                 'Reply-To': self.mail
             }
         )
         html_body = render_to_string(self.html_template_name, context)
         message.attach_alternative(html_body, "text/html")
         message.send()
         logger.info(_("Appointment form submitted and sent (from: %s)") %
                     self.mail)
     except SMTPException:
         logger.exception(_("An error occured while sending the email"))
         return False
     else:
         return True
Beispiel #26
0
def send_confirmation_email(app: Application) -> None:
    """
    Sends a confirmation email to a user, which contains their QR code as well as additional event information.
    :param app: The user's application
    :type app: Application
    :return: None
    """
    subject = f"Hacklahoma Confirmation!"
    email_template = "application/emails/confirmed.html"
    context = {"first_name": app.first_name, "event_name": "Hacklahoma"}
    html_msg = render_to_string(email_template, context)
    msg = html.strip_tags(html_msg)
    email = mail.EmailMultiAlternatives(subject,
                                        msg,
                                        from_email=None,
                                        to=[app.user.email])
    email.attach_alternative(html_msg, "text/html")

    qr_content = json.dumps({
        "first_name": app.first_name,
        "last_name": app.last_name,
        "email": app.user.email,
        "university": app.school.name,
    })
    qr_code = pyqrcode.create(qr_content)
    qr_stream = BytesIO()
    qr_code.png(qr_stream, scale=5)
    email.attach("code.png", qr_stream.getvalue(), "text/png")
    email.send()
Beispiel #27
0
    def send(self, to, subject='', body='', attachments=None):
        """
        Send a simple email. There is no document or template knowledge.
        attachments is a list of dictionaries with the keys:
        filename, content, and  mimetype.
        """
        recipient_list = split_recipient_list(recipients=[to])

        with self.get_connection() as connection:
            email_message = mail.EmailMultiAlternatives(
                body=strip_tags(body),
                connection=connection,
                subject=subject,
                to=recipient_list,
            )

            for attachment in attachments or []:
                email_message.attach(filename=attachment['filename'],
                                     content=attachment['content'],
                                     mimetype=attachment['mimetype'])

            email_message.attach_alternative(body, 'text/html')

            try:
                email_message.send()
            except Exception as exception:
                self.error_log.create(message=exception)
            else:
                self.error_log.all().delete()
Beispiel #28
0
def send_email(recipients,
    subject,
    context,
    text_template=TEXT_TEMPLATE,
    html_template=HTML_TEMPLATE,
    attachments=None,
    bcc=[],
):
    if settings.DEBUG:
        recipients = [settings.DEBUG_EMAIL]

    context['admin_email'] = settings.ADMIN_EMAIL
    context['admin_name'] = settings.ADMIN_NAME

    plaintext = get_template(text_template)
    htmly = get_template(html_template)
    connection = mail.get_connection()
    connection.open()
    for recipient in recipients:
        text_content = plaintext.render(context)
        html_content = htmly.render(context)
        msg = mail.EmailMultiAlternatives(subject, text_content, FROM_ADDRESS, [recipient], bcc=bcc)
        msg.attach_alternative(html_content, "text/html")
        if attachments:
            for attachment in attachments:
                msg.attach(**attachment)

        msg.send()
        logger.info('Sending email "{0}" to {1}...'.format(subject, recipient))

    connection.close()
def send_mail_extra(identifier,
                    *email_args,
                    connection=None,
                    cc=None,
                    bcc=None,
                    headers=None,
                    **email_kwargs):

    data = prep_email(identifier,
                      *email_args,
                      connection=connection,
                      cc=cc,
                      bcc=bcc,
                      headers=headers,
                      **email_kwargs)

    connection = connection or data.get('connection', None)

    email = mail.EmailMultiAlternatives(subject=data['subject'],
                                        body=data['text_message'],
                                        from_email=data['from_email'],
                                        to=data['recipients'],
                                        cc=data['cc'],
                                        bcc=data['bcc'],
                                        headers=data['headers'],
                                        connection=connection)

    email.attach_alternative(data['html_message'], 'text/html')

    return email.send()
Beispiel #30
0
        def messages():
            for sub in subs:
                message = Message(user=sub.user,
                                  body=body,
                                  sent_at=body.sent_at)

                # collect to a bulk email if the subscription is by email:
                if sub.type == EMAIL_MESSAGE or sub.type == ALL_MESSAGES:
                    try:
                        token = ReplyToken(user=sub.user,
                                           post=post,
                                           token=make_uuid(8),
                                           date=now())
                        from_email = settings.EMAIL_FROM_PATTERN % (
                            author.name, settings.DEFAULT_FROM_EMAIL)
                        from_email = from_email.encode("utf-8")
                        reply_to = settings.EMAIL_REPLY_PATTERN % token.token
                        subject = settings.EMAIL_REPLY_SUBJECT % body.subject
                        # create the email message
                        email = mail.EmailMultiAlternatives(
                            subject=subject,
                            body=email_text,
                            from_email=from_email,
                            to=[sub.user.email],
                            headers={'Reply-To': reply_to},
                        )
                        email.attach_alternative(email_html, "text/html")
                        emails.append(email)
                        tokens.append(token)
                    except Exception, exc:
                        # This here can crash the post submission hence the catchall
                        logger.error(exc)

                yield message