def test_send_message_failure(mocker): """Tests that send_messages logs all exceptions""" sendmail = mocker.patch("mail.api.AnymailMessage.send", side_effect=ConnectionError) patched_logger = mocker.patch("mail.api.log") users = UserFactory.create_batch(2) messages = list( messages_for_recipients( [ ( recipient, context_for_user( user=user, extra_context={"url": "https://example.com"} ), ) for recipient, user in safe_format_recipients(users) ], "sample", ) ) send_messages(messages) assert sendmail.call_count == len(users) assert patched_logger.exception.call_count == len(users)
def send_verification_email( strategy, backend, code, partial_token ): # pylint: disable=unused-argument """ Sends a verification email for python-social-auth Args: strategy (social_django.strategy.DjangoStrategy): the strategy used to authenticate backend (social_core.backends.base.BaseAuth): the backend being used to authenticate code (social_django.models.Code): the confirmation code used to confirm the email address partial_token (str): token used to resume a halted pipeline """ url = "{}?verification_code={}&partial_token={}".format( strategy.build_absolute_uri(reverse("register-confirm")), quote_plus(code.code), quote_plus(partial_token), ) api.send_messages( list( api.messages_for_recipients( [ ( code.email, api.context_for_user(extra_context={"confirmation_url": url}), ) ], VERIFICATION_TEMPLATE_NAME, ) ) )
def send_notification(self, email_notification): """ Sends the notification to the user Args: email_notification (EmailNotification): the notification to be sent """ messages = None user = email_notification.user with utils.mark_as_sent_or_canceled(email_notification) as will_send: # check against programmer error if user != self.user: raise Exception( "Notification user doesn't match settings user") # if we're trying to send an email, but the preference is never, we should just cancel it if self.notification_settings.is_triggered_never: raise CancelNotificationError() if not will_send: return last_notification = self._get_most_recent_notification( before=email_notification) data = self._get_notification_data(email_notification, last_notification) # generate the message (there's only 1) messages = list( api.messages_for_recipients( [(recipient, api.context_for_user(user=user, extra_context=data)) for recipient, user in api.safe_format_recipients([user]) ], self._template_name, )) if not messages: raise CancelNotificationError() # we don't want an error sending to cause a resend, because it could cause us to actually send it twice if messages: # if we got this far and have messages, send them api.send_messages(messages)
def test_send_message(mailoutbox): """Tests that send_messages works as expected""" users = UserFactory.create_batch(5) messages = list( messages_for_recipients( [( recipient, context_for_user(user=user, extra_context={"url": "https://example.com"}), ) for recipient, user in safe_format_recipients(users)], "sample", )) send_messages(messages) for message in mailoutbox: assert message in messages
def send(self, to, *args, **kwargs): """ Overrides djoser.email.PasswordResetEmail#send to use our mail API. """ context = self.get_context_data() context.update(self.context) with django_mail.get_connection( settings.NOTIFICATION_EMAIL_BACKEND) as connection: subject, text_body, html_body = render_email_templates( "password_reset", context) msg = AnymailMessage( subject=subject, body=text_body, to=to, from_email=settings.MAILGUN_FROM_EMAIL, connection=connection, ) msg.attach_alternative(html_body, "text/html") send_messages([msg])
def send_bulk_enroll_emails(bulk_assignment_id, product_coupon_assignments): """ Sends an email for recipients to enroll in a courseware offering via coupon Args: bulk_assignment_id (int): The id for the BulkCouponAssignment that the assignments belong to product_coupon_assignments (iterable of ProductCouponAssignments): Product coupon assignments about which we want to notify the recipients """ api.send_messages( api.build_user_specific_messages( EMAIL_BULK_ENROLL, ( get_bulk_enroll_message_data( bulk_assignment_id, product_coupon_assignment.email, product_coupon_assignment.product_coupon, ) for product_coupon_assignment in product_coupon_assignments ), ) )
def send_invitation_email(channel_invitation_id): """ Sends a channel invitation Args: channel_invitation_id (int): the id of the ChannelInvitation """ invite = ChannelInvitation.objects.get(id=channel_invitation_id) signup_url = urljoin(settings.SITE_BASE_URL, reverse("signup")) mail_api.send_messages( list( mail_api.messages_for_recipients( [( invite.email, mail_api.context_for_user(extra_context={ "invite": invite, "signup_url": signup_url }), )], "invite", )))
def send_verify_email_change_email(request, change_request): """ Sends a verification email for a user email change Args: request (django.http.Request): the http request we're sending this email for change_request (ChangeEmailRequest): the change request to send the confirmation for """ url = "{}?verification_code={}".format( request.build_absolute_uri(reverse("account-confirm-email-change")), quote_plus(change_request.code), ) api.send_messages( list( api.messages_for_recipients( [( change_request.new_email, api.context_for_user( extra_context={"confirmation_url": url}), )], EMAIL_CHANGE_EMAIL, )))
def send_ecommerce_order_receipt(order, cyber_source_provided_email=None): """ Send emails receipt summarizing the user purchase detail. Args: cyber_source_provided_email: Include the email address if user provide though CyberSource payment process. order: An order. """ from ecommerce.serializers import OrderReceiptSerializer data = OrderReceiptSerializer(instance=order).data purchaser = data.get("purchaser") coupon = data.get("coupon") lines = data.get("lines") order = data.get("order") receipt = data.get("receipt") country = pycountry.countries.get(alpha_2=purchaser.get("country")) recipients = [purchaser.get("email")] if cyber_source_provided_email and cyber_source_provided_email not in recipients: recipients.append(cyber_source_provided_email) try: messages = list( api.messages_for_recipients( [ ( recipient, api.context_for_user( user=None, extra_context={ "coupon": coupon, "content_title": lines[0].get("content_title") if lines else None, "lines": lines, "order_total": format( sum(float(line["total_paid"]) for line in lines), ".2f", ), "order": order, "receipt": receipt, "purchaser": { "name": " ".join( [ purchaser.get("first_name"), purchaser.get("last_name"), ] ), "email": purchaser.get("email"), "street_address": purchaser.get("street_address"), "state_code": purchaser.get( "state_or_territory" ).split("-")[-1], "postal_code": purchaser.get("postal_code"), "city": purchaser.get("city"), "country": country.name if country else None, "company": purchaser.get("company"), }, }, ), ) for recipient in recipients ], EMAIL_PRODUCT_ORDER_RECEIPT, ) ) api.send_messages(messages) except: # pylint: disable=bare-except log.exception("Error sending order receipt email.")