Python django.conf.settings.DEFAULT_FROM_EMAIL Examples

The following are 30 code examples of django.conf.settings.DEFAULT_FROM_EMAIL(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: mail.py    From conf_site with MIT License 6 votes vote down vote up
def send_email(to, kind, cc=[], **kwargs):

    current_site = Site.objects.get_current()

    ctx = {"current_site": current_site, "STATIC_URL": settings.STATIC_URL}
    ctx.update(kwargs.get("context", {}))
    subject = "[%s] %s" % (
        current_site.name,
        render_to_string(
            "symposion/emails/%s/subject.txt" % kind, ctx
        ).strip(),
    )

    message_html = render_to_string(
        "symposion/emails/%s/message.html" % kind, ctx
    )
    message_plaintext = strip_tags(message_html)

    from_email = settings.DEFAULT_FROM_EMAIL

    email = EmailMultiAlternatives(
        subject, message_plaintext, from_email, to, cc=cc
    )
    email.attach_alternative(message_html, "text/html")
    email.send() 
Example #2
Source File: models.py    From codesy with GNU Affero General Public License v3.0 6 votes vote down vote up
def notify_matching_askers(sender, instance, **kwargs):
    email_template = get_template('../templates/email/ask_met.html')
    unnotified_asks = Bid.objects.filter(
        url=instance.url, ask_match_sent=None).exclude(ask__lte=0)

    for bid in unnotified_asks:
        if bid.ask_met():
            email_context = {'ask': bid.ask, 'url': bid.url}
            subject = (
                "[codesy] There's $%(ask)d waiting for you!" % email_context
            )
            message = email_template.render(email_context)
            send_mail(
                subject,
                message,
                settings.DEFAULT_FROM_EMAIL,
                [bid.user.email]
            )
            # use .update to avoid recursive signal processing
            Bid.objects.filter(id=bid.id).update(ask_match_sent=timezone.now()) 
Example #3
Source File: check_validation.py    From codesy with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        accounts = StripeAccount.objects.all()
        for account in accounts:
            try:
                stripe_account = stripe.Account.retrieve(account.account_id)
                if account.verification != stripe_account.verification:
                    account.verification = json.dumps(
                        stripe_account.verification)
                    account.save()
                    if stripe_account.verification.fields_needed:
                        email_context = (
                            {'expiration': stripe_account.verification.due_by})
                        message = email_template.render(email_context)
                        send_mail(
                            '[codesy] Account validation needed',
                            message,
                            settings.DEFAULT_FROM_EMAIL,
                            [account.user.email]
                        )
            except:
                e = sys.exc_info()[0]
                logger.error("Error during check_validation: %s" % e) 
Example #4
Source File: enroll_reminder.py    From Django-3-by-Example with MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        emails = []
        subject = 'Enroll in a course'
        date_joined = timezone.now().today() - \
                      datetime.timedelta(days=options['days'])
        users = User.objects.annotate(course_count=Count('courses_joined'))\
                            .filter(course_count=0,
                                    date_joined__date__lte=date_joined)
        for user in users:
            message = """Dear {},
            We noticed that you didn't enroll in any courses yet.
            What are you waiting for?""".format(user.first_name)
            emails.append((subject,
                           message,
                           settings.DEFAULT_FROM_EMAIL,
                           [user.email]))
        send_mass_mail(emails)
        self.stdout.write('Sent {} reminders'.format(len(emails))) 
Example #5
Source File: test_tasks.py    From telemetry-analysis-service with Mozilla Public License 2.0 6 votes vote down vote up
def test_send_expiration_mails(mailoutbox, mocker, now, cluster_factory):
    cluster = cluster_factory(
        expires_at=now + timedelta(minutes=59),  # 1 hours is the cut-off
        most_recent_status=models.Cluster.STATUS_WAITING,
    )
    assert len(mailoutbox) == 0
    tasks.send_expiration_mails()
    assert len(mailoutbox) == 1
    message = mailoutbox[0]
    assert message.subject == (
        "%sCluster %s is expiring soon!"
        % (settings.EMAIL_SUBJECT_PREFIX, cluster.identifier)
    )
    assert message.from_email == settings.DEFAULT_FROM_EMAIL
    assert list(message.to) == [cluster.created_by.email]
    cluster.refresh_from_db()
    assert cluster.expiration_mail_sent 
Example #6
Source File: send_mail_notifications.py    From anytask with MIT License 6 votes vote down vote up
def handle(self, **options):
        start_time = time.time()

        domain = Site.objects.get_current().domain
        from_email = settings.DEFAULT_FROM_EMAIL

        if hasattr(settings, 'SEND_MESSAGE_FULLTEXT') and settings.SEND_MESSAGE_FULLTEXT:
            notify_messages = send_fulltext(domain, from_email)
        else:
            notify_messages = [send_only_notify(domain, from_email)]

        num_sent = 0
        sleep_time = 0
        for messages in notify_messages:
            if messages:
                num_sent += send_mass_mail_html(messages)
                time.sleep(1)
                sleep_time += 1

        # logging to cron log
        print "Command send_mail_notifications send {0} email(s) and took {1} seconds (sleep {2} seconds)" \
            .format(num_sent, time.time() - start_time, sleep_time) 
Example #7
Source File: models.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def email_contract(self):
        unit = self.posting.unit
        try:
            contract_email = unit.contract_email_text
            content = contract_email.content
            subject = contract_email.subject
        except TAContractEmailText.DoesNotExist:
            content = DEFAULT_EMAIL_TEXT
            subject = DEFAULT_EMAIL_SUBJECT

        response = HttpResponse(content_type="application/pdf")
        response['Content-Disposition'] = 'inline; filename="%s-%s.pdf"' % (self.posting.slug,
                                                                            self.application.person.userid)
        ta_form(self, response)
        to_email = self.application.person.email()
        if self.posting.contact():
            from_email = self.posting.contact().email()
        else:
            from_email = settings.DEFAULT_FROM_EMAIL
        msg = EmailMultiAlternatives(subject, content, from_email,
                                     [to_email], headers={'X-coursys-topic': 'ta'})
        msg.attach(('"%s-%s.pdf' % (self.posting.slug, self.application.person.userid)), response.getvalue(),
                   'application/pdf')
        msg.send() 
Example #8
Source File: views.py    From django-simple-forum with MIT License 6 votes vote down vote up
def form_valid(self, form):
        user = User.objects.filter(email=self.request.POST.get('email'))
        if user:
            user = user[0]
            subject = "Password Reset"
            password = get_random_string(6)
            message = '<p>Your Password for the forum account is <strong>'+password + \
                '</strong></p><br/><p>Use this credentials to login into <a href="' + \
                settings.HOST_URL + '/forum/">forum</a></p>'
            to = user.email
            from_email = settings.DEFAULT_FROM_EMAIL
            Memail([to], from_email, subject, message, email_template_name=None, context=None)
            user.set_password(password)
            user.save()
            data = {
                "error": False, "response": "An Email is sent to the entered email id"}
            return JsonResponse(data)
        else:
            data = {
                "error": True, "message": "User With this email id doesn't exists!!!"}
            return JsonResponse(data) 
Example #9
Source File: models.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def email_memo(self):
        """
        Emails the registration confirmation email if there is one and if none has been emailed for this registration
        before.
        """
        # If this registration is waitlisted, don't email!
        if self.waitlisted:
            return
        if 'email' not in self.config and self.event.registration_email_text:
            subject = 'Registration Confirmation'
            from_email = settings.DEFAULT_FROM_EMAIL
            content = self.event.registration_email_text
            msg = EmailMultiAlternatives(subject, content, from_email,
                                         [self.email], headers={'X-coursys-topic': 'outreach'})
            msg.send()
            self.email_sent = content
            self.save() 
Example #10
Source File: places.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def send_email(self, user, place):
        config = SiteConfiguration.get_solo()
        email_template_subject = get_template('email/new_authorization_subject.txt')
        email_template_text = get_template('email/new_authorization.txt')
        email_template_html = get_template('email/new_authorization.html')
        # TODO : Unsubscribe link in the email
        email_context = {
            'site_name': config.site_name,
            'ENV': settings.ENVIRONMENT,
            'subject_prefix': settings.EMAIL_SUBJECT_PREFIX_FULL,
            'user': user,
            'place': place,
        }
        # TODO : send mail only if the user chose to receive this type
        send_mail(
            ''.join(email_template_subject.render(email_context).splitlines()),
            email_template_text.render(email_context),
            settings.DEFAULT_FROM_EMAIL,
            recipient_list=[user.email],
            html_message=email_template_html.render(email_context),
            fail_silently=False,
        ) 
Example #11
Source File: signals.py    From appstore with GNU Affero General Public License v3.0 6 votes vote down vote up
def password_changed_signal(sender, instance, **kwargs):
    """
    Regenerate token on password change
    :param sender:
    :param instance:
    :param kwargs:
    :return:
    """
    mail_subect = _('Nextcloud Appstore password changed')
    mail_message = _('Your Appstore password has changed. '
                     'Contact support if this wasn\'t you.')

    try:
        user = get_user_model().objects.get(pk=instance.pk)
        if user.password != instance.password:
            update_token(user.username)
            send_mail(
                    mail_subect,
                    mail_message,
                    settings.DEFAULT_FROM_EMAIL,
                    [user.email],
                    False)
    except User.DoesNotExist:
        pass 
Example #12
Source File: test_utils.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_mass_html_mail(self):
        test_data = list()
        faker = Faker()
        for i in range(random.randint(3, 7)):
            test_data.append((
                faker.sentence(),
                faker.word(), "<strong>{}</strong>".format(faker.word()),
                "test@ps", [],
            ))
            for j in range(random.randint(1, 3)):
                test_data[i][4].append(faker.email())

        result = send_mass_html_mail(test_data)
        self.assertEqual(result, len(test_data))
        self.assertEqual(len(mail.outbox), len(test_data))
        for i in range(len(test_data)):
            for j in range(len(test_data[i][4])):
                self.assertEqual(mail.outbox[i].subject, test_data[i][0])
                self.assertEqual(mail.outbox[i].from_email, settings.DEFAULT_FROM_EMAIL)
                self.assertEqual(mail.outbox[i].to, test_data[i][4]) 
Example #13
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def oauth_authorize(request, request_token, callback, params):
    """
    The callback view for oauth_provider's OAUTH_AUTHORIZE_VIEW.
    """
    consumer = request_token.consumer
    consumerinfo = ConsumerInfo.objects.filter(consumer_id=request_token.consumer_id).order_by('-timestamp').first()
    form = AuthorizeRequestTokenForm(initial={'oauth_token': request_token.key})

    # email the user so we're super-sure they know this is happening
    person = get_object_or_404(Person, userid=request.user.username)
    manage_url = request.build_absolute_uri(reverse('config:manage_tokens'))
    message = EMAIL_INFORM_TEMPLATE.format(consumername=consumer.name, url=manage_url)
    send_mail('CourSys access requested', message, settings.DEFAULT_FROM_EMAIL, [person.email()], fail_silently=False)

    context = {
        'consumer': consumer,
        'consumerinfo': consumerinfo,
        'form': form,
    }
    return render(request, 'api/oauth_authorize.html', context) 
Example #14
Source File: notify_changed_employments.py    From timed-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        email = options["email"]
        last_days = options["last_days"]

        # today is excluded
        end = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        start = end - timedelta(days=last_days)

        employments = Employment.objects.filter(updated__range=[start, end])
        if employments.exists():
            from_email = settings.DEFAULT_FROM_EMAIL
            subject = "[Timed] Employments changed in last {0} days".format(last_days)
            body = template.render({"employments": employments})
            message = EmailMessage(
                subject=subject,
                body=body,
                from_email=from_email,
                to=[email],
                headers=settings.EMAIL_EXTRA_HEADERS,
            )
            message.send() 
Example #15
Source File: utils.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def send_mass_html_mail(datatuple, fail_silently=False, user=None, password=None,
                        connection=None):
    """
    Given a datatuple of (subject, text_content, html_content, from_email,
    recipient_list), sends each message to each recipient list. Returns the
    number of emails sent.

    If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
    If auth_user and auth_password are set, they're used to log in.
    If auth_user is None, the EMAIL_HOST_USER setting is used.
    If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
    """
    connection = connection or get_connection(
        username=user, password=password, fail_silently=fail_silently)
    messages = []
    default_from = settings.DEFAULT_FROM_EMAIL
    for subject, text, html, from_email, recipients in datatuple:
        message = EmailMultiAlternatives(
            subject, text, default_from, recipients,
            headers={'Reply-To': 'Pasporta Servo <saluton@pasportaservo.org>'})
        message.attach_alternative(html, 'text/html')
        messages.append(message)
    return connection.send_messages(messages) or 0 
Example #16
Source File: utilities.py    From opencraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_urgent_alert_on_permanent_deployment_failure(sender, **kwargs):
    """
    Send an urgent alert to an e-mail when the deployment fails in a way that blocks the user.
    This is more urgent than the usual failure e-mails, and it's meant to go for instance to PagerDuty.
    This alert will only happen after ALL deployment attempts have been consumed, and ONLY if the deployment
    was triggered by the user (i.e. if the admins mass-redeploy 100 instances and 3 of them fail, this isn't
    critical and it doesn't trigger this e-mail)..
    """
    instance = kwargs['instance']
    appserver = kwargs['appserver']

    # Only sending critical alerts for failures in registered clients' instances, not in test/sandboxes
    if not instance.betatestapplication_set.exists():
        return

    if appserver is None and instance.provisioning_failure_notification_emails:
        logger.warning(
            "Sending urgent alert e-mail to %s after instance %s didn't provision",
            instance.provisioning_failure_notification_emails,
            instance,
        )

        send_mail(
            'Deployment failed at instance: {}'.format(instance),
            "The deployment of a new appserver failed and needs manual intervention. "
            "You can find the logs in the web interface.",
            settings.DEFAULT_FROM_EMAIL,
            instance.provisioning_failure_notification_emails,
            fail_silently=False,
        ) 
Example #17
Source File: utils.py    From simple-django-login-and-register with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_mail(to, template, context):
    html_content = render_to_string(f'accounts/emails/{template}.html', context)
    text_content = render_to_string(f'accounts/emails/{template}.txt', context)

    msg = EmailMultiAlternatives(context['subject'], text_content, settings.DEFAULT_FROM_EMAIL, [to])
    msg.attach_alternative(html_content, 'text/html')
    msg.send() 
Example #18
Source File: mail.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_mail(subject, message, recipient_list, from_email=None, **kwargs):
    """
    Wrapper around Django's EmailMultiAlternatives as done in send_mail().
    Custom from_email handling and special Auto-Submitted header.
    """
    if not from_email:
        if hasattr(settings, 'WAGTAILADMIN_NOTIFICATION_FROM_EMAIL'):
            from_email = settings.WAGTAILADMIN_NOTIFICATION_FROM_EMAIL
        elif hasattr(settings, 'DEFAULT_FROM_EMAIL'):
            from_email = settings.DEFAULT_FROM_EMAIL
        else:
            from_email = 'webmaster@localhost'

    connection = kwargs.get('connection', False) or get_connection(
        username=kwargs.get('auth_user', None),
        password=kwargs.get('auth_password', None),
        fail_silently=kwargs.get('fail_silently', None),
    )
    multi_alt_kwargs = {
        'connection': connection,
        'headers': {
            'Auto-Submitted': 'auto-generated',
        }
    }
    mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, **multi_alt_kwargs)
    html_message = kwargs.get('html_message', None)
    if html_message:
        mail.attach_alternative(html_message, 'text/html')

    return mail.send() 
