def _send_add_email(email, canteen): try: protocol = "https" if settings.SECURE_SSL_REDIRECT else "http" domain = settings.HOSTNAME canteen_path = f"/modifier-ma-cantine/{canteen.url_slug}" context = { "canteen": canteen.name, "canteen_url": f"{protocol}://{domain}{canteen_path}", } send_mail( subject=f"Vous pouvez gérer la cantine « {canteen.name} »", template="auth/manager_add_notification", context=context, to=[email], ) except ConnectionRefusedError as e: logger.error( f"The manager add notification email could not be sent to {email} : Connection Refused. The manager has been added anyway." ) logger.exception(e) return except Exception as e: logger.error( f"The manager add notification email could not be sent to {email}" ) logger.exception(e) raise Exception( "Error occurred : the mail could not be sent.") from e
def _send_invitation_email(manager_invitation): try: context = { "canteen": manager_invitation.canteen.name, "protocol": "https" if settings.SECURE_SSL_REDIRECT else "http", "domain": settings.HOSTNAME, } send_mail( subject="Invitation à gérer une cantine sur ma cantine", template="auth/manager_invitation", context=context, to=[manager_invitation.email], ) except ConnectionRefusedError as e: logger.error( f"The manager invitation email could not be sent to {manager_invitation.email} : Connection Refused. The manager has been added anyway." ) logger.exception(e) return except Exception as e: logger.error( f"The manager invitation email could not be sent to {manager_invitation.email}" ) logger.exception(e) raise Exception( "Error occurred : the mail could not be sent.") from e
def save(self, *args, **kwargs): """ Overrides the save method to provide a default username and a random password to LCs which are emailed to the provided email address. """ create = self.id is None if create: self.username = u'lc_' + self.city.lower() # Give the user a randomly generated password password = generate_random_string() self.password = password # Compose the email to send to the LC context = { 'lc': self, 'password': password, } subject = render_to_string( 'registration/lc_register_email_subject.txt') subject = subject.strip() message = render_to_string( 'registration/lc_register_email_text.txt', context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email]) # Delegate upward to the parent classes super(LocalCommittee, self).save(*args, **kwargs)
def send(self): if self.status == Message.Status.SENT: logger.exception( f"Attempt to send an already sent message: {self.id}") raise Exception(f"Message already sent on {self.sent_date}") recipients = [ user.email for user in self.destination_canteen.managers.all() ] recipients.append(settings.DEFAULT_FROM_EMAIL) reply_to = [self.sender_email] context = { "canteen": self.destination_canteen.name, "from": self.sender_email, "name": self.sender_name or "Une personne", "message": self.body, } try: send_mail( subject=f"Un message pour {self.destination_canteen.name}", to=recipients, reply_to=reply_to, template="contact_canteen", context=context, ) self.status = Message.Status.SENT self.sent_date = now() self.save() except Exception as e: logger.error(f"Error sending message {self.id}") logger.error(e)
def post(self, request): try: file = request.data["file"] self._verify_file_size(file) email = request.data.get("email", request.user.email) context = { "from": email, "name": request.data.get("name", request.user.get_full_name()), "message": request.data.get("message", ""), } send_mail( subject="Fichier pour l'import de diagnostics massif", to=[settings.CONTACT_EMAIL], reply_to=[email], template="unusual_diagnostic_import_file", attachments=[(file.name, file.read(), file.content_type)], context=context, ) except ValidationError: logger.error( f"{request.user.id} tried to upload a file that is too large (over {settings.CSV_IMPORT_MAX_SIZE})" ) return HttpResponseBadRequest() except Exception as e: logger.error(f"User {request.user.id} encountered an error when trying to email a diagnostic import file") logger.exception(e) return HttpResponseServerError() return HttpResponse()
def post(self, request): email = request.data.get('email', None) user = utils.user_by_email(email=email) if not user: raise exceptions.ValidationError('Not exist email {}'.format( email )) # Send sms validation from common import utils as cutils from django.conf import settings token = jwt.encode({'user_id': user.pk}, user.password, algorithm='HS256').decode('utf-8') link = '{}/v1/reset-password/{}/{}/'.format( settings.URL_WEBSITE, user.id, token ) subject = 'Recuperar contraseña' cutils.send_mail( recipient=[user.email], subject=subject, template='email/recover-password.html', context={ 'display_name': user.display_name(), 'site': settings.APPNAME, 'link': link } ) return Response({'success': 'ok'}, status=status.HTTP_200_OK)
def skype_event_group_email(event_email_id): """ :param event_email_id: :return: """ event_email = EventEmail.objects.get(id=event_email_id) registered_user_list = Registration.objects.filter(event=event_email.event) for reg_user in registered_user_list: logger.info("\n\n group email for loop\n") to_email = [reg_user.attendee.email, ] subject = event_email.email_subject body_email = event_email.email_body send_mail(subject, body_email, to_email)
def resetear_contrasena(self): """Resetea la contreseña del miembro actual. Coloca como nueva contreseña la cedula del miembro.""" from common.utils import send_mail from django.template import loader from django.db import connection if self.usuario: self.usuario.set_password(self.cedula) protocol = 'https' if settings.SECURE_SSL_REDIRECT else 'http' context = {'nombre': self.nombre.upper(), 'dominio': connection.tenant.domain_url, 'protocolo': protocol} message = loader.render_to_string('miembros/emails/contrasena_reseteada.html', context=context) send_mail(_('Contraseña reseteada.'), message, [self.email])
def send_confirmation_email(self, new_email, user): token = tokens.default_token_generator.make_token(user) context = { "token": token, "uid": urlsafe_base64_encode(force_bytes(user.pk)), "protocol": "https" if settings.SECURE_SSL_REDIRECT else "http", "domain": settings.HOSTNAME, } send_mail( subject= "Confirmation de votre changement d'adresse email - ma cantine", template="auth/account_activate_email", context=context, to=[new_email], )
def perform_create(self, serializer): create = super().perform_create(serializer) data = serializer.validated_data send_mail( subject="📨 Nouveau message en attente de validation", template="pending_message", context={ "sender_email": data["sender_email"], "sender_name": data.get("sender_name") or "Pas renseigné", "canteen_name": data["destination_canteen"].name, "body": data["body"], }, to=[settings.CONTACT_EMAIL], ) return create
def send_approve_alert_email(self, lr): template = 'maitenance/email/alert_email.txt' subject = "Please handle my leave request" receiver = lr.employee.email import settings host = settings.LEAVESYSTEMHOST or '' from common.utils import send_mail send_mail(template = template, sender = self.email, receivers = [receiver], context = {'host': host, 'leave_request': lr, 'receiver': lr.employee.display_name, 'sender': self.display_name}, subject = subject, cc = [])
def email_SOP(self, file): name = self.cleaned_data['name'] from_email = self.cleaned_data['email'] msg = self.cleaned_data['msg'] review_type = self.cleaned_data['review_type'] department = self.cleaned_data['intended_department'] subject = "{0} submitted a SOP for review".format(name) body = """ Message: {0} Document Type: {1} Intended Department {2}""".format(msg, review_type, department) email_success = True email_success = send_mail(subject, body, from_email=from_email, attachment=file) if email_success: # confirmation mail to submitter subject = "We have received your document" send_mail_async(subject, SOP_RECEIVED.format(name), to_email=[ from_email, ]) return email_success
def email_SOP(self, file): name = self.cleaned_data['name'] from_email = self.cleaned_data['email'] msg = self.cleaned_data['msg'] subject = "{0} submitted a SOP for review".format(name) email_success = send_mail(subject, msg, from_email=from_email, attachmets=file) return email_success
def save_and_mail(self, event, user): skype_id = self.cleaned_data['skype_id'] email_success = False try: Registration.objects.create(attendee=user, event=event, skype_id=skype_id) except: reg_success = False else: reg_success = True if reg_success: to_email = ADMIN_EMAILS + [user.email, ] subject = "Your event registration is confirmed for the event {0}".format(event.title) body_email = """ Hi {0}, Your registration is confirmed for the event {1}. The event will be held on {2} Bangladesh time. The event duration is {3} hour/ hours. Our Skype ID is 'MSNB'. For any query please email at [email protected]. Please don't forget to receive video call from our Skype account at the mentioned time. Thanks, Support Team My Study Notebook """.format(user.first_name, event.title, event.start_time, event.duration) email_success = send_mail(subject, body_email, to_email) return reg_success, email_success
def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if change and "publication_status" in form.changed_data and obj.publication_status == "published": protocol = "https" if settings.SECURE else "http" canteenUrlComponent = urllib.parse.quote(f"{obj.id}--{obj.name}") context = { "canteen": obj.name, "canteenUrl": f"{protocol}://{settings.HOSTNAME}/nos-cantines/{canteenUrlComponent}", } contact_list = [user.email for user in obj.managers.all()] contact_list.append(settings.CONTACT_EMAIL) send_mail( subject=f"Votre cantine « {obj.name} » est publiée", template="canteen_published", context=context, to=contact_list, fail_silently=True, )
def send_email_to(groups): template = 'maitenance/email/alert_email_list.txt' subject = 'Leave Requests - Waiting for manager aproval' import settings host = settings.LEAVESYSTEMHOST or '' admins = Employee.objects.filter(is_administrative_staff=True)#, domain_id='prod\echen1') admin = admins and admins[0] or type('', (object,), {'display_name': 'Emily Chen', 'email': '*****@*****.**'}) log.Info('Send Alert Email:') for emp_info, reqs in groups.iteritems(): log.Info('Receiver -- ' + emp_info) approver_name, approver_email = emp_info.split('&') c = {'sender': admin.display_name, 'receiver': approver_name, 'reqs': reqs, 'host': host} # For test, add cc to Arthur Wu to confirm that email has been sended. send_mail(template, admin.email, [approver_email], c, subject, cc=['*****@*****.**'] + [a.email for a in admins])
def post(self, request, *args, **kwargs): try: email = request.data.get("email") validate_email(email) name = request.data.get("name") message = request.data.get("message") canteen_id = kwargs.get("pk") canteen = Canteen.objects.get(pk=canteen_id) canteen_path = f"/modifier-ma-cantine/{canteen.url_slug}" url = f"{'https' if settings.SECURE else 'http'}://{settings.HOSTNAME}{canteen_path}/gestionnaires" context = { "email": email, "name": name, "message": message, "url": url, "canteen": canteen.name, "siret": canteen.siret, } send_mail( subject= f"{name} voudrait rejoindre l'équipe de gestion de la cantine {canteen.name}", to=canteen.managers.values_list("email", flat=True), cc=[settings.CONTACT_EMAIL], reply_to=[ email, ], template="canteen_join_request", context=context, ) return JsonResponse({}, status=status.HTTP_200_OK) except ValidationError: return JsonResponse({"error": "Invalid email"}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: logger.error("Exception ocurred while sending email") logger.exception(e) return JsonResponse( {"error": "An error has ocurred"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, )
def send_reminder_email(event_id, is_feedback_email): """ :param event_id: :param is_feedback_email: :return: """ # Change and update the body_email make it more customized event = Event.objects.get(id=int(event_id)) registered_user_list = Registration.objects.filter(event=event) for reg_user in registered_user_list: to_email = [reg_user.attendee.email, ] if is_feedback_email: subject = SUBJECT_FEEDBACK body_email = BODY_FEEDBACK.format(reg_user.attendee.first_name, event.title) else: event_start_time = event.start_time.astimezone(BD_TZ).strftime(time_format) subject = SUBJECT_REMINDER.format(event.title) body_email = BODY_REMINDER.format(reg_user.attendee.first_name, event.title, event_start_time, event.duration) send_mail(subject, body_email, to_email)
def _login_and_send_activation_email(username, request): if not username: return redirect(reverse_lazy("app")) try: user = get_user_model().objects.get(username=username, email_confirmed=False) login(request, user) token = tokens.default_token_generator.make_token(user) context = { "token": token, "uid": urlsafe_base64_encode(force_bytes(user.pk)), "protocol": "https" if settings.SECURE_SSL_REDIRECT else "http", "domain": settings.HOSTNAME, } send_mail( subject="Confirmation de votre adresse email - ma cantine", template="auth/account_activate_email", context=context, to=[user.email], ) return redirect(reverse_lazy("app")) except Exception: raise Exception("Error occurred : the mail could not be sent.")
def post(self, request): try: email = request.data.get("from") validate_email(email) name = request.data.get("name") or "Un·e utilisateur·rice" message = request.data.get("message") context = { "from": email, "name": name, "message": message, } send_mail( subject=f"{name} n'a pas trouvé une cantine publiée", to=[ settings.CONTACT_EMAIL, ], reply_to=[ email, ], template="canteen_not_found", context=context, ) return JsonResponse({}, status=status.HTTP_200_OK) except ValidationError: return JsonResponse({"error": "Invalid email"}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: logger.error("Exception ocurred while sending email") logger.exception(e) return JsonResponse( {"error": "An error has ocurred"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, )
def email_SOP(self, file): name = self.cleaned_data['name'] from_email = self.cleaned_data['email'] msg = self.cleaned_data['msg'] review_type = self.cleaned_data['review_type'] department = self.cleaned_data['intended_department'] subject = "{0} submitted a SOP for review".format(name) body = """ Message: {0} Document Type: {1} Intended Department {2}""".format(msg, review_type, department) email_success = True email_success = send_mail( subject, body, from_email=from_email, attachment=file) if email_success: # confirmation mail to submitter subject = "We have received your document" send_mail_async( subject, SOP_RECEIVED.format(name), to_email=[from_email, ]) return email_success
def test_send_mail(self): response = send_mail( self.subject, self.body, self.to_email, self.from_email) logger.info("Mail has been send from test") self.assertTrue(response)
def STDownloadSerie(api_url, verify_cert, user, password, serie_id, user_email, serie, study, patient): # Donnera le résultat de l'opération success = False try: # Désactive les avertissements du module if not verify_cert: requests.packages.urllib3.disable_warnings() # Définit les en-têtes http headers = {} headers['Content-Type'] = 'application/json; charset=utf-8' headers['Accept'] = 'application/json' # Définit la session de connexion connection = requests.Session() connection.auth = (user, password) # Recherche de l'étude REST = '/studies' full_url = api_url + REST + '/' + serie_id + '/archive' data = connection.get(full_url, headers=headers, verify=verify_cert, stream=True) # Stockage du flux archive dans un fichier directory = params['files']['directory']['series'] filename = directory + '/' + serie_id + '.zip' link = params['files']['link']['series'] + '/' + serie_id + '.zip' with open(filename, 'wb') as fd: for chunk in data.iter_content(chunk_size=128): fd.write(chunk) # Envoi du mail avec le lien de téléchargement if user_email is not None: subject = '[' + params['app']['name'] + '] - ' + 'Download link' sender = params['mail']['sender'] recipients = [] recipients.append(user_email) # A trduire... body_md = _( 'mail serie download pitch %(link)s %(serie_description)s %(study_description)s %(patient)s' ) % { 'link': link, 'serie_description': serie['MainDicomTags']['SeriesDescription'], 'study_description': study['MainDicomTags']['StudyDescription'], 'patient': patient['MainDicomTags']['PatientName'] } send_mail(subject, sender, recipients, body_md) success = True except Exception as e: print('common/tasks.py/STDownloadSerie') print(str(e)) finally: return success
def test_send_mail(self): response = send_mail(self.subject, self.body, self.to_email, self.from_email) logger.info("Mail has been send from test") self.assertTrue(response)