def evenement_envoi_email(self): """ Fonction de composition et d'envoi des Emails après l'activation d'un évènement """ logger.debug('Liste des emails des destinataires: %s' % self.liste_emails) #On récupère le nom, l'adresse, le cp et la ville du magasin magasin_nom = self.magasin.nom magasin_adresse = self.magasin.adresse magasin_cp = self.magasin.cp print type(magasin_cp) magasin_ville = self.magasin.ville locale.setlocale(locale.LC_ALL, '') jour = self.evenement.date_debut.strftime('%A %d %B') heure_debut = '%sH%s' % (self.evenement.date_debut.strftime('%H'), self.evenement.date_debut.strftime('%M')) heure_fin = '%sH%s' % (self.evenement.date_fin.strftime('%H'), self.evenement.date_fin.strftime('%M')) print self.evenement.date_debut print self.evenement.date_debut.strftime('%A %d %B %H %M') d = Context({'magasin_nom' : magasin_nom, 'magasin_adresse' : magasin_adresse, 'magasin_cp' : '%s' % magasin_cp, 'magasin_ville' : magasin_ville, 'jour' : jour, 'heure_debut' : heure_debut, 'heure_fin' : heure_fin, }) texte = get_template('emails/evenement.txt') texte_contenu = texte.render(d) send_mail('Nouvelle offre FLASH', texte_contenu, 'Alain <*****@*****.**>', self.emails_liste) print "Email envoyé"
def test_send_queued_message(self): """ Ensure that send_queued_message properly delivers email, regardless of whether connection is passed in. """ send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') send_queued_message(queued_message, self.connection) self.assertEqual(len(self.mail.outbox), 1) send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') send_queued_message(queued_message) self.assertEqual(len(self.mail.outbox), 2) send_html_mail('Subject', 'Body', '<p>HTML</p>', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') send_queued_message(queued_message, self.connection) self.assertEqual(len(self.mail.outbox), 3) send_html_mail('Subject', 'Body', '<p>HTML</p>', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') send_queued_message(queued_message) self.assertEqual(len(self.mail.outbox), 4)
def send_email_to_admins(user_name=None, content=None, sites=None): # instance = kwargs['instance'] from_address = settings.DEFAULT_EMAIL_FROM_ADDRESS website_name = settings.WEBSITE_NAME if content is None: email_ready = audience_registration_email elif user_name is None: email_ready = content_addition_email else: email_ready = request_widget_email try: subject = email_ready["subject"] recipients = settings.ADMINS for recipient in recipients: if content is None: body = email_ready["body"] % (recipient[0], user_name, website_name) elif user_name is None: body = email_ready["body"] % (recipient[0], content, website_name) else: body = email_ready["body"] % (recipient[0], user_name, content, sites, website_name) send_mail(subject, body, from_address, [recipient[1]]) except: return
def notify_admins(subject, body): """Emails the ``superusers``""" user_list = User.objects.filter(is_superuser=True) recipient_list = [user.email for user in user_list] if recipient_list: send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, recipient_list) return True return False
def test_queue_not_deleted_on_error(self): """ Queued message instance shouldn't be deleted when error is raised during sending """ send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') engine.send_queued_message(queued_message) self.assertEqual(QueuedMessage.objects.count(), 1)
def index(request): from django_mailer import send_mail subject = "fcuk mail" message_body = "this is sparta !!!" recipients = ['*****@*****.**'] send_mail(subject, message_body, settings.DEFAULT_FROM_EMAIL, recipients) return render(request, 'index.html', dict())
def test_send_priority_now(self): """ If send_mail is called with priority of "NOW", the message should get sent right away and the QueuedMessage instance deleted """ send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**'], priority=constants.PRIORITY_EMAIL_NOW) self.assertEqual(len(mail.outbox), 1) self.assertEqual(QueuedMessage.objects.count(), 0)
def test_log(self): """ All emails sent through django_mailer should be logged, even those having "now" priority """ send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') engine.send_queued_message(queued_message, self.connection) self.assertEqual(Log.objects.count(), 1) send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**'], priority=constants.PRIORITIES['now']) self.assertEqual(Log.objects.count(), 2)
def test_blacklist(self): """ Test that blacklist works properly """ Blacklist.objects.create(email='*****@*****.**') send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') send_queued_message(queued_message) self.assertEqual(len(self.mail.outbox), 0) # Explicitly passing in list of blacklisted addresses should also work send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') send_queued_message(queued_message, blacklist=['*****@*****.**']) self.assertEqual(len(self.mail.outbox), 0)
def send_email_to_content_owners(sender, **kwargs): instance = kwargs['instance'] website_url = instance.url from_address = settings.DEFAULT_EMAIL_FROM_ADDRESS website_name = settings.WEBSITE_NAME try: subject = website_registration_email["subject"] body = website_registration_email["body"] % (website_url, website_name) email_addresses = Company.objects.filter(user__profile__registered_for="website_owner").values_list('user__email') if not email_addresses: return recipients = [x[0] for x in Company.objects.filter(user__profile__registered_for="website_owner").values_list('user__email')] for recipient in recipients: send_mail(subject, body, from_address, [recipient]) except: return
def test_defer_on_errors_setting(self): """ Defer queued mail on user defined exception. """ old_errors = settings.DEFER_ON_ERRORS settings.DEFER_ON_ERRORS = (DeferOnError,) # If we see some other random errors email shouldn't be deferred old_backend = django_settings.EMAIL_BACKEND django_settings.EMAIL_BACKEND = \ 'django_mailer.tests.base.DeferOnErrorBackend' send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') engine.send_queued_message(queued_message) queued_message = QueuedMessage.objects.latest('id') self.assertNotEqual(queued_message.deferred, None) settings.DEFER_ON_ERRORS = old_errors
def test_send_mail(self): """ Test to make sure that send_mail creates the right ``Message`` instance """ subject = 'Subject' content = 'Body' from_address = '*****@*****.**' to_addresses = ['*****@*****.**', '*****@*****.**'] send_mail(subject, content, from_address, to_addresses) message = Message.objects.get(pk=1) self.assertEqual(message.subject, subject) self.assertEqual(message.message, content) self.assertEqual(message.from_address, from_address) self.assertEqual(message.to_address, to_addresses[0]) message = Message.objects.get(pk=2) self.assertEqual(message.subject, subject) self.assertEqual(message.message, content) self.assertEqual(message.from_address, from_address) self.assertEqual(message.to_address, to_addresses[1])
def test_message_deferred(self): """ When error returned requires manual intervention to fix, emails should be deferred. """ send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') self.assertEqual(queued_message.deferred, None) engine.send_queued_message(queued_message) queued_message = QueuedMessage.objects.latest('id') self.assertNotEqual(queued_message.deferred, None) # If we see some other random errors email shouldn't be deferred django_settings.EMAIL_BACKEND = \ 'django_mailer.tests.base.OtherErrorBackend' send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') engine.send_queued_message(queued_message) self.assertEqual(queued_message.deferred, None)
def send_email_to_content_owners(sender, **kwargs): instance = kwargs['instance'] website_url = instance.url from_address = settings.DEFAULT_EMAIL_FROM_ADDRESS website_name = settings.WEBSITE_NAME try: subject = website_registration_email["subject"] body = website_registration_email["body"] % (website_url, website_name) email_addresses = Company.objects.filter( user__profile__registered_for="website_owner").values_list( 'user__email') if not email_addresses: return recipients = [ x[0] for x in Company.objects.filter( user__profile__registered_for="website_owner").values_list( 'user__email') ] for recipient in recipients: send_mail(subject, body, from_address, [recipient]) except: return
def object_detail(request, entry, release, object_id): """Books a ``TimeSlot`` for the ``Entry``""" timeslot = unshorten_object(object_id) if not timeslot: raise Http404 # make sure it hasn't been booked start_date = datetime.utcnow() + timedelta(hours=24) if timeslot.is_booked or timeslot.start_date < start_date: # someone has locked in this timeslot message = _('Unfortunately his slot has become unavailable') messages.error(request, message) return HttpResponseRedirect( reverse('timeslot:object_list', args=[entry.id])) # asign the ``TimeSlot`` to the ``Submission`` timeslot.submission = entry timeslot.booking_date = datetime.utcnow() timeslot.is_booked = True timeslot.save() message = _('Your booking has been successful') messages.success(request, message) context = {'entry': entry, 'timeslot': timeslot} # Temporaly send the email through the instance # this will be moved to a queue if request.user.email and settings.BOOKING_SEND_EMAILS: email_template = lambda x: 'timeslot/email/confirmation_%s.txt' % x subject = jingo.render_to_string(request, email_template('subject'), context) # remove empty lines subject = subject.splitlines()[0] body = jingo.render_to_string(request, email_template('body'), context) profile = request.user.get_profile() recipient = '%s <%s>' % (profile.name, request.user.email) send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [ recipient, ], fail_silently=False) return HttpResponseRedirect(entry.get_absolute_url())
def test_sending_email_uses_opened_connection(self): """ Test that send_queued_message command uses the connection that gets passed in as an argument. Connection stored in self is an instance of locmem email backend. If we override the email backend with a dummy backend but passed in the previously opened connection from locmem backend, we should still get the proper result since send_queued_message uses the connection we passed in. """ django_settings.EMAIL_BACKEND = \ 'django.core.mail.backends.dummy.EmailBackend' # Outbox should be empty because send_queued_message uses dummy backend send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') engine.send_queued_message(queued_message) self.assertEqual(len(self.mail.outbox), 0) # Outbox should be populated because send_queued_message uses # the connection we passed in (locmem) send_mail('Subject', 'Body', '*****@*****.**', ['*****@*****.**']) queued_message = QueuedMessage.objects.latest('id') engine.send_queued_message(queued_message, self.connection) self.assertEqual(len(self.mail.outbox), 1)
def my_site(request): warrantys = Warranty.objects.all() repairs = Repair.objects.all() certificates = Certificate.objects.all() #feedback logic if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] sender = form.cleaned_data['sender'] message = form.cleaned_data['message'] copy = form.cleaned_data['copy'] recepients = ['*****@*****.**'] if copy: recepients.append(sender) try: send_mail(subject, message, sender, recepients) except BadHeaderError: return HttpResponse('Invalid header found') return HttpResponseRedirect('#contacts') else: form = ContactForm() return render( request, 'index.html', { 'repairs': repairs, 'warrantys': warrantys, 'certificates': certificates, 'form': form })
def object_detail(request, entry, release, object_id): """Books a ``TimeSlot`` for the ``Entry``""" timeslot = unshorten_object(object_id) if not timeslot: raise Http404 # make sure it hasn't been booked start_date = datetime.utcnow() + timedelta(hours=24) if timeslot.is_booked or timeslot.start_date < start_date: # someone has locked in this timeslot message = _('Unfortunately his slot has become unavailable') messages.error(request, message) return HttpResponseRedirect(reverse('timeslot:object_list', args=[entry.id])) # asign the ``TimeSlot`` to the ``Submission`` timeslot.submission = entry timeslot.booking_date = datetime.utcnow() timeslot.is_booked = True timeslot.save() message = _('Your booking has been successful') messages.success(request, message) context = {'entry': entry, 'timeslot': timeslot} # Temporaly send the email through the instance # this will be moved to a queue if request.user.email and settings.BOOKING_SEND_EMAILS: email_template = lambda x: 'timeslot/email/confirmation_%s.txt' % x subject = jingo.render_to_string(request, email_template('subject'), context) # remove empty lines subject = subject.splitlines()[0] body = jingo.render_to_string(request, email_template('body'), context) profile = request.user.get_profile() recipient = '%s <%s>' % (profile.name, request.user.email) send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [recipient, ], fail_silently=False) return HttpResponseRedirect(entry.get_absolute_url())
def send_reminder(submission_list, extra_context=None): """Emails the ``Submissions`` a reminder of the timeslot""" email_template = lambda x: 'timeslot/email/reminder/%s.txt' % x sent_emails = 0 for submission in submission_list: profile = submission.created_by if not profile.user.email: continue context = { 'submission': submission, 'profile': profile, 'site_url': settings.SITE_URL, } if extra_context: context.update(extra_context) context = Context(context) subject = render_to_string(email_template('subject'), context) subject = subject.splitlines()[0] body = render_to_string(email_template('body'), context) recipient = '%s <%s>' % (profile.name, profile.user.email) send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [recipient], fail_silently=False) sent_emails += 1 return sent_emails