Example #19
Source File: forms.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handle(self, request, data):
        email = self.cleaned_data["email"]
        for user in self.users:
            temp_key = token_generator.make_token(user)
            # save it to the password reset model
            # password_reset = PasswordReset(user=user, temp_key=temp_key)
            # password_reset.save()
            current_site = Site.objects.get_current()
            # send the password reset email

            path = reverse("account_reset_password_from_key",
                           kwargs=dict(uidb36=user_pk_to_url_str(user),
                                       key=temp_key))
            url = request.build_absolute_uri(path)

            context = {"site": current_site,
                       "user": user,
                       "password_reset_url": url}
            context['username'] = user.username

            send_mail(
                _('Reset password'),
                'leonardo_auth/email/password_reset_key.html',
                context,
                [email], settings.DEFAULT_FROM_EMAIL)

        return self.cleaned_data["email"] 
Example #20
Source File: mrsrequest_email.py    From mrs with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle(self, *args, **options):
        start_dt = datetime.strptime(options['start_dt'], '%Y%m%d%H%M%S')
        end_dt = datetime.strptime(options['end_dt'], '%Y%m%d%H%M%S')
        logentries = MRSRequestLogEntry.objects.filter(
            datetime__gte=start_dt,
            datetime__lte=end_dt,
        )

        logentries = logentries.select_related(
            'mrsrequest',
            'mrsrequest__insured'
        ).distinct()

        if options.get('action'):
            action = 'ACTION_' + options['action'].upper()
            logentries = logentries.filter(
                status=getattr(MRSRequestLogEntry, action)
            )

        if not options.get('confirm'):
            setattr(
                settings,
                'EMAIL_BACKEND',
                'django.core.mail.backends.console.EmailBackend'
            )

        for logentry in logentries:
            if logentry.action == MRSRequestLogEntry.ACTION_VALIDATED:
                MRSRequestValidateMixin().mail_insured(logentry.mrsrequest)
            else:
                email = EmailMessage(
                    subject=logentry.data['subject'],
                    body=logentry.data['body'],
                    to=[logentry.mrsrequest.insured.email],
                    reply_to=[settings.TEAM_EMAIL],
                    from_email=settings.DEFAULT_FROM_EMAIL,
                )
                email.send() 
