Ejemplo n.º 1
0
    def handle(self, *args, **kwargs):
        ### Select 
        today = date.today()
        messages = ()
        for user in User.objects.all():
            ### Check batches ready to bottle
            bottle_batch_list = Batch.objects.filter(predicted_ready__lte=today,user=user,notified_bottle_complete=False)
            brewed_batch_list = Batch.objects.filter(predicted_brew_ready__lte=today,user=user,notified_brew_complete=False)
            ### Check batches ready to drink.
            if len(brewed_batch_list) > 0 or len(bottle_batch_list) > 0:
                message_body = 'Hi {user}, the following is ready:\n\n'.format(user=user)
                for batch in brewed_batch_list:
                    message_body += '- Batch #{id}, {name}, is ready to bottle.\n'.format(id=batch.id, name=batch)
                    batch.notified_brew_complete = True
                    batch.save()
                for batch in bottle_batch_list:
                    message_body += '- Batch #{id}, {name}, is ready to drink!\n'.format(id=batch.id, name=batch)
                    batch.notified_bottle_complete = True
                    batch.save()
                message_body += '\nSincerely,\n\nThe homebrew fairy'

                #Prepare the email.
                message = ('Homebrew notification {date}'.format(date=today),
                            message_body,
                            '*****@*****.**',
                            [user.email])
                messages += (message,)
        if len(messages) > 0:
            send_mass_mail(messages, fail_silently=False)
Ejemplo n.º 2
0
    def cancel(self, user, *args, **kwargs):
        extra_note = ''
        part_of_your = 'Part of your'
        if self.booking.booking_parts.exclude(state='cancelled').exclude(id=self.id).count() == 0 and self.booking.cancel.is_available() and kwargs.get('cancel_children', True):
            self.booking.cancel(silent=True, user=user, cancel_children=False)
            extra_note += "\nThis resulted in the cancellation of the booking, as there were no more active parts remaining."
            part_of_your = 'Your'

        if not kwargs.get('silent', False):
            interested_parties = [('{} booking #{} has been cancelled'.format(part_of_your, self.booking.id), self.booking.user.email)]
            from_email = '*****@*****.**'
            message = """
Hello,

Part of your booking number #{} has been cancelled by {}.

Your booking of {}, which was booked from {} to {} was cancelled.{}

Regards,
The Media Booking System
""".format(self.booking.id, user, self.lendable.name, self.start_date, self.end_date, extra_note)

            datatuple = [(subject, message, from_email, [recipient]) for (subject, recipient) in interested_parties]

            mail.send_mass_mail(datatuple, fail_silently=True)
Ejemplo n.º 3
0
    def send(cls, sender, event_type, request, **kwargs):
        catalogue = sender
        from_email = settings.FROM_EMAIL

        if event_type == 'published':
            action = 'added'
            subject = 'A new {0} was {1}'.format(catalogue.kind, action)
        if event_type == 'updated':
            action = 'edited'
            article = 'An' if catalogue.kind == 'offer' else 'A'
            subject = '{0} {1} was {2}'.format(article, catalogue.kind, action)

        catalogue_url = reverse('catalogue_view', kwargs={
            'pk': catalogue.pk, 'kind': catalogue.kind
        })
        notifications_url = reverse('notifications:home')

        body = render_to_string('notification_email.html', {
            'catalogue': catalogue,
            'action': action,
            'notifications_url': request.build_absolute_uri(notifications_url),
            'catalogue_url': request.build_absolute_uri(catalogue_url),
        })

        datatuple = []
        for user in cls.objects.filter(subscribed=True):
            email = [get_user_email(user.user_id)]
            datatuple.append((subject, body, from_email, email))
        send_mass_mail(datatuple)
Ejemplo n.º 4
0
def new_d_msg(t, d, name, hp, mail):
    subject = u'【新释义】有人提交了新的释义!'
    message = d_msg(t, d, name, hp, mail)
    from_email = '*****@*****.**'
    recipient_list = ['*****@*****.**']
    message1 = (subject, message, from_email, recipient_list)
    send_mass_mail((message1,), fail_silently=False)
Ejemplo n.º 5
0
 def mass_mail_volunteer(self, request, queryset):
     if not request.user.is_staff:
         raise PermissionDenied
     form = None
     if 'send' in request.POST:
         form = self.MassMailForm(request.POST)
         if form.is_valid():
             subject = form.cleaned_data['subject']
             message = form.cleaned_data['message']
             count = 0
             plural = ''
             for volunteer in queryset:
                 if volunteer.user.email:
                     # Would have preferred to collect the mails in volunteer_mails list,
                     # then send one mail outside this loop, but we don't want volunteers
                     # to see each other's email addresses for privacy reasons, which means
                     # BCC, which means it will get sent out as separate mails anyway.
                     send_mass_mail(((subject, message, settings.DEFAULT_FROM_EMAIL, [volunteer.user.email]),), fail_silently=False)
                     count += 1
             if count > 1:
                 plural = 's'
             self.message_user(request, 'Mail with subject "{}" sent to  {} volunteer{}.'.format(subject, count, plural))
             return HttpResponseRedirect(request.get_full_path())
     if not form:
         form = self.MassMailForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
         return render(request, 'admin/massmail.html', {'volunteers': queryset,
                                                          'massmail_form': form,
                                                         })
Ejemplo n.º 6
0
    def send_mass_mail(self, request, queryset):
        opts = self.model._meta
        app_label = opts.app_label

        form = MassMailForm()
        if request.POST.get('post'):
            form = MassMailForm(request.POST)
            if form.is_valid():
                data = []
                recipients = [user.email for user in queryset if user.email]
                for recipient in recipients:
                    data.append((form.cleaned_data['subject'], form.cleaned_data['text'],
                        None, (recipient,)))
                mail.send_mass_mail(data)
                messages.success(request, _('Mails sent successfully.'))
                return # Let django handle redirections.
        context = {
            'title': _('Send mass mail'),
            'queryset': queryset,
            'opts': opts,
            'app_label': app_label,
            'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
            'form': form,
        }
        return TemplateResponse(request, 'rcal/send_mass_mail.html', context,
            current_app=self.admin_site.name)
Ejemplo n.º 7
0
    def test_connection_arg(self):
        """Test connection argument to send_mail(), et. al."""
        mail.outbox = []

        # Send using non-default connection
        connection = mail.get_connection("regressiontests.mail.custombackend.EmailBackend")
        send_mail("Subject", "Content", "*****@*****.**", ["*****@*****.**"], connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 1)
        self.assertEqual(connection.test_outbox[0].subject, "Subject")

        connection = mail.get_connection("regressiontests.mail.custombackend.EmailBackend")
        send_mass_mail(
            [
                ("Subject1", "Content1", "*****@*****.**", ["*****@*****.**"]),
                ("Subject2", "Content2", "*****@*****.**", ["*****@*****.**"]),
            ],
            connection=connection,
        )
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 2)
        self.assertEqual(connection.test_outbox[0].subject, "Subject1")
        self.assertEqual(connection.test_outbox[1].subject, "Subject2")

        connection = mail.get_connection("regressiontests.mail.custombackend.EmailBackend")
        mail_admins("Admin message", "Content", connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 1)
        self.assertEqual(connection.test_outbox[0].subject, "[Django] Admin message")

        connection = mail.get_connection("regressiontests.mail.custombackend.EmailBackend")
        mail_managers("Manager message", "Content", connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 1)
        self.assertEqual(connection.test_outbox[0].subject, "[Django] Manager message")
