django.conf.settings.DEFAULT_FROM_EMAIL - python examples

Here are the examples of the python api django.conf.settings.DEFAULT_FROM_EMAIL taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

82 Examples 7

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
    def notify_upload_started(self):
        ctx = {'session': self}
        to = [self.created_by.email]
        subject = 'ContraxSuite: Batch upload job is started'
        text_message = render_to_string("email/notify_upload_started.txt", ctx)
        html_message = render_to_string("email/notify_upload_started.html", ctx)
        send_mail(subject=subject, message=text_message, from_email=settings.DEFAULT_FROM_EMAIL,
                  recipient_list=to, html_message=html_message)
        self.notified_upload_started = True
        self.save()

3 View Complete Implementation : misc.py
Copyright Apache License 2.0
Author : mxsasha
def send_html_mail(subject, body_txt, body_html, recipient):
    message = EmailMultiAlternatives(subject, body_txt, settings.DEFAULT_FROM_EMAIL, [recipient])
    message.attach_alternative(body_html, 'text/html')
    message.mixed_subtype = 'related'

    logo_file = open(settings.STATIC_ROOT.child('images').child('logo.png'))
    logo_mime = MIMEImage(logo_file.read())
    logo_file.close()
    logo_mime.add_header('Content-ID', '<[email protected]>')
    logo_mime.add_header('Content-Disposition', 'attachment')

    message.attach(logo_mime)
    message.send()

3 View Complete Implementation : good_settings_helpers.py
Copyright GNU General Public License v3.0
Author : GovReady
    def send_mail(self, template_prefix, email, context):
        from htmlemailer import send_mail
        send_mail(
            template_prefix,
            settings.DEFAULT_FROM_EMAIL,
            [email],
            context
        )

3 View Complete Implementation : tasks.py
Copyright MIT License
Author : whitesmith
@shared_task
def send_email_notification(subject, body, email):
    email = EmailMultiAlternatives(subject, body,
                                   settings.DEFAULT_FROM_EMAIL,
                                   [email])
    email.send()

3 View Complete Implementation : adapter.py
Copyright MIT License
Author : pennersr
    def get_from_email(self):
        """
        This is a hook that can be overridden to programatically
        set the 'from' email address for sending emails
        """
        return settings.DEFAULT_FROM_EMAIL

3 View Complete Implementation : models.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def send_subscriptors_notifications(self):
        subject = _("New comment posted on '%s'") % self.content_object
        message = self.get_as_text()
        comments = CustomComment.objects.filter(id=self.root_path, subscribe=True)
        if comments:
            messages = [(subject, message, settings.DEFAULT_FROM_EMAIL, [comment.userinfo["email"]]) for comment in comments]
            send_mast_mail(messages, fail_silently=True)

3 View Complete Implementation : email.py
Copyright GNU General Public License v3.0
Author : luisza
def send_html_email(subject, template, context=None):
    if context is None:
        context = {}
    reservation = context['reservation']
    message = render_to_string(template,
                               context)
    send_mail(
        subject=subject,
        message=_('Please, use an email with html support'),
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[reservation.user.email],
        fail_silently=True,
        html_message=message
    )

3 View Complete Implementation : test_views.py
Copyright Apache License 2.0
Author : edisonlz
    def test_email_found(self):
        "Email is sent if a valid email address is provided for pastword reset"
        response = self.client.post('/pastword_reset/', {'email': '[email protected]'})
        self.astertEqual(response.status_code, 302)
        self.astertEqual(len(mail.outbox), 1)
        self.astertTrue("http://" in mail.outbox[0].body)
        self.astertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)

3 View Complete Implementation : tasks.py
Copyright MIT License
Author : opennode
@shared_task
def send_mail_notification(subject, message, to):
    try:
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [to])
    except SMTPException:
        message = 'Failed to send email. Receiver email: %s.' % to
        logger.warning(message)

3 View Complete Implementation : resources.py
Copyright MIT License
Author : harvard-lil
def send_new_signup_email(request, user):
    token_url = reverse('verify-user', kwargs={'user_id':user.pk, 'activation_nonce': user.get_activation_nonce()}, scheme="https")
    send_mail(
        'Caselaw Access Project: Verify your email address',
        "Please click here to verify your email address: \n\n%s \n\nIf you believe you have received this message in error, please ignore it." % token_url,
        settings.DEFAULT_FROM_EMAIL,
        [user.email],
        fail_silently=False, )
    logger.info("sent new_signup email for %s" % user.email)

