def send(self): message = self.cleaned_data['message'] contacts = self.cleaned_data['contacts'] recipients = [recipient.hl_contact for recipient in contacts] api.send_sms(body=message, from_phone='Info', to=recipients) return recipients
def send_sms(request): try: api.send_sms(body='Kindly requesting you to carry my cargo', from_phone='+256776713008', to=['+256775430593']) state = "blah blah has received the notification on their phone." except: return "can't send message"
def send_sms(self, request=None): message = SMS_MESSAGE % {'code': self.code} to = str(self.phone_number) if callable(SILENT_CONFIRMATIONS_FILTER ) and SILENT_CONFIRMATIONS_FILTER(to) is True: logger.debug("Filtered phone confirmation SMS to:%s text:%s", to, message) return api.send_sms(body=message, from_phone=FROM_NUMBER, to=[to]) self._send_signal_and_log(confirmation_sms_sent, phone_number=self.phone_number)
def deliver_bulk(self, recipients, sender, notice_type, extra_context): """ Sending SMS using: https://github.com/stefanfoulis/django-sendsms/ """ print("Sending Bulk Sms... ") context = self.default_context() context.update({ "sender": sender, "notice": ugettext(notice_type.display), "current_site": context['current_site'].domain }) context.update(extra_context) try: messages = self.get_formatted_messages(("sms.txt", ), notice_type.label, context) except TemplateDoesNotExist: # We just ignore the backend if the template does not exist. pass else: body = messages["sms.txt"].strip().encode('utf-8') mobile_phones = [] for recipient in recipients: if context.get('mobile_phone') and len(recipients) == 1: # In case we need to override the default user phone number mobile_phones.append(context['mobile_phone']) else: if mobile_phone_path: mobile_phone = getattr(recipient, mobile_phone_path) else: userprofile = getattr(recipient, 'userprofile') mobile_phone = getattr(userprofile, 'mobile_phone') mobile_phones.append(mobile_phone) api.send_sms(body=body, from_phone=from_phone, to=mobile_phones) if use_notice_model: Notice = get_class_from_path( path='pinax.notifications_backends.models.Notice') # Based on http://stackoverflow.com/a/7390947 # This is mostly a log for sent notifications. for recipient in recipients: Notice.objects.create(recipient=recipient, message=body, notice_type=notice_type, sender=sender, medium='sms')
def test_should_properly_handle_errors(self): with self.settings( SENDSMS_BACKEND='sendsms.backends.ovhsms.OvhSmsBackend', OVH_API_ACCOUNT="myaccount", OVH_API_LOGIN="******", OVH_API_PASSWORD="******", OVH_API_FROM="mysender"): from sendsms.api import send_sms with self.assertRaisesRegex(RuntimeError, "Invalid smsAccount"): send_sms(body='I can hàz txt', from_phone=None, to=['+33632020000']) res = send_sms(body='I can hàz txt', from_phone=None, to=['+33632020000'], fail_silently=True) self.assertEqual(res, [])
def send_sms(self, request=None): message = render_to_string(template_name=SMS_TEMPLATE, context={"code": self.code}, request=request) to=str(self.phone_number) if callable(SILENT_CONFIRMATIONS_FILTER) and \ SILENT_CONFIRMATIONS_FILTER(to) is True: log.debug("Filtered phone confirmation SMS to:%s text:%s", to, message) return api.send_sms(body=message, from_phone=FROM_NUMBER, to=[to])
def post(self, request): message = request.data.get('message') if api.send_sms(body=message, from_phone='+XXXXXXXXXXXXX', to=['+XXXXXXXXXXXXXXXXX']): messages.success(request,"SMS sent successfully") else: messages.error(request, "Not sent successfully!!! ") return render(request, 'sms.html')
def send_sms(message, to, from_=None, fail_silently=False): from_ = from_ or settings.SMS_DEFAULT_FROM_PHONE if isinstance(to, str): to = [to] return api.send_sms(body=message, from_phone=from_, to=to, fail_silently=fail_silently)
def send(self, message, subject=None): from sendsms import api from_ = settings.SMS_DEFAULT_FROM_PHONE recipients = self.kwargs['recipients'] if isinstance(recipients, str): recipients = [recipients] else: recipients = list(recipients) return api.send_sms(body=message, from_phone=from_, to=recipients, fail_silently=False)
def order(request): multiple_form = MultiplePizzaForm() if request.method == 'POST': created_pizza_pk = None filled_form = PizzaForm(request.POST) if filled_form.is_valid(): created_pizza = filled_form.save() created_pizza_pk = created_pizza.id note = 'Thanks for ordering! Your %s %s and %s pizza is on its way!' % ( filled_form.cleaned_data['size'], filled_form.cleaned_data['Main_Course'], filled_form.cleaned_data['Side_Dish'], ) filled_form = PizzaForm() SENDSMS_BACKEND = 'myapp.mysmsbackend.SmsBackend' api.send_sms(body='I can text', from_phone='+12263406180', to=['+12263406180']) message = SmsMessage(body='lolcats make me hungry', from_phone='+12263406180', to=['+12263406180']) message.send() else: note = 'Order was not created, please try again' new_form = PizzaForm() return render( request, 'pizza/order.html', { 'multiple_form': multiple_form, 'pizzaform': filled_form, 'note': note, 'created_pizza_pk': created_pizza_pk }) else: form = PizzaForm() return render(request, 'pizza/order.html', { 'multiple_form': multiple_form, 'pizzaform': form })
def sms_actions(request): """SMS Actions handles sending of SMS, Marking as read and archiving""" # Action will be communicated in the request. action = request.POST.get('sendSMS') message_id = request.POST.get('id') if action == 'sendSMS': form = MessageForm(request.POST) if form.is_valid(): message = Messaging() message.hl_service = 'SMSService' message.hl_contact = form.cleaned_data.get('number') message.hl_key = randint(123456789, 987654321) message.hl_status = 'Outbox' message.hl_type = 'SMS' message.hl_content = form.cleaned_data.get('message') message.hl_staff = request.user.hl_users.hl_key message.hl_time = int(time.time()) message.save() if message_id: message = Messaging.objects.get(id=message_id) if request.POST.get('read'): message.hl_status = 'Old' message.save() return {'success': 1, 'message': 'Message marked as read.'} ctx = {} ctx.update(csrf(request)) # Send sms using sms_send api api.send_sms(body=form.cleaned_data.get('message'), from_phone=message.hl_service, to=[message.hl_contact]) return {'success': 1, 'message': 'SMS Sent Successfully.'}
def send_message( message: str, subject: str, recip: list, recip_email: list, html_message: str = None ): """ Sends message to specified value. Source: Himanshu Shankar (https://github.com/iamhssingh) Parameters ---------- message: str Message that is to be sent to user. subject: str Subject that is to be sent to user, in case prop is an email. recip: list Recipient to whom message is being sent. recip_email: list Recipient to whom EMail is being sent. This will be deprecated once SMS feature is brought in. html_message: str HTML variant of message, if any. Returns ------- sent: dict """ import smtplib from django.conf import settings from django.core.mail import send_mail from sendsms import api sent = {"success": False, "message": None} if not getattr(settings, "EMAIL_HOST", None): raise ValueError( "EMAIL_HOST must be defined in django " "setting for sending mail." ) if not getattr(settings, "EMAIL_FROM", None): raise ValueError( "EMAIL_FROM must be defined in django setting " "for sending mail. Who is sending email?" ) if not getattr(settings, "EMAIL_FROM", None): raise ValueError( "EMAIL_FROM must be defined in django setting " "for sending mail. Who is sending email?" ) # Check if there is any recipient if not len(recip) > 0: raise ValueError("No recipient to send message.") # Check if the value of recipient is valid (min length: [email protected]) elif len(recip[0]) < 5: raise ValueError("Invalid recipient.") # Check if all recipient in list are of same type is_email = validate_email(recip[0]) for ind in range(len(recip)): if validate_email(recip[ind]) is not is_email: raise ValueError("All recipient should be of same type.") elif not is_email: recip[ind] = get_mobile_number(recip[ind]) # Check if fallback email is indeed an email for rcp in recip_email: if not validate_email(rcp): raise ValueError("Invalid email provided: {}".format(rcp)) if isinstance(recip, str): # For backsupport recip = [recip] if isinstance(recip_email, str): # For backsupport recip_email = [recip_email] if is_email: try: send_mail( subject=subject, message=message, html_message=html_message, from_email=settings.EMAIL_FROM, recipient_list=recip, ) except smtplib.SMTPException as ex: sent["message"] = "Message sending failed!" + str(ex.args) sent["success"] = False else: sent["message"] = "Message sent successfully!" sent["success"] = True else: try: api.send_sms(body=message, to=recip, from_phone=None) # Django SendSMS doesn't provide an output of success/failure. # Send mail either ways, just to ensure delivery. send_message( message=message, subject=subject, recip=recip_email, recip_email=recip_email, html_message=html_message, ) except Exception as ex: sent["message"] = "Message sending Failed!" + str(ex.args) sent["success"] = False send_message( message=message, subject=subject, recip=recip_email, recip_email=recip_email, html_message=html_message, ) else: sent["message"] = "Message sent successfully!" sent["success"] = True return sent
def sms(request): api.send_sms(body='I can haz txt', from_phone='+919667626421', to=['+919560440822']) return HttpResponseRedirect('/home')