Ejemplo n.º 8
0
    def test_chunking(self):
        """
        Given 11 messages and a chunk size of 4, the backend should queue
        11/4 = 3 jobs (2 jobs with 4 messages and 1 job with 3 messages).
        """
        N = 11
        chunksize = 4

        with override_settings(CELERY_EMAIL_CHUNK_SIZE=4):
            mail.send_mass_mail([
                ("subject", "body", "*****@*****.**", ["*****@*****.**"])
                for _ in range(N)
            ])

            num_chunks = 3  # floor(11.0 / 4.0)
            self.assertEqual(len(self._delay_calls), num_chunks)

            full_tasks = self._delay_calls[:-1]
            last_task = self._delay_calls[-1]

            for args, kwargs in full_tasks:
                self.assertEqual(len(args[0]), chunksize)

            args, kwargs = last_task
            self.assertEqual(len(args[0]), N % chunksize)
Ejemplo n.º 9
0
def send_via_mail_to(request):
    """
        send email to list of freinds
    :param request:
        in the square represented by :
        west < longitude < east
        north < latitude < south
    """
    idAlert = int(request.POST['id'])
    emails = request.POST['list']
    text = request.POST['text']
    listMails = emails.rstrip('#').split('#')
    alert = Alert.objects.get(id=idAlert)
    # email
    path = reverse("public_show_alert", args=(idAlert,))
    subject = "BloodOn team team,"
    message = ''
    if len(text):
        message += '%s \n,' % text
    message += 'This message has been sent from <href ="http://%s">BloodOn Inc</href>, ' \
               'Because Some one need blood , the %s, ' \
               'at %s \n ' % (settings.SITE_PATH, alert.date_for, alert.organization.name)
    message += '\n for more detail please refer to : <href ="http://%s%s">BloodOn' \
               'Inc</href> \n' % (settings.SITE_PATH,  path)
    messageMail = (subject, message, settings.DEFAULT_FROM_EMAIL, listMails)
    send_mass_mail((messageMail,), fail_silently=False)
    return bloodon_renderAsJson(request, {'success' : True})
    def send_emails(self, recipients):
        """Send the emails using the templates and contexts requested."""
        email_subject = self.options['subject']
        email_sender = self.options['sender']
        txt_template = loader.get_template(self.options['template'])
        context = ast.literal_eval(self.options['context'])
        email_txt = txt_template.render(context)

        emails_sent_count = 0
        messages = []
        for recipient in recipients:
            messages.append((
                email_subject,
                email_txt,
                email_sender,
                [recipient],
            ))
            emails_sent_count += 1

        if not self.options['simulate']:
            send_mass_mail(messages, fail_silently=False)
            tally_stat('pr.emails.sent', inc=emails_sent_count)
            logger.info("Sent %s pr emails." % emails_sent_count)
        else:
            sys.stdout.write('Simulation mode. Imagine that we just sent %s '
                             'emails!\n' % emails_sent_count)
Ejemplo n.º 11
0
    def send_emails(self, uids, feedback_address):
        messages = []
        addresses = []
        data = self.cleaned_data
        for sbj, body, user in self.preview(*uids):
            messages.append((sbj, body, data['from_'], [user.email]))
            addresses.append('"%s %s" - %s' % (user.first_name, user.last_name, user.email))
        mail.send_mass_mail(messages)

        # feedback mail
        ctx = dict(data)
        ctx['addresses'] = '\n'.join(addresses)
        mail.send_mail(
            '[%s] feedback mass mailing (admin stats)' % settings.CONFERENCE,
            '''
message sent
-------------------------------
FROM: %(from_)s
SUBJECT: %(subject)s
BODY:
%(body)s
-------------------------------
sent to:
%(addresses)s
            ''' % ctx,
            dsettings.DEFAULT_FROM_EMAIL,
            recipient_list=[feedback_address],
        )
        return len(messages)
Ejemplo n.º 12
0
def index(request):
    if request.method == "POST":
        # Recupera os dados do POST e Cria um objeto de Formulário do tipo PessoaForm
        form = PessoaForm(request.POST)
        # Valida os dados do Formulario
        if form.is_valid():
            '''É melhor acessar form.cleaned_data. Estes dados não serão somente válidos,
                mas estarão convertidos em tipos relevantes do Python'''
            # Recupera cada valor do Dicionario
            vnome = form.cleaned_data['nome']
            vemail = form.cleaned_data['email']
            vmensagem = form.cleaned_data['mensagem']
            # Metodo para salvar no banco de dados
            form.save()
            # Cria a mensagem para o administrador(CEO)
            msg_adm = ('Mensagem do Cliente', 'Nome: %s \nE-mail: %s \nMensagem: %s ' % (vnome, vemail, vmensagem), '*****@*****.**', ['*****@*****.**'])
            # Cria a mensagem para o Cliente
            msg_cliente = ('Code - WEB Solutions', 'Agradecemos seu Contato e interesse na Code, dentro de 24h entraremos em contato.', '*****@*****.**', ['%s' % (vemail)])
            # Abre apenas uma conexão com o servidor de email e evia as duas mensagens
            try:
                send_mass_mail((msg_adm, msg_cliente), fail_silently=False)
            except:
                raise Http404

            # Redireciona para a Index
            messages.success(request, '%s, mensagem enviada com sucesso !' % vnome.title())
            return render(request, 'index.html')
        else:
            messages.success(request, 'Ops! O formulário foi preenchido incorretamente')
            return render(request, 'index.html')
    else:
        # Se for GET, istancia o Formulário
        form = PessoaForm()
        # Retorna o Formulario renderizado para o Template
        return render_to_response('index.html', {'form': form})
Ejemplo n.º 13
0
    def do_handle(self, *args, **options):

        self.stdout.write('Started.\n')
        logger.info("Start")

        meta_diff = datetime.datetime.now() - datetime.timedelta(days=getattr(settings, 'MESSAGE_DAYS_AGE',1))
        
        t_start = time.time() 
        
        mailing = []
        
        for user in User.objects.filter(pm_inbox__unread=True, pm_inbox__notified__isnull=True, pm_inbox__message__created__lt=meta_diff).distinct():
            messages = user.pm_inbox.filter(unread=True, notified__isnull=True, message__created__lt=meta_diff)
            count = messages.count()
            logger.debug("There are %s messages for %s" % (count, user))
            set_user_language(user)
            subject = ungettext('You have %(count)d unread message', 'You have %(count)d unread messages', count) % {
                'count': count,
            }
            message = render_to_string('djangopm/mail/unread_messages.mail', {'message_count': count,
                                                                        'user': user,
                                                                        'messages':  messages.all()})
            mailing.append((subject, message, None, [ user.email ]))
            messages.update(notified=datetime.datetime.now())
       
        if len(mailing)>0:
            logger.debug("Notify %d users" % len(mailing))
            send_mass_mail(mailing, True)
        logger.info("End")
        
        self.stdout.write('Completed in %d seconds. Notified %s.\n' % (int(time.time() - t_start), len(mailing)))
        
        return "Notify %d users" % len(mailing)