Example #21
Source File: models.py    From mrs with GNU Affero General Public License v3.0 5 votes vote down vote up
def daily_mail(force=False):
    if date.today() in holidays.France() and not force:
        return

    for caisse in Caisse.objects.filter(active=True):
        mrsrequests = caisse.mrsrequest_set.all().status('new').order_by(
            'creation_datetime')

        if not len(mrsrequests):
            continue

        context = dict(
            object_list=mrsrequests,
            BASE_URL=settings.BASE_URL,
            ADMIN_ROOT=crudlfap.site.views['home'].url,
        )

        Caller(
            callback='djcall.django.email_send',
            kwargs=dict(
                subject=template.loader.get_template(
                    'caisse/liquidation_daily_mail_title.txt',
                ).render(context).strip(),
                body=template.loader.get_template(
                    'caisse/liquidation_daily_mail_body.html',
                ).render(context).strip(),
                to=[caisse.liquidation_email],
                reply_to=[settings.DEFAULT_FROM_EMAIL],
                content_subtype='html'
            )
        ).spool('mail') 
Example #22
Source File: wagtailstreamforms_hooks.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def email_submission(instance, form):
    """ Send an email with the submission. """

    if not hasattr(instance, 'advanced_settings'):
        return

    addresses = [instance.advanced_settings.to_address]
    content = ['Please see below submission\n', ]
    from_address = settings.DEFAULT_FROM_EMAIL
    subject = 'New Form Submission : %s' % instance.title

    # build up the email content
    for field, value in form.cleaned_data.items():
        if field in form.files:
            count = len(form.files.getlist(field))
            value = '{} file{}'.format(count, pluralize(count))
        elif isinstance(value, list):
            value = ', '.join(value)
        content.append('{}: {}'.format(field, value))
    content = '\n'.join(content)

    # create the email message
    email = EmailMessage(
        subject=subject,
        body=content,
        from_email=from_address,
        to=addresses
    )

    # attach any files submitted
    for field in form.files:
        for file in form.files.getlist(field):
            file.seek(0)
            email.attach(file.name, file.read(), file.content_type)

    # finally send the email
    email.send(fail_silently=True) 