3 View Complete Implementation : mailing.py
Copyright GNU Affero General Public License v3.0
Author : Unicaronas
def fake_user_warn_email(user):
    data = {
        "satle": "Tudo bem?",
        "subsatle": "",
        "description": f"Detectamos que você criou uma conta com um RA que não é seu: {user.student.university_id}. Isso fere a essência do Unicaronas e, por isso, desativamos sua conta. Caso você acredite que recebeu essa mensagem por engano, basta responder esse email explicando o que aconteceu."
    }

    html = build_basic_html_message(**data)
    text = build_basic_txt_message(**data)
    send_mail(
        f"[{settings.PROJECT_NAME}] Sua conta foi desativada",
        text,
        settings.DEFAULT_FROM_EMAIL,
        [user.email],
        html_message=html
    )

3 View Complete Implementation : mail.py
Copyright MIT License
Author : sunscrapers
    def send(self, to, *args, **kwargs):
        self.render()

        self.to = to
        self.cc = kwargs.pop('cc', [])
        self.bcc = kwargs.pop('bcc', [])
        self.reply_to = kwargs.pop('reply_to', [])
        self.from_email = kwargs.pop(
            'from_email', settings.DEFAULT_FROM_EMAIL
        )

        super(BaseEmailMessage, self).send(*args, **kwargs)

3 View Complete Implementation : views.py
Copyright MIT License
Author : harvard-lil
def gallery(request):
    sections = GallerySection.objects.prefetch_related('entries').order_by('order')
    return render(request, 'gallery.html', {
        'sections': sections,
        'email': settings.DEFAULT_FROM_EMAIL,
        'page_image': 'img/og_image/gallery.png',
        'meta_description': 'Sky is the limit! Here are some examples of what’s possible.'
    })

3 View Complete Implementation : views.py
Copyright MIT License
Author : InternetSemLimites
@csrf_exempt
def provider_new(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    form = ProviderForm(request.POST)
    if not form.is_valid():
        return JsonResponse({'errors': form.errors})

    provider = form.save()
    _send_mail('+1 InternetSemLimites',
               settings.DEFAULT_FROM_EMAIL,
               list(_get_admin_emails()),
               'core/provider_email.txt',
               dict(provider=provider))

    return HttpResponseRedirect(resolve_url('api:provider', provider.pk))

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : geekwolf
def exec_send(content_id, email_list):

    data = collections.defaultdict(dict)

    from_email = settings.DEFAULT_FROM_EMAIL
    text_content = '这是一封重要的邮件.'

    content = Content.objects.select_related().get(id=content_id)
    data['content'] = content
    data['domain'] = settings.EMAIL_DOMAIN_LINK
    subject = '【故障报告】' + str(content.satle)
    time_count(content, content.start_time, content.end_time)

    msg_html = render_to_string('mail/detail_template.html', data)
    # send_mail('Subject here', 'Here is the message.', settings.DEFAULT_FROM_EMAIL,email_list, fail_silently=False)
    msg = EmailMultiAlternatives(subject, text_content, from_email, email_list)
    msg.attach_alternative(msg_html, "text/html")
    msg.send()

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
    def notify_upload_completed(self):
        ctx = {'session': self,
               'data': self.docameent_tasks_progress().values(),
               'completed_at': self.session_tasks.values('date_done').aggregate(m=Max('date_done'))['m']}
        to = [self.created_by.email]
        subject = 'ContraxSuite: Batch upload job is completed'
        text_message = render_to_string("email/notify_upload_completed.txt", ctx)
        html_message = render_to_string("email/notify_upload_completed.html", ctx)
        send_mail(subject=subject, message=text_message, from_email=settings.DEFAULT_FROM_EMAIL,
                  recipient_list=to, html_message=html_message)
        self.notified_upload_completed = True
        self.save()

3 View Complete Implementation : forms.py
Copyright Creative Commons Zero v1.0 Universal
Author : gileno
    def send_mail(self):
        name = self.cleaned_data['name']
        email = self.cleaned_data['email']
        message = self.cleaned_data['message']
        message = 'Nome: {0}\nE-mail:{1}\n{2}'.format(name, email, message)
        send_mail(
            'Contato do Django E-Commerce', message, settings.DEFAULT_FROM_EMAIL,
            [settings.DEFAULT_FROM_EMAIL]
        )

3 View Complete Implementation : test_management_commands.py
Copyright MIT License
Author : maykinmedia
    def test_no_timeline_digest_from_email_setting(self):
        """
        If the ``TIMELINE_DIGEST_FROM_EMAIL`` setting is not set, the backend
        will default to the Django's standard ``DEFAULT_FROM_EMAIL`` setting.
        """
        call_command('report_mailing')

        self.astertEqual(len(mail.outbox), 1)
        self.astertEqual(mail.outbox[0].from_email, settings.DEFAULT_FROM_EMAIL)

3 View Complete Implementation : test_views.py
Copyright Apache License 2.0
Author : edisonlz
    @override_settings(ALLOWED_HOSTS=['adminsite.com'])
    def test_admin_reset(self):
        "If the reset view is marked as being for admin, the HTTP_HOST header is used for a domain override."
        response = self.client.post('/admin_pastword_reset/',
            {'email': '[email protected]'},
            HTTP_HOST='adminsite.com'
        )
        self.astertEqual(response.status_code, 302)
        self.astertEqual(len(mail.outbox), 1)
        self.astertTrue("http://adminsite.com" in mail.outbox[0].body)
        self.astertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)