Ejemplo n.º 14
0
    def send_email(self):
        recipients = ContactRecipient.objects.filter(
            active=True
        ).values_list('email', flat=True)
        template = get_template('email/contact.html')

        if len(recipients) == 0:
            return

        context = dict(
            contact=self
        )
        message = template.render(context)

        try:
            send_mass_mail((
                (
                    'A new contact request from %s' % self.name,
                    message,
                    '*****@*****.**',
                    list(recipients)
                ),
            ))
        except:
            print 'Error sending email'
        else:
            self.date_sent = datetime.datetime.now()
            self.save()
Ejemplo n.º 15
0
def send_prediction_reminder_emails(predictions, users):
    if not predictions:
        return
    mails = []
    subject = u"[Big Brother] Today's Predictions"
    sender = u'*****@*****.**'
    for user in users:
        if not user.email:
            continue
        message = [u'The following predictions are due today on '
                   'http://bigbrother.striemer.ca:', u'']
        for prediction in predictions:
            message.append(u'* {name}'.format(name=prediction))
            choices = prediction.user_choices(user)
            for i in xrange(prediction.number_of_choices):
                if i < len(choices):
                    message.append(u'    {i}. {choice}'.format(
                                   choice=choices[i], i=i + 1))
                else:
                    message.append(
                        u'    {i}. You have not made a prediction'.format(
                            i=i + 1))
            message.append(u'')
        mails.append((subject, u'\n'.join(message), sender, [user.email]))
    send_mass_mail(mails)
Ejemplo n.º 16
0
    def handle(self, *args, **options):
        global log_file
        (user_file, message_base, logfilename, ratestr) = args

        users = [u.strip() for u in open(user_file).readlines()]

        message = middleware.lookup['main'].get_template('emails/' + message_base + "_body.txt").render()
        subject = middleware.lookup['main'].get_template('emails/' + message_base + "_subject.txt").render().strip()
        rate = int(ratestr)

        self.log_file = open(logfilename, "a+", buffering=0)

        i = 0
        for users in chunks(users, rate):
            emails = [(subject, message, settings.DEFAULT_FROM_EMAIL, [u]) for u in users]
            self.hard_log(" ".join(users))
            send_mass_mail(emails, fail_silently=False)
            time.sleep(1)
            print datetime.datetime.utcnow().isoformat(), i
            i = i + len(users)
            # Emergency interruptor
            if os.path.exists("/tmp/stopemails.txt"):
                self.log_file.close()
                sys.exit(-1)
        self.log_file.close()
Ejemplo n.º 17
0
def send_invitation(modeladmin, request, queryset):
    messages_to_send = []

    for invitation in queryset:
        emails = []
        guests = invitation.weddingguest_set.all()

        # activating invitation language
        activate(invitation.invitation_language)

        # lazy translating
        subject = _(u"Jūs pakviesti! Kur? Žiūrėkite į laiško vidų.")
        body_message = _(u"Berniukas sutiko mergaitę. Tiesa, prieš 10 metų. Likusią istorijos\ndalį sužinosite prisijungę prie mūsų šventės.\n\nJūsų kodas: %(code)s\n\nApsilankykite svetainėje: http://rsvp.gang.lt sužinosite daugiau. Iki.")

        for g in guests:
            if g.email != None and g.email.strip() != '':
                emails.append(str(g.email))

        if len(emails) > 0:
            messages.info(request, "Successfully sent emails to: %s" % ','.join(emails))
            messages_to_send.append((subject, body_message % {'code': invitation.invite_code},
                '*****@*****.**',
                emails))

            invitation.email_sent = True
            invitation.email_sent_at = datetime.now()
            invitation.save()

        else:
            messages.error(request, "Invitation %s has no emails assigned" % invitation)

    if len(messages_to_send) > 0:
        send_mass_mail(messages_to_send, fail_silently=False)
Ejemplo n.º 18
0
def send_booking_receipt(booking_id, language_code):
    """
    Send mails on booking confirmed
    """
    translation.activate(language_code)
    booking = Booking.objects.get(pk=booking_id)

    account = booking.event.account
    sender = account.from_address or 'noreply@%s' % Site.objects.get_current().domain

    try:
        send_mass_mail(
            ((render_to_string(
                'signupbox/mails/register_email_subject.txt' if index else 'signupbox/mails/register_email_subject_registrant.txt',
                context_instance=Context({'event': booking.event, 'booking': booking, 'attendee': attendee}, autoescape=False)
            ), render_to_string(
                'signupbox/mails/register_email.txt' if index else 'signupbox/mails/register_email_registrant.txt',
                context_instance=Context({'event': booking.event, 'booking': booking, 'attendee': attendee}, autoescape=False)
            ), sender,
            [attendee.email])
                for index, attendee in enumerate(booking.attendees.order_by('id')) if attendee.email
            )
        )
    except SMTPException, exc:
        process_booking.retry(exc=exc)
Ejemplo n.º 19
0
    def handle_noargs(self, **options):
        time_interval = datetime.timedelta(minutes=1)
        timestamp = timezone.now().replace(second=0, microsecond=0)
        # get recently closed polls
        recently_closed_poll_list = Poll.objects.filter(
            closing_date__lt = timestamp
        ).filter(
            closing_date__gte = timestamp - time_interval
        )

        for poll in recently_closed_poll_list:
            #self.stdout.write('Poll: '+str(poll.pk), ending = '')
            # TODO compute the winner
            # if the poll contains user : send notify them
            participant_list = list(poll.participant.all())
            email_list = ()
            for participant in participant_list:
                message = ()
                if participant.email != "*****@*****.**":
                    # email used for all public poll
                    self.stdout.write('Voter: ' +participant.email, ending = '')
                    message_data = {
                        'admin': poll.admin,
                        'voter_uuid': participant.uuid if poll.private else 'public',
                        'poll': poll,
                        'domain': 'pnyx.dss.in.tum.de',
                        'protocol': 'https',
                    }
                    logger.debug("Voter " + participant.email + " notified about the end of the poll " + str(poll.pk))

                    message += (('Your Pnyx poll has been closed, please check the final results',
                                 render_to_string('polls/poll_closed_email.html', message_data),
                                 '*****@*****.**',
                                 [participant.email]),)
            send_mass_mail(message, fail_silently = False)
Ejemplo n.º 20
0
	def sendMail(self,request):
		# Inicializar variables de correo
		subject = 'Últimas noticias de esta semana'
		message = ''
		messageList = ()

		# Obtener últimas noticias 
		categories = Categories.objects.all()
		for category in categories:
			message = '\n'+category.name+': \n'
			for source in category.sources.all():
				feed_items = feedparser.parse(source.rss_url)
				try:
					for i in range(0,3):
						message +=  feed_items['entries'][i].title + ' - ' + feed_items['entries'][i].link + '\n'
				except Exception as e:
					e
			category.message = message
		# Obtener usuarios suscritos y asignar las categorías correspondientes a su correo
		userProfiles = UserProfile.objects.all()
		for userProfile in userProfiles:
			if userProfile.mailFlag:
				message = ''
				user = User.objects.get(id = userProfile.user.id)
				for category in categories:
					if category.sources:
						message += category.message
				mail = (subject,message,'*****@*****.**',[user.email])
				messageList += mail
		send_mass_mail((messageList,),fail_silently=False)
		return Response(status=201)
