def send_simple_message(address, url, template, order=None): site = Site.objects.get_current() if order: orders = [order for order in order.get_lines()] t = get_templated_mail( template_name=template, from_email=settings.ORDER_FROM_EMAIL, to=[address], context={'site_name': site.name, 'url': url, 'orders': orders, 'order': order, 'address': order.shipping_address}) else: t = get_templated_mail( template_name=template, from_email=settings.ORDER_FROM_EMAIL, to=[address], context={'site_name': site.name, 'url': url}) response = requests.post( "https://api.mailgun.net/v3/{}/messages".format(settings.MAILGUN_DOMAIN_NAME), auth=("api", settings.MAILGUN_API_KEY), data={"from": "Al Rawaa Vape Sales {}".format(t.from_email), "to": [address], "subject": t.subject, "html": t.body}) return response
def test_arguments_get_passsed_to_get_email_message(self, mocked_backend): get_templated_mail(*self.TEST_ARGS, **self.TEST_KWARGS) mocked_backend.assert_called_with(template_prefix='prefix', template_suffix='suffix') get_email_message = mocked_backend.return_value.get_email_message kwargs = dict(self.TEST_KWARGS) del kwargs['template_dir'] del kwargs['file_extension'] get_email_message.assert_called_with(*self.TEST_ARGS, **kwargs)
def test_arguments_get_email_message_fallback(self, mocked_backend): kwargs = dict(self.TEST_KWARGS) del kwargs['template_prefix'] del kwargs['template_suffix'] get_templated_mail(*self.TEST_ARGS, **kwargs) mocked_backend.assert_called_with(template_prefix=kwargs['template_dir'], template_suffix=kwargs['file_extension']) get_email_message = mocked_backend.return_value.get_email_message kwargs['template_prefix'] = kwargs.pop('template_dir') kwargs['template_suffix'] = kwargs.pop('file_extension') get_email_message.assert_called_with(*self.TEST_ARGS, **kwargs)
def send_to_subscribers(self, id): from django.db.models import Q yesterday = timezone.now() - datetime.timedelta(15) query = Event.objects.all() \ .filter(Q(author__friendship__friend__id=id) & Q(created__gt=yesterday)) \ .distinct().order_by('-created').prefetch_related('author', 'content_object') user = User.objects.get(pk=id) recipient_list = [ user.email, ] if settings.DEBUG: recipient_list = [admin[0] for admin in settings.ADMINS] event_list = list(query) context = { 'events': event_list, 'user': user, } email = get_templated_mail('subscribe', context, '*****@*****.**', recipient_list) email.send() return user.email
def send_to_subscribers(self, id): from django.db.models import Q yesterday = timezone.now() - datetime.timedelta(15) query = Event.objects.all() \ .filter(Q(author__friendship__friend__id=id) & Q(created__gt=yesterday)) \ .distinct().order_by('-created').prefetch_related('author', 'content_object') user = User.objects.get(pk=id) recipient_list = [user.email, ] if settings.DEBUG: recipient_list = [admin[0] for admin in settings.ADMINS] event_list = list(query) for q in event_list: if q.author.avatar: q.avatar = InlineImage('ava_{}.jpeg'.format(q.id), open(q.author.avatar.file.name, 'rb').read(), 'jpeg') else: q.avatar = None context = { 'events': event_list, 'user': user, } email = get_templated_mail('subscribe', context, '*****@*****.**', recipient_list) for q in event_list: if q.avatar: q.avatar.attach_to_message(email) email.send() return user.email
def multi_templated_email(templateName, to_emails, from_email, context): """ send separate emails to multiple recipients using a template """ for to in to_emails: email = get_templated_mail(templateName, context=context, from_email=from_email, to=[to]) email.send()
def test_arguments_get_email_message_fallback(self, mocked_backend): kwargs = dict(self.TEST_KWARGS) del kwargs['template_prefix'] del kwargs['template_suffix'] get_templated_mail(*self.TEST_ARGS, **kwargs) mocked_backend.assert_called_with( template_prefix=kwargs['template_dir'], template_suffix=kwargs['file_extension']) get_email_message = mocked_backend.return_value.get_email_message kwargs['template_prefix'] = kwargs.pop('template_dir') kwargs['template_suffix'] = kwargs.pop('file_extension') get_email_message.assert_called_with(*self.TEST_ARGS, **kwargs)
def send_mail(template, from_mail, recipient_list, context): if settings.DEBUG: recipient_list = [admin[0] for admin in settings.ADMINS] email = get_templated_mail(template, context, from_mail, recipient_list) email.send()
def send_mail(from_email, recipient_list, attachments=[]): if settings.DEBUG: recipient_list = [admin[0] for admin in settings.ADMINS] email = get_templated_mail( 'mail', { # 'image': InlineImage('image.jpeg', open('./static/image.jpeg', 'rb').read(), 'jpeg'), }, from_email, recipient_list) email.send()
def send_email(seller, client, licenses): message = get_templated_mail( template_name='notify_seller', from_email=EMAIL_HOST_USER, to=[seller.email], context={ 'seller': seller, 'client': client, 'licenses': licenses }, ) message.send()
def email_invitees(round_url, round_donations, round_expiration, round_invitees): """ email sent by round creator to invite other people to the round by email """ email_from = '*****@*****.**' invitees_list = round_invitees.split(',') time_left = round_expiration.replace(tzinfo=None) - datetime.now().replace(tzinfo=None) round_donation_str = "Fake Person, Another Fake Person" #TODO: r.name for r in round_donations for invitee in invitees_list: email = get_templated_mail('invite', context={}, from_email=email_from, to=[invitee]) email.send()
def send_match_email(user_one, user_two): email = get_templated_mail(template_name='match', from_email='*****@*****.**', to=[user_one.email, user_two.email], context={ 'name_one': user_one.name, 'description_one': user_one.description, 'name_two': user_two.name, 'description_two': user_two.description }) send_mail(email.subject, email.body, email.from_email, email.to)
def send_mail_to_user(template, from_email, user): recipient_list = [ user.email, ] if settings.DEBUG: recipient_list = [admin[0] for admin in settings.ADMINS] email = get_templated_mail(template, { 'user': user, }, from_email, recipient_list) # img = InlineImage('continue.jpeg', open('./static/continue.jpeg', 'rb').read(), 'jpeg') # img.attach_to_message(email) email.send()
def test_get_templated_mail(self): context = dict(subject='Subject', ) msg = get_templated_mail( template_name='test', to=['*****@*****.**'], context=context, ) """:type : EmailMultiAlternatives""" self.assertEqual(msg.subject, context['subject']) self.assertEqual(msg.body, "Plain text") self.assertEqual(len(msg.alternatives), 1) self.assertEqual(msg.alternatives[0][0], "<p>HTML text</p>") self.assertEqual(msg.alternatives[0][1], "text/html")
def send_email(template, from_mail, recipient_list, context=None): if settings.DEBUG: recipient_list = [admin[0] for admin in settings.ADMINS] email = get_templated_mail( template, context, from_mail, recipient_list, # headers={'charset': 'utf-8'}, ) # email.encoding = 'utf8' email.send()
def handle(self, *args, **options): template_name = options.get('template_name') context_file = options.get('context') # If context file is not set, use the template name to assume the context file path if context_file is None: context_file = 'core/management/commands/mail_context/{}.json'.format( template_name) # Check that context JSON file exists if not os.path.isfile(context_file): raise CommandError('Context JSON file not found: ' + context_file) # Read in the context file to a dictionary with open(context_file) as handle: context = json.loads(handle.read()) try: mail = get_templated_mail( template_name=template_name, from_email='*****@*****.**', to=['*****@*****.**'], context=context, ) except Exception as ex: raise CommandError( 'Could not get templated mail named \'{}\''.format( template_name), ex) # If the 'save' option (-s) was specified, save the text and HTML versions # of the mail message to files. if options.get('save'): main_message = mail.body if hasattr(mail, 'alternatives') and len(mail.alternatives): main_message = mail.alternatives[0][0] with open(template_name + '.txt', 'w') as mail_txt: mail_txt.write(mail.body) with open(template_name + '.html', 'w') as mail_html: mail_html.write(main_message) # Otherwise, just print the HTML message to stdout else: print(mail.alternatives[0][0])
def send_mail(from_mail, recipient_list): if settings.DEBUG: recipient_list = [admin[0] for admin in settings.ADMINS] email = get_templated_mail( 'base', { 'image': InlineImage('kobe.jpg', open(settings.MEDIA_ROOT + 'Kobe.jpg', 'rb').read(), 'jpeg'), 'host': 'https//yandex.ru' }, from_mail, recipient_list, ) email.send()
def make_email(context, recipient): from_email = settings.DEFAULT_FROM_EMAIL with open('bullets.png', 'rb') as bulletpic: image = bulletpic.read() inline_image = InlineImage(filename="bullets.png", content=image) context['bullet_pic'] = inline_image # with open('acacia.png', 'rb') as acaciapic: # image = acaciapic.read() # inline_image_a = InlineImage(filename="acacia.png", content=image) # context['extra_pic'] = inline_image_a mail = get_templated_mail(template_name="source/bullets/acacia-charity", from_email=from_email, to=[recipient], context=context) mail.attach_file('1010-sponsorship.pdf') mail.send() # ???
def __init__(self, data, subscription_obj, add_csv=True, **extra_context): """ :arg data: a :class:`django.db.models.query.QuerySet` :arg subscription_obj: :class:`p_soc_auto_base.models.Subscription` instance Will contain all the metadata required to build and send the email message. This includes template information and pure SMTP data (like email addresses and stuff). :arg bool add_csv: generate the csv file from :attr:`Email.data` and attach it to the email message? :arg dict extra_context: additional data required by the `Django template <https://docs.djangoproject.com/en/2.2/topics/templates/#module-django.template>`_ for rendering the email message If this argument is present, the {key: value,} pairs therein will be appended to the :attr:`Email.context` :class:`dictionary <dict>`. :raises: :exc:`Exception` if the email message cannot be prepared """ self.add_csv = add_csv """ :class:`bool` attribute controlling whether a comma-separated file is to be created and attached to the email message """ self.csv_file = None """ :class:`str` attribute for the name of the comma-separated file This attribute is set in the :meth:`prepare_csv`. """ self.subscription_obj = subscription_obj """ an :class:`p_soc_auto_base.models.Subscriptions` instance with the details required for rendering and sending the email message """ self.data = data """ :class:`django.db.models.query.QuerySet` with the data to be rendered in the email message body """ self.headers = self._get_headers_with_titles() """ a :class:`dictionary <dict>` that maps human readable column names (headers) to the fields in the :attr:`data` :class:`django.db.models.query.QuerySet` """ self._prepare_csv() self.prepared_data = [] """ :class:`list` of :class:`dictionaries <dict>` where each item represents a row in the :attr:`Email.data` :class:`django.db.models.query.QuerySet` with the human readable format of the field name (as represented by the values in the :attr:`Email.headers` :class:`dictionary <dict>`) as the key and the contents of the field as values For example, if the `queryset` has one entry with dog_name: 'jimmy', the corresponding entry in :attr:`Email.headers` is {'dog_name': 'Dog name'}, and the item in this list will end up as {'Dog name': 'jimmy'}. """ if data: self.prepared_data = [{ key: data_item[key] for key in self.headers.keys() } for data_item in data.values(*self.headers.keys())] self.context = dict(report_date_time=timezone.now(), headers=self.headers, data=self.prepared_data, source_host_name='http://%s:%s' % (socket.getfqdn(), settings.SERVER_PORT), source_host=socket.getfqdn(), tags=self._set_tags(), email_subject=self.subscription_obj.email_subject, alternate_email_subject=self.subscription_obj. alternate_email_subject, subscription_name=subscription_obj.subscription, subscription_id=subscription_obj.pk) """ :class:`dictionary <dict>` used to `render the context <https://docs.djangoproject.com/en/2.2/ref/templates/api/#rendering-a-context>`_ for the email message """ if extra_context: self.context.update(**extra_context) self._debug_init() LOG.debug('Context: %s', self.context) try: self.email = get_templated_mail( template_name=subscription_obj.template_name, template_dir=subscription_obj.template_dir, template_prefix=subscription_obj.template_prefix, from_email=get_preference('emailprefs__from_email') if settings.DEBUG else subscription_obj.from_email, to=get_list_preference('emailprefs__to_emails') if settings.DEBUG else subscription_obj.emails_list.split(','), context=self.context, create_link=True) LOG.debug('email object is ready') except Exception as err: LOG.exception(str(err)) raise err if self.csv_file: self.email.attach_file(self.csv_file)
def test_get_templated_mail_returns_response_of_get_email_message( self, mocked_backend): ret = get_templated_mail(*self.TEST_ARGS) self.assertTrue( ret is mocked_backend.return_value.get_email_message.return_value)
def test_called_get_email_message_from_vanilla_backend( self, mocked_backend): get_templated_mail(*self.TEST_ARGS) mocked_backend.return_value.get_email_message.assert_called_once()
def test_called_get_email_message_from_vanilla_backend(self, mocked_backend): get_templated_mail(*self.TEST_ARGS) mocked_backend.return_value.get_email_message.assert_called_once()
def send_mail(from_email, recipient_list): if settings.DEBUG: recipient_list = [admin[0] for admin in settings.ADMINS] email = get_templated_mail('mail', {}, from_email, recipient_list) email.send()