Example #23
Source File: forms.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def from_email(self):
        return u"%s <%s>" % (self.cleaned_data["name"], settings.DEFAULT_FROM_EMAIL,) 
Example #24
Source File: utils.py    From opencraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def html_email_helper(template_base_name: str, context: Dict[str, Any], subject: str,
                      recipient_list: Iterable[str], from_email: str = None):
    """
    A helper function for sending HTML emails.

    @param template_base_name: Base template path. The function will append .txt and .html
           to get the appropriate templates for the text and html parts of the email respectively.
    @param context: The context to pass to the email. Automatically includes common context
           needed by emails.
    @param subject: Email subject.
    @param recipient_list: List of email addresses.
    @param from_email: The sender of the email. Uses default if nothing is passed.
    """
    email_context = build_email_context(context, subject=subject)

    text_template = get_template(f'{template_base_name}.txt')
    text_message = text_template.render(email_context)

    html_template = get_template(f'{template_base_name}.html')
    html_message = html_template.render(email_context)

    send_mail(
        subject=subject,
        message=text_message,
        html_message=html_message,
        from_email=from_email or settings.DEFAULT_FROM_EMAIL,
        recipient_list=recipient_list,
    ) 
Example #25
Source File: models.py    From codesy with GNU Affero General Public License v3.0 5 votes vote down vote up
def notify_approved_claim(sender, instance, created, **kwargs):
    claim = instance.claim
    votes_needed = claim.offers.count()

    if claim.num_rejections == votes_needed:
        email_template = get_template('../templates/email/claim_reject.html')

        current_site = Site.objects.get_current()
        email_context = ({
            'url': claim.issue.url,
            'site': current_site,
        })
        message = email_template.render(email_context)
        send_mail(
            "[codesy] Your claim has been rejected",
            message,
            settings.DEFAULT_FROM_EMAIL,
            [claim.user.email]
        )

    if votes_needed == claim.num_approvals:
        email_template = get_template('../templates/email/claim_approved.html')

        current_site = Site.objects.get_current()
        email_context = ({
            'url': claim.issue.url,
            'site': current_site,
        })
        message = email_template.render(email_context)

        send_mail(
            "[codesy] Your claim has been approved",
            message,
            settings.DEFAULT_FROM_EMAIL,
            [claim.user.email]
        ) 