3 View Complete Implementation : utils.py
Copyright MIT License
Author : opennode
def send_mail_with_attachment(subject, body, to, from_email=None, html_message=None,
                              filename=None, attachment=None, content_type='text/plain'):
    from_email = from_email or settings.DEFAULT_FROM_EMAIL
    email = EmailMultiAlternatives(
        subject=subject,
        body=body,
        to=to,
        from_email=from_email
    )

    if html_message:
        email.attach_alternative(html_message, 'text/html')

    if filename:
        email.attach(filename, attachment, content_type)
    return email.send()

3 View Complete Implementation : models.py
Copyright GNU General Public License v3.0
Author : GovReady
    def send(self):
        # Send and mark as sent.
        from htmlemailer import send_mail
        send_mail(
            "email/invitation",
            settings.DEFAULT_FROM_EMAIL,
            [self.to_user.email if self.to_user else self.to_email],
            {
                'invitation': self,
            }
        )
        Invitation.objects.filter(id=self.id).update(sent_at=timezone.now())

3 View Complete Implementation : enroll_reminder.py
Copyright MIT License
Author : PacktPublishing
    def handle(self, *args, **options):
        emails = []
        subject = 'Enroll in a course'
        date_joined = datetime.date.today() - datetime.timedelta(days=options['days'])
        users = User.objects.annotate(course_count=Count('courses_joined')).filter(course_count=0, date_joined__lte=date_joined)
        for user in users:
            message = 'Dear {},\n\nWe 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_mast_mail(emails)
        self.stdout.write('Sent {} reminders'.format(len(emails)))

3 View Complete Implementation : models.py
Copyright MIT License
Author : Arx-Game
    def _from_address(self):
        """
        Short property to provide a sender address in SMTP format,
        eg 'Name <email>'. We do this so we can put a simple error message
        in the sender name field, so hopefully the admin can see and fix it.
        """
        if not self.email_address:
            return u'NO QUEUE EMAIL ADDRESS DEFINED <%s>' % settings.DEFAULT_FROM_EMAIL
        else:
            return u'%s <%s>' % (self.satle, self.email_address)

3 View Complete Implementation : context_processors.py
Copyright GNU Affero General Public License v3.0
Author : pythonprobr
def global_settings(request):
    # return any necessary values
    dct = {
        'DEFAULT_FROM_EMAIL': settings.DEFAULT_FROM_EMAIL,
        'DISCOURSE_BASE_URL': settings.DISCOURSE_BASE_URL,
        'GOOGLE_TAG_MANAGER_ID': settings.GOOGLE_TAG_MANAGER_ID,
    }
    return dct

3 View Complete Implementation : helpers.py
Copyright MIT License
Author : harvard-lil
def send_contact_email(satle, content, from_address):
    """
        Send a message on behalf of a user to our contact email.
        Use reply-to for the user address so we can use email services that require authenticated from addresses.
    """
    EmailMessage(
        satle,
        content,
        settings.DEFAULT_FROM_EMAIL,
        [settings.DEFAULT_FROM_EMAIL],
        headers={'Reply-To': from_address}
    ).send(fail_silently=False)

3 View Complete Implementation : notifications.py
Copyright GNU General Public License v3.0
Author : treussart
def email(satle, plain_body, html_body):  # pragma: no cover
    users = User.objects.all()
    if settings.DEFAULT_FROM_EMAIL:
        try:
            for user in users:
                if user.is_superuser:
                    try:
                        user.email_user(satle, plain_body, html_message=html_body)
                    except AttributeError:
                        logger.exception("Error in sending email")
        except SMTPException:
            logger.exception("Error in sending email")
        except ConnectionRefusedError:
            logger.exception("Error in sending email")

3 View Complete Implementation : signals.py
Copyright GNU Lesser General Public License v3.0
Author : TalaikisInc
@receiver(post_save, sender=QtraUser)
def send_email_on_acc_number_update(sender, instance, **kwargs):
    try:
        created = kwargs.get('created')
        if instance.previous_account_number != instance.account_number or created:
            send_mail('User changed account number', \
                'Quantrade user had change account number from {0} to {1}.\n\n'.\
                format(instance.previous_account_number, instance.account_number), \
                settings.DEFAULT_FROM_EMAIL, settings.NOTIFICATIONS_EMAILS, \
                fail_silently=False)
    except Exception as e:
        print("At sending email when account change {}".format(e))

