def send_mail(subject, like, to): email = EmailMultiAlternatives(subject, like, '*****@*****.**', to) pic = InlineImage('spirit.jpg', open(u'C:\spirit.jpg', 'rb').read(), subtype='jpeg') pic.attach_to_message(email) html = render_to_string('emails/liked.html', {'spirit': pic, 'cool': like}) email.attach_alternative(html, 'text/html') email.send()
def send_digest(subject, posts, to): email = EmailMultiAlternatives(subject, str(posts), '*****@*****.**', to) pic = InlineImage('spirit.jpg', open(u'C:\spirit.jpg', 'rb').read(), subtype='jpeg') pic.attach_to_message(email) html = render_to_string('emails/digest.html', { 'spirit': pic, 'posts': posts }) email.attach_alternative(html, 'text/html') email.send()
def send_welcome_letter(self): if settings.DEBUG: to = [admin[0] for admin in settings.ADMINS] # base_send_mail(subject, text, '*****@*****.**', to) email = EmailMultiAlternatives('Welcome', 'hi', '*****@*****.**', to) pic = InlineImage('pic.jpg', open('/home/lida/web_project_2sem/technotrack-web2-spring-2017/core/static/core/download.png','rb').read()) pic.attach_to_message(email) html = render_to_string('email/welcome_letter.html', {'username': self.username, 'SITE_URL': settings.SITE_URL, 'pic': pic}) email.attach_alternative(html, 'text/html') # email.attach('myfile.txt', 'THIS IS MY FILE', 'text/plain') email.send()
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 send_daily_template_mail(user, day): tomorrow = day + timedelta(1) day_start = datetime.combine(day, time()) day_end = datetime.combine(tomorrow, time()) posts = Post.objects.\ filter(created__lte=day_end, created__gte=day_start).\ filter(author__in=user.friends.values_list('user2')) import os path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ava.png') with open(path, 'r') as fin: ava_image = fin.read() inline_image = InlineImage(filename="ava.png", content=ava_image) send_templated_mail( template_name='daily', from_email='*****@*****.**', recipient_list=[user.email], context={ 'username': user.username, 'posts': posts, 'date': day, 'ava_image': inline_image, }, create_link=True # Optional: # cc=['*****@*****.**'], # bcc=['*****@*****.**'], # headers={'My-Custom-Header':'Custom Value'}, # template_prefix="my_emails/", # template_suffix="email", )
def send_daily_mail(user, day): tomorrow = day + timedelta(days=1) day_start = datetime.combine(day, time()) day_end = datetime.combine(tomorrow, time()) from ugc.models import Post posts = Post.objects.filter(created__lte=day_end, created__gte=day_start) # From a file f = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'img.png') with open(f, 'rb') as img: image = img.read() inline_image = InlineImage(filename="img.png", content=image) send_templated_mail( template_name='daily', from_email='*****@*****.**', recipient_list=[user.email], context={ 'username': user.username, 'posts': posts, 'date': day, 'image': inline_image, }, create_link=True # Optional: # cc=['*****@*****.**'], # bcc=['*****@*****.**'], # headers={'My-Custom-Header':'Custom Value'}, # template_prefix="my_emails/", # template_suffix="email", )
def send_mail(subject, text, template, context, to): if settings.DEBUG: to = [admin[0] for admin in settings.ADMINS] email = EmailMultiAlternatives(subject, text, '*****@*****.**', to) pic = InlineImage( 'pepe.png', open( '/Users/Oskar/Desktop/Phystech/Technotrack/WEB2/Project/src/core/static/images/pepe_logo.png', 'rb').read(), 'image/png') pic.attach_to_message(email) context['pepe_logo'] = pic html = render_to_string(template, context) email.attach_alternative(html, 'text/html') email.send()
class InlineMessageTestCase(MockedNetworkTestCaseMixin, TestCase): def setUp(self): self.inline_image = InlineImage('foo.png', 'content', 'png') def test_needs_two_args(self): with self.assertRaises(TypeError): InlineImage() with self.assertRaises(TypeError): InlineImage('foo') def test_has_no_cid(self): self.assertIsNone(self.inline_image._content_id) def test_generate_cid(self): str(self.inline_image) self.assertIsNotNone(self.inline_image._content_id) @mock.patch('templated_email.utils.make_msgid', return_value='foo') def test_str(self, mocked): self.assertEqual(str(self.inline_image), 'cid:foo') @mock.patch('templated_email.utils.make_msgid', return_value='foo') def test_should_cache_cid(self, mocked): str(self.inline_image) str(self.inline_image) mocked.assert_called_once() def test_changing_content_should_generate_new_cid(self): src_value = str(self.inline_image) cid = self.inline_image._content_id self.inline_image.content = 'content2' cid2 = self.inline_image._content_id src_value2 = str(self.inline_image) self.assertNotEqual(src_value, src_value2) cid3 = self.inline_image._content_id self.assertNotEqual(cid, cid2) self.assertNotEqual(cid2, cid3) def test_attach_to_message(self): message = mock.Mock() self.inline_image.attach_to_message(message) mimeimage = message.attach.call_args[0][0] self.assertEquals(mimeimage.get('Content-ID'), self.inline_image._content_id) self.assertEquals(mimeimage.get('Content-Disposition'), 'inline; filename="foo.png"')
def setUp(self): self.backend = TemplateBackend() self.inline_image = InlineImage('foo.png', base64.b64decode(imageb64)) self.message = self.backend.get_email_message( 'inline_image.email', {'image_file': self.inline_image}, from_email='*****@*****.**', cc=['*****@*****.**'], bcc=['*****@*****.**'], to=['*****@*****.**'])
def test_host_inline_image_if_not_exist(self): inline_image = InlineImage('foo.jpg', b'bar') self.storage_mock.save = Mock(return_value='saved_url') with self.patch_storage(): filename = self.backend.host_inline_image(inline_image) self.assertEqual(filename, '/media/saved_url') self.storage_mock.save.assert_called_once() name, content = self.storage_mock.save.call_args[0] self.assertEquals( name, 'templated_email/37b51d194a7513e45b56f6524f2d51f2foo.jpg') self.assertTrue(isinstance(content, BytesIO))
def test_get_email_message_with_inline_image(self, mocked): self.storage_mock.save = Mock(return_value='saved_url') with self.patch_storage(): self.backend.get_email_message( 'foo.email', {'an_image': InlineImage('file.png', b'foo', subtype='png')}, from_email='*****@*****.**', cc=['*****@*****.**'], bcc=['*****@*****.**'], to=['*****@*****.**'], create_link=True) second_call_context = mocked.call_args_list[1][0][1] self.assertEqual(second_call_context['an_image'], '/media/saved_url')
def send_digest_letter(self): to = [admin[0] for admin in settings.ADMINS] # base_send_mail(subject, text, '*****@*****.**', to) email = EmailMultiAlternatives('Welcome', 'hi', '*****@*****.**', to) pic = InlineImage('pic.jpg', open('/home/lida/web_project_2sem/technotrack-web2-spring-2017/core/static/core/download.png', 'rb').read()) pic.attach_to_message(email) html = render_to_string('email/digest_letter.html', {'username': self.username, 'SITE_URL': settings.SITE_URL, 'pic': pic}) #for object in User.following.through.objects.filter(from_user=self.id): # events = Event.objects.filter(author_id=object.to_user) email.attach_alternative(html, 'text/html') # email.attach('myfile.txt', 'THIS IS MY FILE', 'text/plain') email.send()
def test_host_inline_image_if_exist(self): inline_image = InlineImage('foo.jpg', b'bar') self.storage_mock.exists = Mock(return_value=True) with self.patch_storage(): filename = self.backend.host_inline_image(inline_image) self.assertEqual( filename, '/media/templated_email/37b51d194a7513e45b56f6524f2d51f2foo.jpg') self.storage_mock.save.assert_not_called() self.storage_mock.exists.assert_called_once_with( 'templated_email/37b51d194a7513e45b56f6524f2d51f2foo.jpg')
def send_bullet_mail(template_name, recipient_list, context, extra_headers={}, from_email=None): if from_email == None: 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 return send_templated_mail(template_name=template_name, from_email=from_email, recipient_list=recipient_list, context=context, headers=extra_headers)
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, { 'image': InlineImage('continue.jpeg', open('./static/continue.jpeg', 'rb').read(), 'jpeg'), '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 _send_mail(template_name, to_emails, from_email=None, **kwargs): """ Sends an email using a template (leveraging django-templated-email) If you need to attach extra images to the email, add them to kwargs prefixed with `IMAGE_`, like... _send_mail('welcome', [[email protected]], IMAGE_TEST="images/test.jpg"} {# and then in our template.. #} <img src="{{ IMAGE_TEST }}"/> :param template_name: :param to_emails: :param from_email: :param kwargs: additional context to insert into email template :return: email result """ context = dict(**settings.DEFAULT_EMAIL_CONTEXT) if kwargs: # pragma: no cover context.update(kwargs) # Turn static image paths into inline images in our template context for name, path in context.items(): if name.startswith("IMAGE_"): # Currently only gets static files... maybe should rename IMAGE_ to STATIC_IMAGE_ ? with open(find(path), 'rb') as image: context[name] = InlineImage( filename=os.path.basename(path), content=image.read() ) from_email = from_email if from_email is not None else settings.DEFAULT_FROM_EMAIL try: return send_templated_mail( template_name=template_name, from_email=from_email, recipient_list=to_emails, context=context, ) except AnymailRecipientsRefused: # pragma: no cover logger.exception(f'AnymailRecipientsRefused raised for {to_emails}')
def send_email_task(self, template, from_mail, recipient_id, text): recipient_list = [ {User.objects.get(id=recipient_id).email}, ] context = { 'text': text, 'image': InlineImage('kobe.jpg', open(settings.MEDIA_ROOT + 'Kobe.jpg', 'rb').read(), 'jpeg'), 'subject': 'New post' } try: send_email(template, from_mail, recipient_list, context) except Exception as exc: raise self.retry(exc=exc, countdown=3, max_retries=3)
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 form_send_email(request, pk): '''the organizer of the event can send the email to all members who are going to his event''' template_name = 'events/send_email.html' event = get_object_or_404(Events, id=pk) members = JoinModelButton.objects.filter(event=pk, value='Join') obj = [] for m in members: obj += UserProfileInfoModel.objects.filter(user=m.user) # obj += User.objects.filter(username=m.user) if request.method == 'POST': form = SendEmailForm(request.POST) if form.is_valid(): subject = request.POST.get('subject', '') message = request.POST.get('message', '') if subject and message: for o in obj: # print(o.email, o.user, o.first_name, o.last_name) try: img_data = event.cover.read() img_name = Path(event.cover.url).name inline_image = InlineImage(filename=img_name, content=img_data, subtype='jpeg') if o.first_name: c = { 'event_image': inline_image, 'content': message, 'event': event, 'username': o.first_name, 'sendler': request.user.username, 'pk': pk, 'subject': subject } else: c = { 'event_image': inline_image, 'content': message, 'event': event, 'username': o.user, 'sendler': request.user.username, 'pk': pk, 'subject': subject } send_templated_mail( template_name='welcome', from_email=settings.EMAIL_HOST_USER, recipient_list=[o.email], context=c) except BadHeaderError: return HttpResponse('Invalid header found.') success_url = reverse_lazy('event_detail', kwargs={'pk': event.id}) return HttpResponseRedirect(success_url) else: return HttpResponse('Make sure all fields are entered and valid.') return redirect('event_detail', pk=event.id) else: form = SendEmailForm() user_profile = UserProfileInfoModel.objects.get(user=request.user) context = { 'form': form, 'title': 'Send email to all members', 'name_button': 'Send emails', 'user_profile': user_profile, 'event': event } return render(request, template_name, context)
def setUp(self): self.inline_image = InlineImage('foo.png', 'content', 'png')
def test_needs_two_args(self): with self.assertRaises(TypeError): InlineImage() with self.assertRaises(TypeError): InlineImage('foo')
import os from django.conf import settings from templated_email import send_templated_mail, InlineImage from payments.utils import * sender_email = "BHMC<*****@*****.**>" secretary_email = "*****@*****.**" treasurer_email = "*****@*****.**" admin_email = "*****@*****.**" logo_file = os.path.join(settings.BASE_DIR, "templates/templated_email/logo.png") with open(logo_file, "rb") as logo: image = logo.read() inline_image = InlineImage(filename=logo_file, content=image) def send_notification(payment, slots, player): user = payment.user event = payment.event registration = slots[0].registration if payment.notification_type == "R": send_member_welcome(user) send_has_notes_notification(user, event, registration.notes) elif payment.notification_type == "N": send_member_welcome(user) send_new_member_notification(user, player, registration.notes) elif payment.notification_type == "M": send_match_play_confirmation(user)
def overall_report(): os.chdir(os.path.dirname(sys.argv[0])) data = do_get_dfs_capacity_email() rows, remaining, metadata = do_get_hdfs_used_weekly() rows1, metadata = do_get_hdfs_used_monthly() rows2, metadata = do_get_hdfs_used_quarterly() rows3 = do_get_hive_top_email() rows4 = do_get_impala_top_email() rows5 = query_small_files() get_impala_job_summary() get_hive_job_summary() query_file_incr_info() do_get_dfs_cpu() do_get_dfs_mem() do_get_dfs_net() with open('./cpu.png', 'rb') as lena1: image1 = lena1.read() with open('./mem.png', 'rb') as lena2: image2 = lena2.read() with open('./net.png', 'rb') as lena3: image3 = lena3.read() with open('./hdfs_weekly.png', 'rb') as lena4: image4 = lena4.read() with open('./hdfs_monthly.png', 'rb') as lena5: image5 = lena5.read() with open('./hdfs_quarterly.png', 'rb') as lena6: image6 = lena6.read() with open('./file.png', 'rb') as lena7: image7 = lena7.read() with open('./file2.png', 'rb') as lena8: image8 = lena8.read() with open('./impala_pie.png', 'rb') as lena9: image9 = lena9.read() with open('./hive_pie.png', 'rb') as lena10: image10 = lena10.read() inline_image1 = InlineImage(filename="cpu.png", content=image1) inline_image2 = InlineImage(filename="mem.png", content=image2) inline_image3 = InlineImage(filename="net.png", content=image3) inline_image4 = InlineImage(filename="hdfs_weekly.png", content=image4) inline_image5 = InlineImage(filename="hdfs_monthly.png", content=image5) inline_image6 = InlineImage(filename="hdfs_quarterly.png", content=image6) inline_image7 = InlineImage(filename="file.png", content=image7) inline_image8 = InlineImage(filename="file2.png", content=image8) inline_image9 = InlineImage(filename="impala_pie.png", content=image9) inline_image10 = InlineImage(filename="hive_pie.png", content=image10) send_templated_mail( template_name='report_template2', from_email='*****@*****.**', recipient_list=['*****@*****.**', '*****@*****.**'], context={ 'time': zone_conversion(get_now()), 'data': data, 'rows': rows, 'rows1': rows1, 'rows2': rows2, 'rows3': rows3, 'rows4': rows4, 'rows5': rows5, 'remaining': remaining, 'cpu_image': inline_image1, 'mem_image': inline_image2, 'net_image': inline_image3, 'hdfs_weekly_image': inline_image4, 'hdfs_monthly_image': inline_image5, 'hdfs_quarterly_image': inline_image6, 'file_image': inline_image7, 'file2_image': inline_image8, 'impala_pie_image': inline_image9, 'hive_pie_image': inline_image10 }, # Optional: # cc=['*****@*****.**'], # bcc=['*****@*****.**'], # headers={'My-Custom-Header':'Custom Value'}, # template_prefix="my_emails/", # template_suffix="email", ) print 'email send'