Example #26
Source File: models.py    From codesy with GNU Affero General Public License v3.0 5 votes vote down vote up
def notify_matching_offerers(sender, instance, created, **kwargs):
    # Only notify when the claim is first created
    if not created:
        return True

    email_template = get_template('../templates/email/claim_notify.html')

    current_site = Site.objects.get_current()

    self_Q = models.Q(user=instance.user)
    offered0_Q = models.Q(offer=0)
    others_bids = Bid.objects.filter(
        issue=instance.issue
    ).exclude(
        self_Q | offered0_Q
    )

    for bid in others_bids:
        email_context = ({
            'user': instance.user,
            'url': instance.issue.url,
            'offer': bid.offer,
            'site': current_site,
            'claim_link': instance.get_absolute_url(),
        })
        message = email_template.render(email_context)
        send_mail(
            "[codesy] A claim needs your vote!",
            message,
            settings.DEFAULT_FROM_EMAIL,
            [bid.user.email]
        ) 
Example #27
Source File: emails.py    From pycon with MIT License 5 votes vote down vote up
def send_mail(subject, recipients, template, context={}, path="notifications/"):
    context.update({"FRONTEND_URL": settings.FRONTEND_URL})

    html_body = render_to_string(f"{path}{template}.html", context)
    text_body = render_to_string(f"{path}{template}.txt", context)

    message = EmailMultiAlternatives(
        subject, text_body, settings.DEFAULT_FROM_EMAIL, recipients
    )

    message.attach_alternative(html_body, "text/html")
    return message.send(False) 