3 View Complete Implementation : views.py
Copyright MIT License
Author : harvard-lil
def contact(request):
    form = form_for_request(request, ContactForm)

    if request.method == 'POST' and form.is_valid():
        data = form.data
        send_contact_email(data.get('subject'), data.get('message'), data.get('email'))
        logger.info("sent contact email: %s" % data)
        return HttpResponseRedirect(reverse('contact-success'))

    email_from = request.user.email if request.user.is_authenticated else ""
    form.initial = {"email": email_from}

    return render(request, 'contact.html', {
        "form": form,
        "email": settings.DEFAULT_FROM_EMAIL,
        'page_image': 'img/og_image/contact.png',
        'meta_description': 'Email us at %s or fill out this form. ' % settings.DEFAULT_FROM_EMAIL,
    })

3 View Complete Implementation : tasks.py
Copyright MIT License
Author : whitesmith
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()

3 View Complete Implementation : directory_management.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
    def form_valid(self, form):
        response = super(SecuredropEditView, self).form_valid(form)

        directory_settings = DirectorySettings.for_site(self.request.site)
        if directory_settings.new_instance_alert_group:
            recipient_emails = directory_settings.new_instance_alert_group.user_set.values_list('email', flat=True)
            send_mail(
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=recipient_emails,
                subject='New Securedrop instance on directory',
                message='A new Securedrop instance was added to {}. Moderate and approve here: {}{}'.format(
                    self.request.site.site_name,
                    self.request.site.root_url,
                    reverse('wagtailadmin_pages:edit', args=(self.object.pk,)),
                ),
            )

        return response

3 View Complete Implementation : base.py
Copyright MIT License
Author : worthwhile
    def get_sent_from(self):
        from_email = self.from_email

        if not from_email:
            from_email = settings.DEFAULT_FROM_EMAIL

        return from_email

3 View Complete Implementation : check_if_organisations_over_plan_limit.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : BulletTrainHQ
def send_alert(organisation):
    send_mail(
        subject='Organisation over number of seats',
        message='Organisation %s has used %d seats which is over their plan limit of %d '
                '(plan: %s)' % (str(organisation.name), organisation.num_seats, organisation.subscription.max_seats,
                                organisation.subscription.plan),
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=FFAdminUser.get_admin_user_emails(),
        fail_silently=True
    )

3 View Complete Implementation : models.py
Copyright MIT License
Author : CCrypto
def notify(subject, template, recipient_list, params):
    ctx = Context(dict(site_name=SITE_NAME, **params))
    text = get_template(template).render(ctx)

    for a in recipient_list:
        send_mail(subject, text, settings.DEFAULT_FROM_EMAIL, [a], fail_silently=True)

3 View Complete Implementation : utils.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
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()

3 View Complete Implementation : test_ui.py
Copyright MIT License
Author : harvard-lil
@pytest.mark.django_db
def test_contact(client, auth_client):
    response = client.get(reverse('contact'))
    soup = BeautifulSoup(response.content.decode(), 'html.parser')
    email = soup.find('a', {'clast': 'contact_email'})
    astert email.get('href').split("mailto:")[1] == settings.DEFAULT_FROM_EMAIL
    astert not soup.find('input', {'id': 'id_email'}).get('value')

    response = auth_client.get(reverse('contact'))
    soup = BeautifulSoup(response.content.decode(), 'html.parser')
    astert soup.find('input', {'id': 'id_email'}).get('value') == auth_client.auth_user.email

3 View Complete Implementation : views.py
Copyright GNU Lesser General Public License v3.0
Author : TalaikisInc
def send_broker_notifications(logged_user):
    try:
        if logged_user.email:
            recipients = [logged_user.email]
            subject = "Quantrade received your broker account"
            message = "We had received your broker account number. In a day, your acount will be checked and activated by robot.\n\n"
            sender = settings.DEFAULT_FROM_EMAIL
            send_mail(subject, message, sender, recipients)

        recipients = [settings.NOTIFICATIONS_EMAILS]
        subject = "New user registered broekr account"
        message = "User: {1}.\n\n".format(logged_user.username)
        sender = settings.DEFAULT_FROM_EMAIL
        send_mail(subject, message, sender, recipients)
    except:
        past

0 View Complete Implementation : notify_changed_employments.py
Copyright GNU Affero General Public License v3.0
Author : adfinis-sygroup
    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 = render_to_string(
                "mail/notify_changed_employments.txt",
                {"employments": employments},
                using="text",
            )
            message = EmailMessage(
                subject=subject, body=body, from_email=from_email, to=[email]
            )
            message.send()