Ejemplo n.º 21
0
def send_fillform_mail(modeladmin, request, queryset):
    """Send fillform informations to the user"""
    if request.POST.get('post'):
        register_view_url = request.build_absolute_uri(reverse('staff:registration'))

        mails = tuple(__get_fillform_email(register_view_url, p) for p in queryset)
        send_mass_mail(mails)
        count = len(mails)

        data = {'count': count,
                'person': str(queryset[0]),}

        admin_msg = ungettext(
            'Die Fillform E-Mail wurde an {person} verschickt.',
            'Die Fillform E-Mails wurden an {count} Personen verschickt.',
            count).format(**data)

        modeladmin.message_user(request, admin_msg, messages.SUCCESS)
    else:
        context = {
            'queryset': queryset,
            'opts' : modeladmin.opts,
            'title': _("Fillform E-Mail verschicken"),
            'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        }
        template = loader.get_template("staff/admin/fillform_email_confirm.html")

        return TemplateResponse(request, template, context)
Ejemplo n.º 22
0
def drop_ride(request, ride_id):
    """
    This function drops a user from a ride if they are part of it. Otherwise, it
    does nothing and reports an error.
    """
    context_instance = RequestContext(request)
    user = context_instance['user']
    query = Q(ride__id=ride_id) &\
        Q(user__id=user.id)
    sr = SearchRequest.objects.filter(query)
    if sr:
        sr = sr[0]
        ride = sr.ride
        		
        sr.delete()
        messages.add_message(request, messages.SUCCESS,
                             "Success! You were removed from the ride.")
        #Send e-mail notification to other riders
        subject = '%s %s has left your ride' % (user.first_name, user.last_name)
        body = 'Sorry, but %s has left a ride you are a part of at CabFriendly.com.  Go to http://cabfriendly.com/rides/%d/ to view updated details and coordinate the ride.' % (user.first_name, ride.id)
        emails = []
        ride.filled_out()
        for rider in ride.riders:
            if rider.id != user.id:
                emails.append((subject, body, OUR_EMAIL, [rider.email]))
        send_mass_mail(emails, fail_silently=False)
    else:
        messages.add_message(request, messages.WARNING,
                             "You actually weren't part of ride %s to begin with :)"
                             % (ride_id))
    return redirect('/')
Ejemplo n.º 23
0
def send_alert(request):
    try: 
        contacts = Contact.objects.filter(user=request.user)

        if not contacts:
            return render_to_response('contacts/alert-status.html', {'status_msg': 'There are no emergency contacts available. Please add your emergency contacts.'}, RequestContext(request))
        else:
            try:
                location = request.POST.get('location', '')
                user = UserProfile.objects.get(user=request.user)
                from_email = request.user.email
                
                msg_list = _build_message_list(user, contacts, location, from_email)

                if len(msg_list) > 0:
                    datatuple = tuple(msg_list)
                    # send alert messages
                    send_mass_mail(datatuple, fail_silently=True,
                                    auth_user=os.environ.get('ERGO_ALERT_AUTH_USER', ERGO_ALERT_AUTH_USER),
                                    auth_password=os.environ.get('ERGO_ALERT_AUTH_PASSWORD', ERGO_ALERT_AUTH_PASSWORD))
                    
                else:
                    return render_to_response('contacts/alert-status.html', {'status_msg': 'Emergency contact alert options have not been specified. Please edit your emergency contacts.'}, RequestContext(request))

                # return success status
                return render_to_response('contacts/alert-status.html', {'status_msg': 'Emergency contacts have been successfully notified.'}, RequestContext(request))
                    
            except UserProfile.DoesNotExist:
                # return missing profile
                return render_to_response('contacts/alert-status.html', {'status_msg': 'ERROR: Missing user profile.'}, RequestContext(request))

    except:
        return render_to_response('contacts/alert-status.html', {'status_msg': 'Error encountered while alerting emergency contacts. Please try again.'}, RequestContext(request))
Ejemplo n.º 24
0
 def mass_mail_volunteer(self, request, queryset):
     if not request.user.is_staff:
         raise PermissionDenied
     form = None
     if 'send' in request.POST:
         form = self.MassMailForm(request.POST)
         if form.is_valid():
             subject = form.cleaned_data['subject']
             message = form.cleaned_data['message']
             count = 0
             plural = ''
             volunteer_mails = []
             for volunteer in queryset:
                 # TODO: actually send the mail
                 if volunteer.user.email:
                     volunteer_mails.append(volunteer.user.email)
                     count += 1
             send_mass_mail(((subject, message, settings.DEFAULT_FROM_EMAIL, volunteer_mails),), fail_silently=False)
             if count > 1:
                 plural = 's'
             self.message_user(request, 'Mail with subject "%s" sent to  %d volunteer%s.' % (subject, count, plural))
             return HttpResponseRedirect(request.get_full_path())
     if not form:
         form = self.MassMailForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
         return render(request, 'admin/massmail.html', {'volunteers': queryset,
                                                          'massmail_form': form,
                                                         })
Ejemplo n.º 25
0
 def save(self):
     name = self.cleaned_data['name']
     email = self.cleaned_data['email']
     message = self.cleaned_data['message']
     subject = 'IAS Individual Contact Form'
     messages = []
     messages.append((
         subject,
         render_to_string(
             'crm/contact/contact_form.txt',
             self.cleaned_data,
         ),
         settings.DEFAULT_FROM_EMAIL,
         self.recipients,
     ))
     messages.append((
         subject,
         render_to_string(
             'crm/contact/contact_form_confirmation.txt',
             self.cleaned_data,
         ),
         settings.DEFAULT_FROM_EMAIL,
         [email],
     ))
     send_mass_mail(messages, fail_silently=True)
Ejemplo n.º 26
0
def send_email(request):

    form = BulkEmailForm(request.POST or None)
    if request.method == 'POST':

        if form.is_valid():
            subject = form.cleaned_data['subject']
            body = form.cleaned_data['body']
            person_query = form.get_person_query()
            emails = _get_emails(person_query, subject, body)

            if 'preview' in request.POST:
                try:
                    preview = emails[0]
                except IndexError:
                    preview = None
            else:
                send_mass_mail(emails)
                messages.success(request, "Emails sent successfully")

                return HttpResponseRedirect(reverse('index'))

    return render(
        template_name='karaage/emails/send_email_form.html', context=locals(),
        request=request)
Ejemplo n.º 27
0
    def cancel(self, user, *args, **kwargs):
        new_kwargs = dict(kwargs)
        new_kwargs['silent'] = True
        new_kwargs['user'] = user
        new_kwargs['cancel_children'] = False
        did_cancel = []
        if kwargs.get('cancel_children', True):
            for child in self.booking_parts.all():
                if child.cancel.is_available():
                    did_cancel.append(child)
                    child.cancel(*args, **new_kwargs)

        if not kwargs.get('silent', False):
            interested_parties = [('Your booking #{} has been cancelled'.format(self.id), self.user.email)]
            from_email = '*****@*****.**'
            this_also = """
This also resulted in the cancellation of the parts:"""
            for things in did_cancel:
                this_also += "\n * {} (booked from {} to {})".format(things.lendable.name, things.start_date, things.end_date)
            if not did_cancel:
                this_also = ""
            message = """
Hello,

Your booking number #{} has been cancelled by {}.
{}

Regards,
The Media Booking System
""".format(self.id, user, this_also)

            datatuple = [(subject, message, from_email, [recipient]) for (subject, recipient) in interested_parties]

            mail.send_mass_mail(datatuple, fail_silently=True)
Ejemplo n.º 28
0
    def send_email(self):
        """Send email to selected athletes."""
        email_addresses = set(self.cleaned_data['additional_emails'])
        if self.cleaned_data['sent_to_all']:
            for athlete in Athlete.objects.exclude(active=False).exclude(email__isnull=True).exclude(email=''):
                email_addresses.update(athlete.email_addresses)
            for coach in User.objects.exclude(email__isnull=True).exclude(email=''):
                email_addresses.add(coach.email)
        else:
            for athlete in self.cleaned_data['athletes']:
                email_addresses.update(athlete.email_addresses)
            for team in self.cleaned_data['teams']:
                for athlete in team.athletes.exclude(active=False).exclude(email__isnull=True).exclude(email=''):
                    email_addresses.update(athlete.email_addresses)
            for coach in self.cleaned_data['coaches']:
                email_addresses.add(coach.email)

        if not email_addresses:
            raise Exception('No email selected')

        email_addresses.add('Spirit Cheer 07 <*****@*****.**>')

        for email in email_addresses:
            logger.info('Sending email to {}'.format(email))

        send_mass_mail((self.cleaned_data['subject'], self.cleaned_data['message'], 'Spirit Cheer 07 <*****@*****.**>', (email,)) for email in email_addresses)
Ejemplo n.º 29
0
def enviarMail(request):

	if request.method == 'POST':

		formulario = ContactoForm(request.POST)
		if formulario.is_valid():
			nombre = formulario.cleaned_data['nombre']
			correo = formulario.cleaned_data['correo']
			mensaje = formulario.cleaned_data['mensaje'] + "\n" + formulario.cleaned_data['correo'] + "\n" + formulario.cleaned_data['celular']

			""" direcciones de correo a enviar correo de contacto """
			datatuple = (
    		(nombre, mensaje, correo, ['*****@*****.**']),
    		(nombre, mensaje, correo, ['*****@*****.**']),
			)

			send_mass_mail(datatuple)

			return render(request, 'index.html')

	else:

		formulario = ContactoForm()

	return render(request, 'contacto.html', {'formulario': formulario})
Ejemplo n.º 30
0
Archivo: tests.py Proyecto: 6ft/django
    def test_connection_arg(self):
        """Test connection argument to send_mail(), et. al."""
        mail.outbox = []

        # Send using non-default connection
        connection = mail.get_connection('mail.custombackend.EmailBackend')
        send_mail('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 1)
        self.assertEqual(connection.test_outbox[0].subject, 'Subject')

        connection = mail.get_connection('mail.custombackend.EmailBackend')
        send_mass_mail([
            ('Subject1', 'Content1', '*****@*****.**', ['*****@*****.**']),
            ('Subject2', 'Content2', '*****@*****.**', ['*****@*****.**']),
        ], connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 2)
        self.assertEqual(connection.test_outbox[0].subject, 'Subject1')
        self.assertEqual(connection.test_outbox[1].subject, 'Subject2')

        connection = mail.get_connection('mail.custombackend.EmailBackend')
        mail_admins('Admin message', 'Content', connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 1)
        self.assertEqual(connection.test_outbox[0].subject, '[Django] Admin message')

        connection = mail.get_connection('mail.custombackend.EmailBackend')
        mail_managers('Manager message', 'Content', connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 1)
        self.assertEqual(connection.test_outbox[0].subject, '[Django] Manager message')
Ejemplo n.º 31
0
def send_many_text(data_tuple):
    """
    一次性发送多条消息: 自动添加前缀和主题签名
    datatuple:
    (
        (subject0, message0, sender, recipient),
        (subject1, message1, sender, recipient),
        (subject2, message2, sender, recipient),
    )
    """
    data_tuple = ((add_prefix(d[0]), d[1], d[2], d[3]) for d in data_tuple)
    send_mass_mail(data_tuple)
Ejemplo n.º 32
0
def send_server_update_notification():
    r = requests.get(GITHUB_API_URL + '/repos/' + GITHUB_USER + '/' + GITHUB_REPO + '/commits/' + GITHUB_BRANCH)
    data = r.json()
    sha = data['sha']
    author = data['commit']['author']['name']

    send_mail = False
    teerace_server_sha = cache.get('teerace_server_sha')
    if teerace_server_sha is None:
        date = datetime.strptime(data['commit']['author']['date'], '%Y-%m-%dT%H:%M:%SZ')
        now = timezone.now()
        if now - date < timedelta(days=1):  # only do this if the last commit is not older than one day to prevent spam mails
            send_mail = True
    else:
        if sha != teerace_server_sha:
            send_mail = True

    if send_mail:
        from race.models import Server
        cache.set('teerace_server_sha', sha, timeout=None)

        if not DEFAULT_FROM_MAIL:
            return

        # only notify people with servers online
        servers_online = Server.objects.filter(
            last_connection_at__gte=(datetime.now()-timedelta(minutes=10))
        )
        users = []
        for server in servers_online:
            users.append(server.maintained_by)

        if users:
            users = set(users)
            messages = [
                (
                    u'Teerace: New server available',
                    u'Hello {username}\r\n\r\nThere is a new version of the '
                    'teerace server available.\r\n\r\nThe latest commit with '
                    'the message "{commit_message}" was done by {commiter}.'
                    '\r\nPlease decide for yourself if it is necessary to '
                    'compile the new version. For more information visit {url}'
                    '\r\n\r\ncheers\r\nTeerace team'.format(username=user.username,
                        commit_message=data['commit']['message'],
                        commiter=author,
                        url=data['html_url']
                    ),
                    DEFAULT_FROM_MAIL,
                    [user.email]
                ) for user in users
            ]
            send_mass_mail(messages, fail_silently=not DEBUG)
Ejemplo n.º 33
0
def mail_members(request):
    if request.method == "POST":
        form = MailMembersForm(request.POST)
    else:
        form = MailMembersForm()

    if form.is_valid():
        members = form.get_members()

        subject = form.cleaned_data["subject"]
        message = form.cleaned_data["message"]
        sender = request.user.username + "@stacken.kth.se"

        recipients = form.cleaned_data["recipients"]
        if recipients:
            recipients = [("", [recipient])
                          for recipient in recipients.split(",")]
        else:
            recipients = [(f"{member.first_name} {member.last_name}",
                           [member.email, f"{member.username}@stacken.kth.se"])
                          for member in members]

        extra_to = form.cleaned_data["extra_to"]
        if not extra_to:
            extra_to = "*****@*****.**"
        recipients.append(("", [extra_to]))

        context = {
            "recipients": recipients,
            "form": form,
            "test": True,
            "exception": None,
        }

        if request.POST.get("do_it", "") == "true":
            context["test"] = False
            messages = [(subject, message, sender, email)
                        for (_, email) in recipients]
            try:
                send_mass_mail(messages, fail_silently=False)
            except:
                context["exception"] = sys.exc_info()

        return render(request, "mail_members_test.html", context)

    return render(
        request,
        "mail_members.html",
        {
            "form": form,
        },
    )
Ejemplo n.º 34
0
def send_notifications():
    emails_list = []
    email_from = 'ANS Support <*****@*****.**>'

    # Problems
    # Up
    up_problems = models.Problem.objects.filter(send_up_email=True)
    for problem in up_problems:
        # Check if there are any email addresses to send to
        addresses = problem.notification_addresses_list
        if len(addresses) > 0:
            # Send email
            email_to = addresses
            email_subject = "".join([
                "[AgileNMS] INFO: ",
                str(problem.check),
                " no longer has a problem '" + problem.name + "'"
            ])
            email_message = render_to_string(
                'monitoring/emails/problem_up.txt', {'problem': problem})
            emails_list.append(
                (email_subject, email_message, email_from, email_to))

        # Clear send_up_email flag
        problem.send_up_email = False
        problem.save()

    # Down
    down_problems = models.Problem.objects.filter(send_down_email=True)
    for problem in down_problems:
        # Check if there are any email addresses to send to
        addresses = problem.notification_addresses_list
        if len(addresses) > 0:
            # Send email
            email_to = addresses
            email_subject = "".join([
                "[AgileNMS] ERROR: ",
                str(problem.check), " has a problem '" + problem.name + "'"
            ])
            email_message = render_to_string(
                'monitoring/emails/problem_down.txt', {'problem': problem})
            emails_list.append(
                (email_subject, email_message, email_from, email_to))

        # Clear send_down_email flag
        problem.send_down_email = False
        problem.save()

    print tuple(emails_list)

    # Send emails
    send_mass_mail(tuple(emails_list))
Ejemplo n.º 35
0
def email(request):

	students = Student.objects.all()
	to_emails = []
	i = 0
	for stu in students:
		to_emails.append(stu.email)
	message1 = ('TA evaluations', 'Here is a link to fill out your evaluations: http://localhost:8000/login ', '*****@*****.**', to_emails)
	send_mass_mail((message1,), fail_silently=False)
	context = {

	}
	return render(request, "ta/email.html", context)
Ejemplo n.º 36
0
Archivo: views.py Proyecto: Jahsil/dj
def subscribe(request):
    sub = forms.Subscribe()
    if request.method == 'POST':
        sub = forms.Subscribe(request.POST)
        subject = 'Welcome to DataFlair'
        message = 'Hope you are enjoying your Django Tutorials'
        recepient = str(sub['Email'].value())
        send_mass_mail(datatuple=(subject, message, EMAIL_HOST_USER,
                                  recepient))

        return render(request, 'subscribe/success.html',
                      {'recepient': recepient})
    return render(request, 'subscribe/index.html', {'form': sub})
Ejemplo n.º 37
0
def send_many_mail(req):
    title = '阿里叫你回家'
    content1 = '恭喜你获得一瓶老干妈'
    email_from = settings.DEFAULT_FROM_EMAIL
    recieve1 = [

        '*****@*****.**',
    ]
    content2 = 'good!!!'
    msg1 = (title, content1, email_from, recieve1)
    msg2 = (title, content2, email_from, ['*****@*****.**'])
    send_mass_mail((msg1, msg2))
    return HttpResponse("ok")
Ejemplo n.º 38
0
def send_notifications(subscription_type, **kwargs):
    logger.debug("sending notification for {0}".format(subscription_type))
    context = kwargs or {}
    context.update({
        'domain': settings.SITE_DOMAIN,
        'env': settings.ENVIRONMENT
    })
    subscribers = Subscription.objects.filter(subscription_type=subscription_type)
    subject = render_to_string('subscriptions/email_subject.txt', context).strip()
    body = render_to_string('subscriptions/email_body.txt', context).strip()
    messages = [(subject, body, settings.DEFAULT_FROM_EMAIL,
                 [subscriber.user.email]) for subscriber in subscribers]
    send_mass_mail(messages, fail_silently=True)
Ejemplo n.º 39
0
def send_many_email(req):
    title = "恭喜你中了一等奖"
    msg = '特奖励澧县1日游'
    email_from = settings.DEFAULT_FROM_EMAIL
    reciever1 = [
        '*****@*****.**',
        '*****@*****.**'
    ]
    msg1 = (title, msg, email_from, reciever1)
    msg2 = (title, msg, email_from, ['*****@*****.**', '*****@*****.**'])

    send_mass_mail((msg1, msg2), fail_silently=True)
    return HttpResponse("ok")
Ejemplo n.º 40
0
def edit_handler(sender, **kwargs):
    if not kwargs['created'] and 'volunteers' not in kwargs['update_fields']:
        event = kwargs['instance']

        volunteer_emails = _get_volunteer_emails(event=event)
        subject = event.organization.name + " update their " + event.title + " event."
        message = "You are receiving this message because you are registered for this event and the organizer has " \
                  "updated some details about the event. \nPlease find a link to the updated event below.\n\n" \
                  "\nYour event: https://voluntyr.herokuapp.com/Event/" + str(event.id)

        emails = _make_emails(volunteer_emails, settings.DEFAULT_FROM_EMAIL,
                              subject, message)
        send_mass_mail(emails)
Ejemplo n.º 41
0
def send_actual_email(selected_users, subject, body):
    site = Site.objects.get(pk=settings.SITE_ID)
    subject_template = Template(subject)
    body_template = Template(body)
    datatuple = ()
    for user in selected_users:
        context = Context({'site': site, 'user': user})
        datatuple += ((subject_template.render(context),
                       body_template.render(context),
                       settings.DEFAULT_FROM_EMAIL, [user.email]), )

    print 'Sending mass mail'
    send_mass_mail(datatuple)
Ejemplo n.º 42
0
def contact(request):
    if request.method == 'POST':
        fname = request.POST.get('fname')
        lname = request.POST.get('lname')
        address = request.POST.get('address')
        subject = request.POST.get('subject')
        #send_mail(subject, fname, lname, ['*****@*****.**'], fail_silently=False)
        message1 = ('Subject here', fname, '*****@*****.**',
                    ['*****@*****.**'])
        message2 = ('Another Subject', lname, '*****@*****.**',
                    ['*****@*****.**'])
        send_mass_mail((message1, message2), fail_silently=False)
    return render(request, 'website/contact.html')
Ejemplo n.º 43
0
def notify_on_changes(event):
    participant_emails = list(event.participation_set.values_list(
        'user__email',
        flat=True
    ))
    subject = f'Update information on event {event.title}'
    message = f'{event.description}\n'
    message += f'{event.title} will be from {localtime(event.start_date)} to {localtime(event.end_date)}\n'
    message += f'Location: {event.location}\n'
    message += 'Regards,'
    datatuple = ((subject, message, settings.EMAIL_HOST_USER, [email])
                 for email in participant_emails)
    send_mass_mail(datatuple)
Ejemplo n.º 44
0
def send_bulk_mail(subject, body, recipients):
    """
    Sends an email with the given subject and body to every recipient in the
    set/list of recipients. The emails are send one-by-one (so that no
    addresses are "leaked", e.g. by putting all receivers in the "TO: " field).

    The sender email address is read from the settings.
    """

    message_tuples = [(subject, body, settings.DEFAULT_FROM_EMAIL, [r])
                      for r in recipients]

    send_mass_mail(message_tuples)
Ejemplo n.º 45
0
    def notify(self, subject, message):
        from django.core.mail import send_mass_mail
        from smtplib import SMTPException

        subs = [
            user.email for user in self.subscribers.all()
            if user.email is not None
        ]
        try:
            send_mass_mail(
                (subject, message, settings.ISSUES_MAIL_ADDRESS, subs))
        except SMTPException as e:
            print "Issue Notification: Couldn't send mail because", e
Ejemplo n.º 46
0
def send_many_email(req):
    title = "加油"
    content1 = "恭喜帅磊磊喜提高铁一辆"
    email_from = settings.DEFAULT_FROM_EMAIL
    reciever1 = ['*****@*****.**', '*****@*****.**']
    content2 = "皮一下,超好玩的"
    #邮件1&2
    msg1 = (title, content1, email_from, reciever1)
    msg2 = ("小哥哥", content2, email_from,
            ['*****@*****.**', '*****@*****.**'])
    #使用send_mass_mail
    send_mass_mail((msg1, msg2), fail_silently=True)
    return HttpResponse("ok 666")
Ejemplo n.º 47
0
def mail_send(request):
    # 发送一封邮件
    # send_mail(主题,   内容,    从哪发送(发送人账号),      接受人列表,       ...)  前四个必填
    # send_mail('邮箱主题', '这是内容<a href="http://127.0.0.1:8000/">返回</a>', '*****@*****.**', ['*****@*****.**'])

    # 发送多封邮件
    m1 = ('邮箱主题', '1', '*****@*****.**', ['*****@*****.**'])
    m2 = ('邮箱主题', '2', '*****@*****.**', ['*****@*****.**'])
    m3 = ('邮箱主题', '3', '*****@*****.**', ['*****@*****.**'])
    m4 = ('邮箱主题', '4', '*****@*****.**', ['*****@*****.**'])
    send_mass_mail((m1, m2, m3, m4))

    return HttpResponse('发送成功')
Ejemplo n.º 48
0
    def handle(self, *args, **options):
        emails = []
        subject = 'Przypomnienie ;)'
        date_loan =  datetime.date.today() - datetime.timedelta(days=options['days'])
        friend_who_have_loaned_books = LoanBook.objects.filter(date__lte=date_loan)

        for friend in friend_who_have_loaned_books:
            message = f"Cześć {friend.friend_name},\n\n" \
                f"mam nadzieję, że książka: {friend.book.title} Ci się podoba. " \
                f"Jak tylko skończysz czytać, proszę zwróć ją. Chcę jeszcze do niej kiedyś zajrzeć :)"
            emails.append((subject, message, settings.DEFAULT_FROM_EMAIL, [friend.friend_email]))
        send_mass_mail(emails)
        self.stdout.write(f'Sent {len(emails)} reminders.')
 def test_connection_sharing(self):
     """RequestsBackend reuses one requests session when sending multiple messages"""
     datatuple = (
         ('Subject 1', 'Body 1', '*****@*****.**', ['*****@*****.**']),
         ('Subject 2', 'Body 2', '*****@*****.**', ['*****@*****.**']),
     )
     mail.send_mass_mail(datatuple)
     self.assertEqual(self.mock_request.call_count, 2)
     session1 = self.mock_request.call_args_list[0][
         0]  # arg[0] (self) is session
     session2 = self.mock_request.call_args_list[1][0]
     self.assertEqual(session1, session2)
     self.assertEqual(self.mock_close.call_count, 1)
Ejemplo n.º 50
0
def request_contact(request, pk):
    apartment = get_object_or_404(Apartment, pk=pk)
    tenant = User.objects.get(email_address=request.user.email_address)
    tenant_email = request.user.email_address
    message_to_tenant = ('Request Received', 'Congratulations {}, one of our agents will contact shortly'.format(tenant.first_name), '*****@*****.**', ['{}'.format(tenant_email)])
    message_to_agent = ('Request for contact', '{0} is interested in {1}. His mobile number is {2}'.format(tenant.get_full_name(), apartment.title, tenant.profile.mobile_number), '*****@*****.**', ['*****@*****.**'])
    datatuple = (
        message_to_tenant,
        message_to_agent,
    )
    send_mass_mail(datatuple)
    messages.success(request, 'Congratulations, one of our agents will contact shortly')
    return redirect('apartments:detail', pk=apartment.pk)
Ejemplo n.º 51
0
 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_mass_mail(emails)
     self.stdout.write('Sent {} reminders'.format(len(emails)))
Ejemplo n.º 52
0
def on_save_articles(instance, created, **kwargs):
    if created:
        suivi, created = Suivis.objects.get_or_create(nom_suivi='articles')
        titre = "Permacat - nouvel article"
        message = " Un nouvel article a été créé " + \
                  "\n Vous pouvez y accéder en suivant ce lien : https://permacat.herokuapp.com" + instance.get_absolute_url() + \
                  "\n\n------------------------------------------------------------------------------" \
                  "\n vous recevez cet email, car vous avez choisi de suivre les articles sur le site http://www.Perma.Cat/forum/articles/"
        emails = [suiv.email for suiv in followers(suivi) if instance.auteur != suiv]
        try:
            send_mass_mail([(titre, message, "*****@*****.**", emails), ])
        except:
            pass
Ejemplo n.º 53
0
 def test_save_mass_mail_to_db(self):
     """
     Test that using send_mass_mail creates multiple Message objects in DB instead, when
     EMAIL_BACKEND is set.
     """
     self.assertEqual(Message.objects.count(), 0)
     with self.settings(EMAIL_BACKEND="mailer.backend.DbBackend"):
         message1 = ('Subject ☺', 'Body', '*****@*****.**',
                     ['*****@*****.**'])
         message2 = ('Another Subject ☺', 'Body', '*****@*****.**',
                     ['*****@*****.**'])
         mail.send_mass_mail((message1, message2))
         self.assertEqual(Message.objects.count(), 2)
Ejemplo n.º 54
0
def notify_comment_tagged_users(user_ids, comment_id):
    """
    Notify users about being tagged on comments.
    """
    comment = Comment.objects.get(id=comment_id)
    users = User.objects.filter(id__in=user_ids)
    subject = "You are tagged on a comment"
    text = "You are tagged on the following comment:\n\n{}".format(
        comment.text)
    from_email = "*****@*****.**"

    messages = [(subject, text, from_email, [x.email]) for x in users]
    mail.send_mass_mail(messages, fail_silently=False)
Ejemplo n.º 55
0
def review_submit(request):
    if request.method == "POST":
        r = Review()
        r.Name = request.POST.get("Name")
        r.Email = request.POST.get("Email")
        r.Review = request.POST.get("Review")
        
        try:
            image = request.FILES['attachment']
            print(image)
            r.photo = image
            r.save()
            try:
                message1 = ("New Review by "+r.Name, r.Name+" - "+r.Review+" email-id: "+r.Email,EMAIL_HOST_USER, ["*****@*****.**"])
                f= f'Hey Dear {r.Name},\nThanks for your review on my website. I will publish it soon.\nHave a good day:)'
                message2 = ("Thanks for Review", f,EMAIL_HOST_USER, [r.Email])
                send_mass_mail((message1, message2), fail_silently=False)
            except Exception as e:
                print('Email sending error: ',e)  
            try:
                msg = EmailMessage(
                    'New review image',
                    'this is the image',
                    'EMAIL_HOST_USER',
                    ['*****@*****.**'],
                    headers={'Message-ID': 'foo'},
                )
                msg.content_subtype = "html"
                if image:
                    print('extension',str(r.photo.name).split(".")[-1])
                    mime_image = MIMEImage(r.photo.read(),_subtype=str(r.photo.name).split(".")[-1])
                    mime_image.add_header('Content-ID', '<image>')
                    msg.attach(mime_image)
                    print('mime image',mime_image)
                msg.send()
            except:
                pass
        except Exception as e:
            print('image is not given',e)
            r.save()
            try:
                message1 = ("New Review by "+r.Name, r.Name+" - "+r.Review+" email-id: "+r.Email,EMAIL_HOST_USER, ["*****@*****.**"])
                f= f'Hey Dear {r.Name},\nThanks for your review on my website. I will publish it soon.\nYou can send your image to show on website on this email: [email protected]\nHave a good day:)'
                message2 = ("Thanks for Review", f,EMAIL_HOST_USER, [r.Email])
                send_mass_mail((message1, message2), fail_silently=False)
            except Exception as e:
                print('Email sending error: ',e)    
            
        return redirect('/')
    else:
        return redirect('/')
Ejemplo n.º 56
0
def add_announcement(request):
    if request.method == 'POST':
        form = AnnouncementForm(request.POST)
        if form.is_valid():
            obj = Announcement()
            obj.title = form.cleaned_data['title']
            obj.target = form.cleaned_data['target']
            obj.user = request.user
            obj.body = form.cleaned_data['body']
            obj.save()

            if 'send_emailBoolean' in request.POST:
                send_emailBoolean = request.POST['send_emailBoolean']
            else:
                send_emailBoolean = False
            if send_emailBoolean:

                truemessage = render_to_string(
                    'core/announcement_email.html', {
                        'user':
                        request.user.first_name + request.user.last_name,
                        'body': form.cleaned_data['body'],
                        'target': form.cleaned_data['target']
                    })
                message_list = []
                for user in User.objects.all():
                    if user.email != '':
                        message_list.append((obj.title, truemessage,
                                             settings.ANN_EMAIL, [user.email]))

                send_mass_mail(message_list,
                               fail_silently=True,
                               auth_user=settings.ANN_EMAIL)

                messages.success(
                    request,
                    "Announcement has been successfully posted and users have been notified via email."
                )
                return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

            else:
                messages.success(request,
                                 "Announcement has been successfully posted.")
                return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
        else:
            error_string = "Announcement was not successfully posted, because of the following errors:  "
            for field in form:
                for error in field.errors:
                    error_string += error + '  '
            messages.error(request, error_string)
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Ejemplo n.º 57
0
def contact(request):

    name = (request.POST.get('fname', ' '))
    email = (request.POST.get('eid', ' '))
    query = (request.POST.get('query', ' '))
    suggest = (request.POST.get('suggest', ' '))
    myth = (request.POST.get('myth', ' '))

    if email == " " and name == " " and query == " " and suggest == " " and myth == " ":
        email, name, query, suggest, myth = 0, 0, 0, 0, 0
    else:
        li = 'email: '+email + "\n"+"name: "+name+"\n"+"query: " + \
            query+"\n"+'suggestion: '+suggest+"\n"+"myth: "+myth
        text = name + ', thank you for showing your interest.Soon we will catch you.You can visit our instagram page fight against corona.This message is only for verification of your email id.Our team request you to stay at home and stay safe.'
        print(
            name,
            email,
            query,
            suggest,
            myth,
        )
        if len(name) >= 3 and name[0].isupper() == True and (
                query) == "" or len(query) >= 5 and (suggest) == "" or len(
                    suggest) >= 5 and myth == "" or len(myth) >= 5:
            print("hello")
            message1 = (
                'This data is coming from user end',
                li,
                settings.EMAIL_HOST_USER,
                [
                    '*****@*****.**', '*****@*****.**',
                    '*****@*****.**'
                ],
            )
            message2 = ('Check mail from covaidwarriors.com', text,
                        settings.EMAIL_HOST_USER, [email])

            send_mass_mail((message1, message2), fail_silently=False)

            print(message1, message2)
            messages.success(
                request,
                " BOOYAH! Your data has been submitted successfully.Soon we will contact you at your given email id."
            )
        else:
            messages.error(
                request,
                "Please fill the field correctly.Hover each field to see the format of a field."
            )

    return render(request, 'corona/contact.html')
Ejemplo n.º 58
0
def result_notification_send(request, status):
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])

    if not request.user.has_perm("reviews.can_manage"):
        return access_not_permitted(request)

    fields = ["submission_pks", "from_address", "subject", "body"]
    if not all([k in request.POST for k in fields]):
        return HttpResponseBadRequest()

    try:
        submission_pks = [int(pk) for pk in request.POST["submission_pks"].split(",")]
    except ValueError:
        return HttpResponseBadRequest()

    submissions = SubmissionBase.objects.filter(
        result__status=status,
    )
    submissions = submissions.filter(pk__in=submission_pks)
    submissions = submissions.select_related("result")
    submissions = submissions.select_subclasses()

    notification_template_pk = request.POST.get("notification_template", "")
    if notification_template_pk:
        notification_template = NotificationTemplate.objects.get(
            pk=notification_template_pk
        )
    else:
        notification_template = None

    emails = []

    for submission in submissions:
        rn = ResultNotification()
        rn.submission = submission
        rn.template = notification_template
        rn.to_address = submission.submitter.email
        rn.from_address = request.POST["from_address"]
        rn.subject = request.POST["subject"]
        rn.body = Template(request.POST["body"]).render(
            Context({
                "submission": submission.notification_email_context()
            })
        )
        rn.save()
        emails.append(rn.email_args)

    send_mass_mail(emails)

    return redirect("pinax_submissions:result_notification", status=status)
Ejemplo n.º 59
0
def task_send_email():
    """
    Sends email notifications about tasks deadlines every day
    """
    messages_list = []
    for task in Task.objects.all():
        if task.developer and task.status != 'Done':
            messages_list.append(
                ('Task deadline is coming!',
                 '{} days left until {} deadline!'.format(
                     task.due_date - datetime.datetime.today(), Task.title),
                 settings.EMAIL_HOST_USER, Task.developer.email))
    send_mass_mail(tuple(messages_list))
    logger.info("Sent email to ")
Ejemplo n.º 60
0
    def handle(self, *args, **options):

        letter_list = Letter.objects.filter(destination_time__lte=timezone.now(), 
                email_sent='not sent')
    
        email_list = []
        for letter in letter_list:
            email_list.append((letter.subject, 
                letter.message, 
                letter.user.email, 
                [letter.user.email]))
            letter.email_sent = 'sent'
            letter.save()
        send_mass_mail(email_list, fail_silently=False)