Example #28
Source File: tasks.py    From hawkpost with MIT License 5 votes vote down vote up
def process_email(message_id, form_data, sent_by=None):
    message = Message.objects.get(id=message_id)
    box = message.box
    msg = form_data["message"]
    file_name = form_data.get("file_name", "")
    subject = _('New submission to your box: {}').format(box)
    reply_to = [sent_by] if sent_by else []

    if file_name:
        body = _("The submitted file can be found in the attachments.")
        email = EmailMultiAlternatives(
            subject,
            body,
            settings.DEFAULT_FROM_EMAIL,
            [box.owner.email],
            reply_to=reply_to,
            attachments=[(file_name, msg, "application/octet-stream")]
        )
    else:
        email = EmailMultiAlternatives(subject,
                                       msg,
                                       settings.DEFAULT_FROM_EMAIL,
                                       [box.owner.email],
                                       reply_to=reply_to)

    # Output e-mail message for debug purposes
    # with open('email.mbox', 'w') as f:
    #     f.write(email.message().as_string(unixfrom=True))

    email.send()
    now = timezone.now()
    box.last_sent_at = now
    box.save()
    message.sent_at = now
    message.status = Message.SENT
    message.save() 
Example #29
Source File: tasks.py    From hawkpost with MIT License 5 votes vote down vote up
def send_email_notification(subject, body, email):
    email = EmailMultiAlternatives(subject, body,
                                   settings.DEFAULT_FROM_EMAIL,
                                   [email])
    email.send() 
Example #30
Source File: tasks.py    From hawkpost with MIT License 5 votes vote down vote up
def send_email(user, subject, template):
    content = render_to_string(template, context={"user": user})
    email = EmailMultiAlternatives(subject, content,
                                   settings.DEFAULT_FROM_EMAIL,
                                   [user.email])
    email.send()


# Every day at 4 AM UTC