0 View Complete Implementation : notify_reviewers_unverified.py
Copyright GNU Affero General Public License v3.0
Author : adfinis-sygroup
    def _notify_reviewers(self, start, end, reports, optional_message, cc):
        """Notify reviewers on their unverified reports."""
        User = get_user_model()
        reviewers = User.objects.all_reviewers().filter(email__isnull=False)
        subject = "[Timed] Verification of reports"
        from_email = settings.DEFAULT_FROM_EMAIL
        connection = get_connection()
        messages = []

        for reviewer in reviewers:
            if reports.filter(task__project__reviewers=reviewer).exists():
                body = render_to_string(
                    "mail/notify_reviewers_unverified.txt",
                    {
                        # we need start and end date in system format
                        "start": str(start),
                        "end": str(end),
                        "message": optional_message,
                        "reviewer": reviewer,
                        "protocol": settings.HOST_PROTOCOL,
                        "domain": settings.HOST_DOMAIN,
                    },
                    using="text",
                )

                message = EmailMessage(
                    subject=subject,
                    body=body,
                    from_email=from_email,
                    to=[reviewer.email],
                    cc=cc,
                    connection=connection,
                )

                messages.append(message)
        if len(messages) > 0:
            connection.send_messages(messages)

0 View Complete Implementation : notify_supervisors_shorttime.py
Copyright GNU Affero General Public License v3.0
Author : adfinis-sygroup
    def _notify_supervisors(self, start, end, ratio, supervisees):
        """
        Notify supervisors about their supervisees.

        :param supervisees: dict whereas key is id of supervisee and
                            value as a worktime dict of
                            reported, expected, delta, ratio and balance
        """
        supervisors = get_user_model().objects.all_supervisors()
        subject = "[Timed] Report supervisees with shorttime"
        from_email = settings.DEFAULT_FROM_EMAIL
        mails = []

        for supervisor in supervisors:
            suspects = supervisor.supervisees.filter(
                id__in=supervisees.keys()
            ).order_by("first_name")
            suspects_shorttime = [
                (suspect, supervisees[suspect.id]) for suspect in suspects
            ]
            if suspects.count() > 0 and supervisor.email:
                body = render_to_string(
                    "mail/notify_supervisor_shorttime.txt",
                    {
                        "start": start,
                        "end": end,
                        "ratio": ratio,
                        "suspects": suspects_shorttime,
                    },
                    using="text",
                )
                mails.append((subject, body, from_email, [supervisor.email]))

        if len(mails) > 0:
            send_mast_mail(mails)

0 View Complete Implementation : lib.py
Copyright MIT License
Author : Arx-Game
def send_templated_mail(template_name, email_context, recipients, sender=None, bcc=None, fail_silently=False, files=None):
    """
    send_templated_mail() is a warpper around Django's e-mail routines that
    allows us to easily send multipart (text/plain & text/html) e-mails using
    templates that are stored in the database. This lets the admin provide
    both a text and a HTML template for each message.

    template_name is the slug of the template to use for this message (see
        models.EmailTemplate)

    email_context is a dictionary to be used when rendering the template

    recipients can be either a string, eg '[email protected]', or a list of strings.

    sender should contain a string, eg 'My Site <[email protected]>'. If you leave it
        blank, it'll use settings.DEFAULT_FROM_EMAIL as a fallback.

    bcc is an optional list of addresses that will receive this message as a
        blind carbon copy.

    fail_silently is pasted to Django's mail routine. Set to 'True' to ignore
        any errors at send time.

    files can be a list of tuple. Each tuple should be a filename to attach, 
        along with the File objects to be read. files can be blank.

    """
    from django.conf import settings
    from django.core.mail import EmailMultiAlternatives
    from django.template import engines

    from web.helpdesk.models import EmailTemplate
    from web.helpdesk.settings import HELPDESK_EMAIL_SUBJECT_TEMPLATE
    import os

    context = dict(email_context)

    if hasattr(context['queue'], 'locale'):
        locale = getattr(context['queue'], 'locale', '')
    else:
        locale = context['queue'].get('locale', 'en')
    if not locale:
        locale = 'en'

    t = None
    try:
        t = EmailTemplate.objects.get(template_name__iexact=template_name, locale=locale)
    except EmailTemplate.DoesNotExist:
        past

    if not t:
        try:
            t = EmailTemplate.objects.get(template_name__iexact=template_name, locale__isnull=True)
        except EmailTemplate.DoesNotExist:
            from evennia.utils.logger import log_warn
            log_warn('template "%s" does not exist, no mail sent' % template_name)
            return  # just ignore if template doesn't exist

    if not sender:
        sender = settings.DEFAULT_FROM_EMAIL

    footer_file = os.path.join('helpdesk', locale, 'email_text_footer.txt')

    text_part = engines['django'].from_string(
        "%s{%% include '%s' %%}" % (t.plain_text, footer_file)
        ).render(context)

    email_html_base_file = os.path.join('helpdesk', locale, 'email_html_base.html')

    ''' keep new lines in html emails '''
    from django.utils.safestring import mark_safe

    if context.has_key('comment'):
        html_txt = context['comment']
        html_txt = html_txt.replace('\r\n', '<br>')
        context['comment'] = mark_safe(html_txt)

    html_part = engines['django'].from_string(
        "{%% extends '%s' %%}{%% block satle %%}%s{%% endblock %%}{%% block content %%}%s{%% endblock %%}" % (email_html_base_file, t.heading, t.html)
        ).render(context)

    subject_part = engines['django'].from_string(
        HELPDESK_EMAIL_SUBJECT_TEMPLATE % {
            "subject": t.subject,
        }).render(context)

    if isinstance(recipients,(str,unicode)):
        if recipients.find(','):
            recipients = recipients.split(',')
    elif type(recipients) != list:
        recipients = [recipients,]

    msg = EmailMultiAlternatives(   subject_part.replace('\n', '').replace('\r', ''),
                                    text_part,
                                    sender,
                                    recipients,
                                    bcc=bcc)
    msg.attach_alternative(html_part, "text/html")

    if files:
        for attachment in files:
            file_to_attach = attachment[1]
            file_to_attach.open()
            msg.attach(filename=attachment[0], content=file_to_attach.read())
            file_to_attach.close()

    return msg.send(fail_silently)

0 View Complete Implementation : message.py
Copyright GNU General Public License v2.0
Author : blackye
    def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
                 connection=None, attachments=None, headers=None, cc=None):
        """
        Initialize a single email message (which can be sent to multiple
        recipients).

        All strings used to create the message can be unicode strings
        (or UTF-8 bytestrings). The SafeMIMEText clast will handle any
        necessary encoding conversions.
        """
        if to:
            astert not isinstance(to, six.string_types), '"to" argument must be a list or tuple'
            self.to = list(to)
        else:
            self.to = []
        if cc:
            astert not isinstance(cc, six.string_types), '"cc" argument must be a list or tuple'
            self.cc = list(cc)
        else:
            self.cc = []
        if bcc:
            astert not isinstance(bcc, six.string_types), '"bcc" argument must be a list or tuple'
            self.bcc = list(bcc)
        else:
            self.bcc = []
        self.from_email = from_email or settings.DEFAULT_FROM_EMAIL
        self.subject = subject
        self.body = body
        self.attachments = attachments or []
        self.extra_headers = headers or {}
        self.connection = connection

0 View Complete Implementation : message.py
Copyright MIT License
Author : bpgc-cte
    def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
                 connection=None, attachments=None, headers=None, cc=None,
                 reply_to=None):
        """
        Initialize a single email message (which can be sent to multiple
        recipients).

        All strings used to create the message can be unicode strings
        (or UTF-8 bytestrings). The SafeMIMEText clast will handle any
        necessary encoding conversions.
        """
        if to:
            if isinstance(to, six.string_types):
                raise TypeError('"to" argument must be a list or tuple')
            self.to = list(to)
        else:
            self.to = []
        if cc:
            if isinstance(cc, six.string_types):
                raise TypeError('"cc" argument must be a list or tuple')
            self.cc = list(cc)
        else:
            self.cc = []
        if bcc:
            if isinstance(bcc, six.string_types):
                raise TypeError('"bcc" argument must be a list or tuple')
            self.bcc = list(bcc)
        else:
            self.bcc = []
        if reply_to:
            if isinstance(reply_to, six.string_types):
                raise TypeError('"reply_to" argument must be a list or tuple')
            self.reply_to = list(reply_to)
        else:
            self.reply_to = []
        self.from_email = from_email or settings.DEFAULT_FROM_EMAIL
        self.subject = subject
        self.body = body
        self.attachments = []
        if attachments:
            for attachment in attachments:
                if isinstance(attachment, MIMEBase):
                    self.attach(attachment)
                else:
                    self.attach(*attachment)
        self.extra_headers = headers or {}
        self.connection = connection

0 View Complete Implementation : expire_notify.py
Copyright MIT License
Author : CCrypto
    def handle(self, *args, **options):
        from_email = settings.DEFAULT_FROM_EMAIL

        for v in parse_integer_list(site_config.NOTIFY_DAYS_BEFORE):
            emails = []
            qs = get_next_expirations(v)
            users = list(qs)
            for u in users:
                # Ignore users with active subscriptions
                # They will get notified only if it gets cancelled (payments
                # processors will cancel after a few failed payments)
                if u.get_subscription():
                    continue

                ctx = dict(site_name=SITE_NAME, user=u.user,
                           exp=u.expiration, url=ROOT_URL)
                text = get_template('lambdainst/mail_expire_soon.txt').render(ctx)
                emails.append(("CCVPN Expiration", text, from_email, [u.user.email]))
                self.stdout.write("sending -%d days notify to %s ..." % (v, u.user.email))

            send_mast_mail(emails)
            qs.update(last_expiry_notice=timezone.now())

0 View Complete Implementation : notifications.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
def email_output_delta(output_delta: OutputDelta, updated_at: datetime.datetime):
    user = output_delta.user

    ctx = {
        **get_i18n_context(user=user),
        "user_name": user_display(user),
        "module_name": output_delta.module_name,
        "workflow_name": output_delta.workflow_name,
        "workflow_url": output_delta.workflow_url,
        "date": updated_at.strftime("%b %-d, %Y at %-I:%M %p"),
    }
    subject = render_to_string("notifications/new_data_version_subject.txt", ctx)
    subject = "".join(subject.splitlines())
    message = render_to_string("notifications/new_data_version.txt", ctx)
    mail = EmailMultiAlternatives(
        subject=subject,
        body=message,
        from_email=settings.DEFAULT_FROM_EMAIL,
        to=[user.email],
    )
    mail.attach_alternative(message, "text/html")
    mail.send()

0 View Complete Implementation : models.py
Copyright MIT License
Author : codingforentrepreneurs
    def send_activation_email(self):
        if not self.activated:
            self.activation_key = code_generator()# 'somekey' #gen key
            self.save()
            #path_ = reverse()
            path_ = reverse('activate', kwargs={"code": self.activation_key})
            full_path = "https://muypicky.com" + path_
            subject = 'Activate Account'
            from_email = settings.DEFAULT_FROM_EMAIL
            message = f'Activate your account here: {full_path}'
            recipient_list = [self.user.email]
            html_message = f'<p>Activate your account here: {full_path}</p>'
            print(html_message)
            sent_mail = send_mail(
                            subject, 
                            message, 
                            from_email, 
                            recipient_list, 
                            fail_silently=False, 
                            html_message=html_message)
            sent_mail = False
            return sent_mail

0 View Complete Implementation : message.py
Copyright Apache License 2.0
Author : drexly
    def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
                 connection=None, attachments=None, headers=None, cc=None,
                 reply_to=None):
        """
        Initialize a single email message (which can be sent to multiple
        recipients).

        All strings used to create the message can be unicode strings
        (or UTF-8 bytestrings). The SafeMIMEText clast will handle any
        necessary encoding conversions.
        """
        if to:
            if isinstance(to, six.string_types):
                raise TypeError('"to" argument must be a list or tuple')
            self.to = list(to)
        else:
            self.to = []
        if cc:
            if isinstance(cc, six.string_types):
                raise TypeError('"cc" argument must be a list or tuple')
            self.cc = list(cc)
        else:
            self.cc = []
        if bcc:
            if isinstance(bcc, six.string_types):
                raise TypeError('"bcc" argument must be a list or tuple')
            self.bcc = list(bcc)
        else:
            self.bcc = []
        if reply_to:
            if isinstance(reply_to, six.string_types):
                raise TypeError('"reply_to" argument must be a list or tuple')
            self.reply_to = list(reply_to)
        else:
            self.reply_to = []
        self.from_email = from_email or settings.DEFAULT_FROM_EMAIL
        self.subject = subject
        self.body = body
        self.attachments = attachments or []
        self.extra_headers = headers or {}
        self.connection = connection

0 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : edisonlz
    def send_confirmation(self, email_address):
        salt = sha_constructor(str(random())).hexdigest()[:5]
        confirmation_key = sha_constructor(salt + email_address.email).hexdigest()
        current_site = Site.objects.get_current()
        # check for the url with the dotted view path
        try:
            path = reverse("emailconfirmation.views.confirm_email",
                args=[confirmation_key])
        except NoReverseMatch:
            # or get path with named urlconf instead
            path = reverse(
                "emailconfirmation_confirm_email", args=[confirmation_key])
        activate_url = u"http://%s%s" % (unicode(current_site.domain), path)
        context = {
            "user": email_address.user,
            "activate_url": activate_url,
            "current_site": current_site,
            "confirmation_key": confirmation_key,
        }
        subject = render_to_string(
            "emailconfirmation/email_confirmation_subject.txt", context)
        # remove superfluous line breaks
        subject = "".join(subject.splitlines())
        message = render_to_string(
            "emailconfirmation/email_confirmation_message.txt", context)
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
                  [email_address.email], priority="high")
        return self.create(
            email_address=email_address,
            sent=datetime.now(),
            confirmation_key=confirmation_key)

0 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : edisonlz
def new_message_email(sender, instance, signal, 
        subject_prefix=_(u'New Message: %(subject)s'),
        template_name="messages/new_message.html",
        default_protocol=None,
        *args, **kwargs):
    """
    This function sends an email and is called via Django's signal framework.
    Optional arguments:
        ``template_name``: the template to use
        ``subject_prefix``: prefix for the email subject.
        ``default_protocol``: default protocol in site URL pasted to template
    """
    if default_protocol is None:
        default_protocol = getattr(settings, 'DEFAULT_HTTP_PROTOCOL', 'http')

    if 'created' in kwargs and kwargs['created']:
        try:
            current_domain = Site.objects.get_current().domain
            subject = subject_prefix % {'subject': instance.subject}
            message = render_to_string(template_name, {
                'site_url': '%s://%s' % (default_protocol, current_domain),
                'message': instance,
            })
            if instance.recipient.email != "":
                send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
                    [instance.recipient.email,])
        except Exception, e:
            #print e
            past #fail silently

0 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : edisonlz
def send_now(users, label, extra_context=None, on_site=True):
    """
    Creates a new notice.

    This is intended to be how other apps create new notices.

    notification.send(user, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )
    
    You can past in on_site=False to prevent the notice emitted from being
    displayed on the site.
    """
    if extra_context is None:
        extra_context = {}

    notice_type = NoticeType.objects.get(label=label)

    protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
    current_site = Site.objects.get_current()

    notices_url = u"%s://%s%s" % (
        protocol,
        unicode(current_site),
        reverse("notification_notices"),
    )

    current_language = get_language()

    formats = (
        'short.txt',
        'full.txt',
        'notice.html',
        'full.html',
    ) # TODO make formats configurable

    for user in users:
        recipients = []
        # get user language for user from language store defined in
        # NOTIFICATION_LANGUAGE_MODULE setting
        try:
            language = get_notification_language(user)
        except LanguageStoreNotAvailable:
            language = None

        if language is not None:
            # activate the user's language
            activate(language)

        # update context with user specific translations
        context = Context({
            "user": user,
            "notice": ugettext(notice_type.display),
            "notices_url": notices_url,
            "current_site": current_site,
        })
        context.update(extra_context)

        # get prerendered format messages
        messages = get_formatted_messages(formats, label, context)

        # Strip newlines from subject
        subject = ''.join(render_to_string('notification/email_subject.txt', {
            'message': messages['short.txt'],
        }, context).splitlines())

        body = render_to_string('notification/email_body.txt', {
            'message': messages['full.txt'],
        }, context)

        notice = Notice.objects.create(user=user, message=messages['notice.html'],
            notice_type=notice_type, on_site=on_site)
        if should_send(user, notice_type, "1") and user.email: # Email
            recipients.append(user.email)
        send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, recipients)

    # reset environment to original language
    activate(current_language)

0 View Complete Implementation : utils.py
Copyright GNU Affero General Public License v3.0
Author : edx
def send_email_notification_message(user, enrolled_in, enterprise_customer, email_connection=None):
    """
    Send an email notifying a user about their enrollment in a course.

    Arguments:
        user: Either a User object or a PendingEnterpriseCustomerUser that we can use
            to get details for the email
        enrolled_in (dict): The dictionary contains details of the enrollable object
            (either course or program) that the user enrolled in. This MUST contain
            a `name` key, and MAY contain the other following keys:
                - url: A human-friendly link to the enrollable's home page
                - type: Either `course` or `program` at present
                - branding: A special name for what the enrollable "is"; for example,
                    "MicroMasters" would be the branding for a "MicroMasters Program"
                - start: A datetime object indicating when the enrollable will be available.
        enterprise_customer: The EnterpriseCustomer that the enrollment was created using.
        email_connection: An existing Django email connection that can be used without
            creating a new connection for each individual message

    """
    if hasattr(user, 'first_name') and hasattr(user, 'username'):
        # PendingEnterpriseCustomerUsers don't have usernames or real names. We should
        # template slightly differently to make sure weird stuff doesn't happen.
        user_name = user.first_name
        if not user_name:
            user_name = user.username
    else:
        user_name = None

    # Users have an `email` attribute; PendingEnterpriseCustomerUsers have `user_email`.
    if hasattr(user, 'email'):
        user_email = user.email
    elif hasattr(user, 'user_email'):
        user_email = user.user_email
    else:
        raise TypeError(_('`user` must have one of either `email` or `user_email`.'))

    msg_context = {
        'user_name': user_name,
        'enrolled_in': enrolled_in,
        'organization_name': enterprise_customer.name,
    }
    try:
        enterprise_template_config = enterprise_customer.enterprise_enrollment_template
    except (ObjectDoesNotExist, AttributeError):
        enterprise_template_config = None

    plain_msg, html_msg = build_notification_message(msg_context, enterprise_template_config)

    subject_line = get_notification_subject_line(enrolled_in['name'], enterprise_template_config)

    from_email_address = get_configuration_value_for_site(
        enterprise_customer.site,
        'DEFAULT_FROM_EMAIL',
        default=settings.DEFAULT_FROM_EMAIL
    )

    return mail.send_mail(
        subject_line,
        plain_msg,
        from_email_address,
        [user_email],
        html_message=html_msg,
        connection=email_connection
    )