def send_mail(self, global_merge_vars): if self.to == "": try: msg = EmailMessage(subject="[Issue] Email Missing", from_email="*****@*****.**", to=["*****@*****.**"],) msg.template_name = "Issue" msg.global_merge_vars = { 'problem': 'Email ID Missing', 'details1': 'SendMail Id: ' + str(self.id), 'details2': 'User with missing email: ' + str(self.to_name), 'details3': '', } msg.send() except Exception as e: print(e) return try: global_merge_vars['USERNAME'] = self.to_name # Building actor details actor = User.objects.get(id=self.actor_id) actor_url = ''.join(['http://www.makeystreet.com', reverse('catalog:maker', kwargs={'username': actor.username} )]) global_merge_vars['ACTOR_URL'] = actor_url global_merge_vars['ACTOR_NAME'] = actor.first_name if os.environ.get('DJANGO_SETTINGS_MODULE', '') == 'woot.settings.dev': print("From: "+self.from_email) print("To: "+self.to) print("To Name:"+self.to_name) print("CC: "+self.cc) print("Subject: "+self.subject) print("Mail Type: "+self.mail_type.desc) print("Template: "+self.template) print(global_merge_vars) return msg = EmailMessage(subject=self.subject, from_email=self.from_email, to=[self.to_name + "<" + self.to + ">", ], bcc=[self.cc, 'Alex JV<*****@*****.**>']) msg.template_name = self.template msg.global_merge_vars = global_merge_vars msg.send() self.sent_time = timezone.now() super(SendMail, self).save() except Exception as e: print(e) pass
def send_mandrill_template_mail(template_name, to, global_merge_vars=None, merge_vars=None, content_blocks=None, subject=None, from_email=None, **options): if isinstance(to, six.string_types): to = [to] msg = EmailMessage(subject=subject, from_email=from_email, to=to) msg.template_name = template_name if content_blocks: msg.template_content = content_blocks if global_merge_vars: msg.global_merge_vars = global_merge_vars if merge_vars: msg.merge_vars = merge_vars for option, value in six.iteritems(options): if option not in VALID_DJRILL_OPTIONS: raise ValueError('Invalid option for Mandrill template: %s' % option) setattr(msg, option, value) if not subject: msg.use_template_subject = True if not from_email: msg.use_template_from = True msg.send()
def post(self, request, *args, **kwargs): form_contact = self.form_class(request.POST) success = False if form_contact.is_valid(): date = datetime.today() form_contact.save() success = True from django.core.mail import EmailMessage msg = EmailMessage(subject="R | Contact", from_email=settings.DEFAULT_FROM_EMAIL, to=[settings.DEFAULT_TO_EMAIL]) msg.template_name = "rmp_contact" # A Mandrill template name msg.template_content = { # Content blocks to fill in 'TRACKING_BLOCK': "<a href='.../*|TRACKINGNO|*'>track it</a>" } msg.global_merge_vars = { # Merge tags in your template 'SITE_URL': settings.SITE_URL, 'STATIC_URL': settings.STATIC_URL, 'TXT_NAME': request.POST['name'], 'TXT_EMAIL': request.POST['email'], 'TXT_MESSAGE': request.POST['message'], 'TXT_YEAR': date.year } msg.merge_vars = { # Per-recipient merge tags 'a@.': {'NAME': "Pat"}, } msg.send() return render(request, self.template_name, { 'form_contact': form_contact, 'success': success })
def send_bookmark_reminder_email(): for profile in UserProfile.objects.all(): user = profile.user # Get all bookmarked events ending in the next 7 days from today # What day will it be 7 days from now- now = timezone.now().date() seven_days = now + timedelta(days=7) my_bookmarks = Bookmark.objects.filter(user=user, event__end_date__gte=now, event__end_date__lte=seven_days) if my_bookmarks: bookmarked_events = [] for bookmark in my_bookmarks: bookmarked_events.append({"EVENT_TITLE": bookmark.event.title, "IMAGE_URL": bookmark.event.image.url, "EVENT_DESCRIPTION": bookmark.event.description, "EVENT_URL": "http://www." + Site.objects.get_current().domain + bookmark.event.get_absolute_url(), "END_DATE": "{}".format(bookmark.event.end_date.strftime("%A, %d. %B"))}) subject = "Events ending soon on Alltoez" msg = EmailMessage(subject=subject, from_email=("Alltoez", "*****@*****.**"), to=[user.email]) msg.template_name = "Bookmarked Events Ending" msg.global_merge_vars = { "USER_NAME": profile.first_name, "events": bookmarked_events, } msg.send()
def get_redtri_events(): today = datetime.today() try: redtri_events = redtri.get_events(EVENTS_NUM_DAYS_SCRAPE_LOOK_AHEAD) redtri_events_context = [] for parsed_event in redtri_events: title = parsed_event.get('title', None) url = parsed_event.get('orig_link', None) redtri_events_context.append({"event_url": url, "event_title": title}) if redtri_events_context and not settings.DEBUG and False: # Now send mail subject = "Alltoez | Redtri events | {}".format(today.strftime("%A, %d. %B")) msg = EmailMessage(subject=subject, from_email=("No Reply", "*****@*****.**"), to=["*****@*****.**", "*****@*****.**"]) msg.template_name = "RedTri Events" msg.global_merge_vars = { "events": redtri_events_context, "CHECK_DATE": "{}".format(today.strftime("%A, %d. %B")), "redtri_event_count": len(redtri_events_context) } msg.send() except Exception: pass
def get_expired_events(): today = datetime.today() expired_events_qs = Event.objects.filter(end_date=datetime.today()) if expired_events_qs: expired_events = [] for event in expired_events_qs: expired_events.append({ "event_url": "http://www." + Site.objects.get_current().domain + event.get_absolute_url(), "event_title": event.title, "image_url": event.image.url }) if not settings.DEBUG: # Now send mail subject = "Alltoez | Expired Events | {}".format( today.strftime("%A, %d. %B")) msg = EmailMessage( subject=subject, from_email=("No Reply", "*****@*****.**"), to=["*****@*****.**", "*****@*****.**"]) msg.template_name = "Expired Events" msg.global_merge_vars = { "events": expired_events, "CHECK_DATE": "{}".format(today.strftime("%A, %d. %B")), "expired_count": expired_events_qs.count() } msg.send()
def send_mandrill_template_mail( template_name, to, global_merge_vars=None, merge_vars=None, content_blocks=None, subject=None, from_email=None, **options ): if isinstance(to, six.string_types): to = [to] msg = EmailMessage(subject=subject, from_email=from_email, to=to) msg.template_name = template_name if content_blocks: msg.template_content = content_blocks if global_merge_vars: msg.global_merge_vars = global_merge_vars if merge_vars: msg.merge_vars = merge_vars for option, value in six.iteritems(options): if option not in VALID_DJRILL_OPTIONS: raise ValueError("Invalid option for Mandrill template: %s" % option) setattr(msg, option, value) if not subject: msg.use_template_subject = True if not from_email: msg.use_template_from = True msg.send()
def get_redtri_events(): today = datetime.today() try: redtri_events = redtri.get_events(EVENTS_NUM_DAYS_SCRAPE_LOOK_AHEAD) redtri_events_context = [] for parsed_event in redtri_events: title = parsed_event.get('title', None) url = parsed_event.get('orig_link', None) redtri_events_context.append({ "event_url": url, "event_title": title }) if redtri_events_context and not settings.DEBUG and False: # Now send mail subject = "Alltoez | Redtri events | {}".format( today.strftime("%A, %d. %B")) msg = EmailMessage( subject=subject, from_email=("No Reply", "*****@*****.**"), to=["*****@*****.**", "*****@*****.**"]) msg.template_name = "RedTri Events" msg.global_merge_vars = { "events": redtri_events_context, "CHECK_DATE": "{}".format(today.strftime("%A, %d. %B")), "redtri_event_count": len(redtri_events_context) } msg.send() except Exception: pass
def send_custom_email_mandrill(email_to, temp_vars): msg = EmailMessage(to=[email_to]) msg.template_name = "test-email" # slug from Mandrill msg.global_merge_vars = temp_vars msg.use_template_subject = True msg.use_template_from = True msg.send()
def tournaments_pay_team(pp_obj, data_post): tournament = Tournament.objects.get(id=pp_obj.id_event) team = Teams.objects.get(id=pp_obj.id_payer) if tournament and team: if float(data_post['mc_gross']) == float( tournament.price) and data_post['mc_currency'] == "EUR": pp_obj.txn_id = data_post['txn_id'] team.txn_id = data_post['txn_id'] pp_obj.verified = True pp_obj.save() team.save() msg = EmailMessage(subject="Inscription valide", from_email="*****@*****.**", to=[team.admin.email], bcc=admins_mails) msg.global_merge_vars = { 'NAME1': team.admin.username, 'NAMETOURNOI': tournament.name } msg.template_name = "base" ret = msg.send() logger.debug("It worked in teams !!!") if ret != 1: logger.debug( "Message non envoye a: {} pour le tournoi: {}".format( team.admin.email, tournament.name)) return HttpResponse("Payment accepted") else: logger.debug("No tournament ({}) or team.admin ({})".format( tournament, team.admin)) return HttpResponse("There was shit in da payment")
def ipn(request): admins_mails = [admin[1] for admin in ADMINS] if request.method == 'POST': data = dict(request.POST) for k in data: data[k] = data[k][0].encode('utf-8') tmp = urllib.urlopen("https://www.paypal.com/cgi_bin/websrc", 'cmd=_notify-validate&' + urllib.urlencode(data)).read() if tmp == 'VERIFIED': if data['payment_status'] == 'Completed' and 'custom' in data.keys() and data['custom']: team = Teams.objects.get(id=int(data['custom'])) if not Teams.objects.filter(txn_id=data['txn_id']) and data[ 'receiver_email'] == team.tournament.receiver_email and float(data['mc_gross']) == float( team.tournament.price) and data['payment_status'] == 'Completed' and data[ 'mc_currency'] == 'EUR': team.verified = True team.txn_id = data['txn_id'] team.save() msg = EmailMessage(subject="Inscription valide", from_email="*****@*****.**", to=[team.admin.email], bcc=admins_mails) msg.global_merge_vars={'NAME1' : team.admin.username, 'NAMETOURNOI' : team.tournament.name} msg.template_name="base" msg.send() return HttpResponse("team verified") logger.debug("almost") return HttpResponse("team not valid") else: logger.debug("ret") return HttpResponse("OK") else: logger.debug("get") return HttpResponse( '<form method="post" action="https://www.sandbox.paypal.com/cgi-bin/webscr" class="paypal-button" target="_top" style="opacity: 1;"><div class="hide" id="errorBox"></div><input type="hidden" name="button" value="buynow"><input type="hidden" name="business" value="*****@*****.**"><input type="hidden" name="item_name" value="tournoi"><input type="hidden" name="quantity" value="1"><input type="hidden" name="amount" value="50"><input type="hidden" name="currency_code" value="EUR"><input type="hidden" name="shipping" value="0"><input type="hidden" name="tax" value="0"><input type="hidden" name="notify_url" value="http://danstonpi.eu/api/ret/ipn"><input type="hidden" name="cancel_url" value="http://danstonpi.eu/cancel"><input type="hidden" name="return_url" value="http://danstonpi.eu/done"><input type="hidden" name="cmd" value="_xclick"><input type="hidden" name="bn" value="JavaScriptButton_buynow"><input type="hidden" name="custom" value="26"/><button type="submit" class="paypal-button large">Buy Now</button></form>')
def sendActivationEmail(email=None, activation_key=None): msg = EmailMessage(subject="Activacion a GusYa!", from_email="*****@*****.**", to=[email]) msg.template_name = "Activate" msg.global_merge_vars = { 'KEY': activation_key, } msg.send()
def send(self, template_name, from_email, recipient_list, context, cc=None, bcc=None, fail_silently=False, headers=None, template_prefix=None, template_suffix=None, template_dir=None, file_extension=None, **kwargs): msg = EmailMessage(from_email=from_email, to=recipient_list) msg.template_name = template_name msg.global_merge_vars = context msg.fail_silently = fail_silently if cc: msg.cc = cc if bcc: msg.bcc = bcc msg.use_template_subject = kwargs.get('use_template_subject', True) msg.use_template_from = kwargs.get('use_template_from', True) msg.async = kwargs.get('async', True) try: msg.send() except Exception as e: if not fail_silently: raise return msg.extra_headers.get('Message-Id', None)
def invite(request): #template = "tclassroom/invite_join_course" message = request.POST['message'] userid = request.user.id username = request.user.username parsed_mails = request.POST['list'].split('#') emails = [] me = User.objects.get(id=userid) email = me.email already = CollaboratorInvitation.objects.filter(fromuser=me, accepted=False) if (already.count () > 10): return dump_and_render_json(request, dict({'status' : 'error', 'code' : 'limited exceeded'})) tolist = [] for item in parsed_mails : append = True if (item == email): continue for sent in already : if (sent.usermail == item) : append = False break if append : tolist.append(item) emails.append(CollaboratorInvitation (usermail=item, fromuser=me)) if len(emails) == 0 : return dump_and_render_json(request, dict({'status' : 'error', 'code' : 'limited exceeded'})) #subject = render_to_string('teacher_invitation_subject.txt'.format(template)) mandrillappmessage = EmailMessage(subject=username + " Invitation!", to=tolist, from_email=settings.EMAIL_NO_REPLY) mandrillappmessage.template_name = "TEACHER_COLLABORATION_INVITATION" mandrillappmessage.global_merge_vars = { # Merge tags in your template 'ACTIVATE': " show invitation", 'MESSAGE': message } merge_vars = {} CollaboratorInvitation.objects.bulk_create(emails) time_threshold = datetime.now() - timedelta(seconds=3) invitations = CollaboratorInvitation.objects.filter(sent_at__gt=time_threshold, fromuser=me) value = {} for invitation in invitations : value = model_to_dict(invitation, fields = ['usermail']) url = request.build_absolute_uri (reverse("teacher_invitation_response", args=[invitation.id])) value.update ({ 'URL' : url}) merge_vars[invitation.usermail] = value mandrillappmessage.merge_vars = merge_vars """ message.merge_vars = { '*****@*****.**': {'offer': "15% off anvils"}, '*****@*****.**': {'offer': "instant tunnel paint"} } msg = EmailMultiAlternatives(subject, "body", settings.EMAIL_NO_REPLY, bcc=emails) msg.attach_alternative(body, "text/html") response_ = msg.send() """ try : mandrillappmessage.send() return render_json(request, mandrillappmessage.mandrill_response) except djrill.MandrillAPIError as ex: return render_json(request, mandrillappmessage.mandrill_response)
def mandrill_bad_request(error, id): msg = EmailMessage(subject="Bad Request QueroMeia", from_email="QueroMeia <*****@*****.**>", to=["*****@*****.**"]) msg.template_name = "bad-request" msg.global_merge_vars = {'ERROR': error, 'ID': id} msg.send() return None
def mandrill_recovery(email, code): msg = EmailMessage(subject="Seu ingresso voltou!", from_email="QueroMeia <*****@*****.**>", to=[email]) msg.template_name = "recovery" msg.global_merge_vars = {'CODE': str(code)} msg.send() return None
def send_email(to, subject, template_name, global_merge_vars): """Envia emails.""" msg = EmailMessage( subject=subject, from_email=settings.DEFAULT_FROM_EMAIL, to=to) msg.template_name = template_name msg.global_merge_vars = global_merge_vars msg.send()
def send_follow_up(self): msg = EmailMessage(to=[self.stripe_name], bcc=[email[1] for email in settings.MANAGERS]) msg.template_name = 'gift-roulette-follow-up' msg.global_merge_vars = { 'STORY': self.get_description_text(), 'LINK': 'https://giftroulette.me/gift/{private_hash}/'.format( private_hash=self.private_hash )} msg.send()
def send_mandrill_email(self,mandrill_template_name, context_dict): """ Send a mandrill template email to the owner of self. :param mandrill_template_name: str """ msg = EmailMessage(to=[self.user.email],) msg.template_name = mandrill_template_name msg.global_merge_vars = context_dict msg.send()
def notify_user(email, subject, body, user=''): msg = EmailMessage(subject=subject, from_email="CrowdCafe <*****@*****.**>", to=[email]) msg.template_name = "CONTACT_USER" msg.global_merge_vars = { 'MESSAGE': body, "USER": user } msg.async = True msg.send()
def _send_notify(user, filename, subject, body, file_desc, url=None): msg = EmailMessage( subject=subject, from_email="*****@*****.**", body=body, to=[user.email] ) msg.template_name = "DARG_FILE_DOWNLOAD" msg.global_merge_vars = {'FILE_DESC': file_desc, 'URL': url} msg.send()
def send_mandrill_email(self, mandrill_template_name, context_dict): """ Send a mandrill template email to the owner of self. :param mandrill_template_name: str """ from django.core.mail import EmailMessage msg = EmailMessage(to=[self.user.email], ) msg.template_name = mandrill_template_name msg.global_merge_vars = context_dict msg.send()
def send_email_from_template(to_profile, template_name, global_merge_vars=None, merge_vars=None, from_name=None, from_email=None, subject=None, sent_before_control=False): log_type = template_name if sent_before_control: if mail_is_sent_before(to_profile, log_type): return False if to_profile.mail_subscription is False: return False msg = EmailMessage( to=[to_profile.email, ] ) msg.template_name = template_name if not global_merge_vars: global_merge_vars = {} msg.global_merge_vars = global_merge_vars if merge_vars: msg.merge_vars = merge_vars msg.subject = subject if not from_email: from_email = settings.MAILING_FROM_EMAIL if not from_name: from_name = settings.MAILING_FROM_NAME msg.from_email = from_email msg.from_name = from_name msg.send() mandrill_id, mandrill_status = "-1", "unknown" try: if msg.mandrill_response and len(msg.mandrill_response): mandrill_id, mandrill_status = msg.mandrill_response[0].get("_id"), msg.mandrill_response[0].get("status") except Exception as error: pass mail_log = MailLog( to=to_profile, type=log_type, mandrill_response_id=mandrill_id, mandrill_status=mandrill_status, ) mail_log.save()
def _setup_message(self): msg = EmailMessage(subject=self.subject, from_email=settings.DEFAULT_FROM_EMAIL, to=self.to) if self.template: msg.template_name = self.template["name"] msg.global_merge_vars = self.template["global_merge_vars"] msg.merge_vars = self.template.get("merge_vars", {}) msg.merge_language = self.template.get("merge_language", "mailchimp") return msg
def post(self, request): from_email = request.DATA['fromEmail'] from_name = request.DATA['fromName'] to_email = request.DATA['toEmail'] to_name = request.DATA['toName'] email = EmailMessage(to=[to_email], from_email=from_email) email.template_name = "send-to-friend" email.global_merge_vars = {'FROMFRIEND': from_name, \ 'TOFRIEND': to_name} email.use_template_subject = True email.send() return HttpResponse(status=status.HTTP_204_NO_CONTENT)
def send_mail(to, template_name, subject=None, from_email=None, local_vars=None, global_vars=None): subject = subject or EMAIL_SUBJECTS[template_name] from_email = from_email or settings.DEFAULT_FROM_EMAIL local_vars = local_vars or {} global_vars = global_vars or {} msg = EmailMessage(from_email=from_email, to=to, subject=subject) msg.template_name = template_name msg.merge_vars = local_vars msg.global_merge_vars = global_vars return msg.send()
def send_email_payment(email, payment): amount_len = len(str(payment.mount)) amount_str = str(payment.mount) amount_new = amount_str[:amount_len-2] + '.' + amount_str[amount_len-2:] msg = EmailMessage(subject="Recibos Gus", from_email="*****@*****.**", to=[email]) msg.template_name = "payment" msg.global_merge_vars = { 'amount': amount_new, 'description': payment.description, 'card': payment.card.card_number, 'date': payment.creation_date, } msg.send()
def _send_message(self, subject, from_email, to, heading, content): msg = EmailMessage(subject=subject, from_email=from_email, to=to) msg.template_name = "BASIC" # A Mandrill template name msg.template_content = { # Content blocks to fill in 'HEADING': heading, 'CONTENT': content } msg.global_merge_vars = { # Merge tags in your template 'HEADING': heading, 'CONTENT': content } msg.merge_vars = {} msg.send()
def post(self, request): from_email = request.DATA['fromEmail'] from_name = request.DATA['fromName'] to_email = request.DATA['toEmail'] to_name = request.DATA['toName'] email = EmailMessage( to=[to_email], from_email=from_email ) email.template_name = "send-to-friend" email.global_merge_vars = {'FROMFRIEND': from_name, \ 'TOFRIEND': to_name} email.use_template_subject = True email.send() return HttpResponse(status=status.HTTP_204_NO_CONTENT)
def sendSystemEmail(user, subject, template_name, merge_vars): merge_vars["first_name"] = user.first_name merge_vars["last_name"] = user.last_name merge_vars["site_url"] = settings.SITE_URL merge_vars["current_year"] = timezone.now().year merge_vars["company"] = "CoderDojoChi" msg = EmailMessage(subject=subject, from_email=settings.DEFAULT_FROM_EMAIL, to=[user.email]) msg.template_name = template_name msg.global_merge_vars = merge_vars msg.inline_css = True msg.use_template_subject = True msg.send()
def save(self, *args, **kwargs): """ Sends confirmation email about appointment """ super(Appointment, self).save(*args, **kwargs) email = EmailMessage( to=[self.participant.email] ) email.template_name = "appointment-email" email.global_merge_vars = {'TEST': self.test.title, \ 'DATE': self.date.__format__('%A, %B %-d, %Y'), \ 'TIME': self.time.__format__('%-I:%M %p')} email.use_template_subject = True email.use_template_from = True email.send()
def provider_post_save(sender, instance, **kwargs): message = instance msg = EmailMessage(to=['*****@*****.**']) msg.template_name = 'mark2cure-support' msg.global_merge_vars = { 'NAME': 'Unauthenicated User', 'TEXT': message.text, 'REFERRAL': message.referral } if message.user: msg.cc = [message.user.email] msg.global_merge_vars['NAME'] = message.user.username msg.send()
def send_initial_password_mail(user, password): """ task sending out email with new passwword via mandrill """ msg = EmailMessage( subject=_('Welcome to Das Aktienregister - Your new password'), from_email="*****@*****.**", to=[user.email]) msg.template_name = "DARG_WELCOME_PASSWORD" msg.template_content = {} msg.global_merge_vars = { 'NEW_PASSWORD': password, } msg.merge_vars = {} msg.send()
def handle(self, *args, **options): msg = EmailMessage( subject='Test', from_email='*****@*****.**', to=['*****@*****.**'] ) msg.template_name = "debit" msg.global_merge_vars = { 'TITLE': 'Домашний учет', 'LINK': reverse('money:index'), 'USERNAME': '******', 'OPERATION_USER': '******', 'OPERATION_ACCOUNT': 'Личный (Олег)', 'OPERATION_AMOUNT': 40000, 'COPYRIGHT': '2015 © Иванов Олег', } msg.send()
def email_user(self, subject, from_email=None, **kwargs): """ Sends an email to this User. """ email = EmailMessage(to=[self.email], from_email=from_email) email.template_name = "forgot-password" email.use_template_subject = True email.use_template_from = True email.global_merge_vars = { "SITE_NAME": Site.objects.get_current().name, "RESET_TOKEN": self.password_reset_token } email.send(fail_silently=False)
def sendSystemEmail(user, subject, template_name, merge_vars): merge_vars['first_name'] = user.first_name merge_vars['last_name'] = user.last_name merge_vars['site_url'] = settings.SITE_URL merge_vars['current_year'] = timezone.now().year merge_vars['company'] = 'CoderDojoChi' msg = EmailMessage(subject=subject, from_email=settings.DEFAULT_FROM_EMAIL, to=[user.email]) msg.template_name = template_name msg.global_merge_vars = merge_vars msg.inline_css = True msg.use_template_subject = True msg.send()
def send_welcome_mail(sender, email_address, **kwargs): user = email_address.user emailId = user.first_name + " " + user.last_name + "<" +\ email_address.email + ">" msg = EmailMessage(subject="Welcome to Makeystreet", from_email="Alex J V<*****@*****.**>", to=[emailId], cc=['Numaan Ashraf<*****@*****.**>'], bcc=['Alex JV<*****@*****.**>']) msg.template_name = "SignUp" msg.use_template_subject = True msg.use_template_from = True msg.global_merge_vars = { 'USERNAME': user.first_name, } msg.preserve_recipients = True msg.send()
def ipn(request): admins_mails = [admin[1] for admin in ADMINS] if request.method == 'POST': data = dict(request.POST) for k in data: data[k] = data[k][0].encode('utf-8') tmp = urllib.urlopen("https://www.paypal.com/cgi_bin/websrc", 'cmd=_notify-validate&' + urllib.urlencode(data)).read() if tmp == 'VERIFIED': if data['payment_status'] == 'Completed' and 'custom' in data.keys( ) and data['custom']: team = Teams.objects.get(id=int(data['custom'])) if not Teams.objects.filter(txn_id=data['txn_id']) and data[ 'receiver_email'] == team.tournament.receiver_email and float( data['mc_gross']) == float( team.tournament.price) and data[ 'payment_status'] == 'Completed' and data[ 'mc_currency'] == 'EUR': team.verified = True team.txn_id = data['txn_id'] team.save() msg = EmailMessage(subject="Inscription valide", from_email="*****@*****.**", to=[team.admin.email], bcc=admins_mails) msg.global_merge_vars = { 'NAME1': team.admin.username, 'NAMETOURNOI': team.tournament.name } msg.template_name = "base" msg.send() return HttpResponse("team verified") logger.debug("almost") return HttpResponse("team not valid") else: logger.debug("ret") return HttpResponse("OK") else: logger.debug("get") return HttpResponse( '<form method="post" action="https://www.sandbox.paypal.com/cgi-bin/webscr" class="paypal-button" target="_top" style="opacity: 1;"><div class="hide" id="errorBox"></div><input type="hidden" name="button" value="buynow"><input type="hidden" name="business" value="*****@*****.**"><input type="hidden" name="item_name" value="tournoi"><input type="hidden" name="quantity" value="1"><input type="hidden" name="amount" value="50"><input type="hidden" name="currency_code" value="EUR"><input type="hidden" name="shipping" value="0"><input type="hidden" name="tax" value="0"><input type="hidden" name="notify_url" value="http://danstonpi.eu/api/ret/ipn"><input type="hidden" name="cancel_url" value="http://danstonpi.eu/cancel"><input type="hidden" name="return_url" value="http://danstonpi.eu/done"><input type="hidden" name="cmd" value="_xclick"><input type="hidden" name="bn" value="JavaScriptButton_buynow"><input type="hidden" name="custom" value="26"/><button type="submit" class="paypal-button large">Buy Now</button></form>' )
def send_debit_email(user, operation): """ :type user: User :type operation: Operation :return: """ msg = EmailMessage(to=[user.email]) msg.template_name = "debit" msg.global_merge_vars = { 'TITLE': 'Домашний учет', 'LINK': reverse('money:index'), 'USERNAME': user.first_name, 'OPERATION_USER': operation.user.first_name, 'OPERATION_ACCOUNT': operation.account.title, 'OPERATION_AMOUNT': intcomma(round(operation.amount, 0)), 'COPYRIGHT': '2015 © Иванов Олег', } msg.send()
def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse subject='New Member Application Received' message= ("A new request for membership has been posted through l'Union Alsacienne Website." + "\r\n\n" + "Name: " + form.cleaned_data['first_name'] + " " + form.cleaned_data['last_name'] + "\r\n" + "Address: " + form.cleaned_data['address'] + "\n" + form.cleaned_data['city'] + " " + form.cleaned_data['zip'] + " " + form.cleaned_data['state'] + "\r\n\n" + "Occupation: " + form.cleaned_data['occupation'] + "\n" + " at " + form.cleaned_data['company'] + "\r\n\n" + "Mobile phone: " + form.cleaned_data['mobile_phone'] + "\n" + " Home phone: " + form.cleaned_data['home_phone'] + "\n" + " Fax: " + form.cleaned_data['home_fax'] + "\r\n\n" + "E-mail: " + form.cleaned_data['email'] + "\r\n\n" + "Date of birth: " + str(form.cleaned_data['date_of_birth']) + "\n" + "Place: " + form.cleaned_data['birth_place'] + "\n" + "If not from Alsace: " + form.cleaned_data['if_not_alsace_Reason'] + "\r\n\n" + "Venue: " + form.cleaned_data['venue'] + "\n" + "Date: " + str(form.cleaned_data['date_membership_application']) + "\n" + " Signature: " + form.cleaned_data['signature'] + "\r\n\n" + "First sponsor: " + form.cleaned_data['first_sponsor'] + "\n" + "Second sponsor: " + form.cleaned_data['second_sponsor'] + "\r\n\n" + "Posted through l'Union Alsacienne Website"+ "\r\n") sender='*****@*****.**' recipient=['*****@*****.**','*****@*****.**','*****@*****.**'] email=EmailMessage(subject,message,sender,recipient) email.send() #send_mail(subject,message,sender,recipient,fail_silently=False) msg = EmailMessage(subject="Thank you for your application", from_email="*****@*****.**", to=[form.cleaned_data['email']]) msg.template_name = "Membership_Confirmation_MC2" # A Mandrill template name msg.global_merge_vars = { # Merge tags in your template 'CURRENT_YEAR': str(datetime.date.today().year), 'COMPANY': 'Union Alsacienne of New York' } msg.merge_vars = { # Per-recipient merge tags form.cleaned_data['email'] : {'first_name': form.cleaned_data['first_name'],'state' : form.cleaned_data['state'],'zip' : form.cleaned_data['zip'],'city' : form.cleaned_data['city'],'address' : form.cleaned_data['address'],'last_name': form.cleaned_data['last_name'],}, } msg.send() form.save(True) return HttpResponseRedirect('/membership/payment?type=1') #redirect after post
def send_post(post): when = post.day_of_week + ', ' + post.show_date if post.not_all_day: when = when + ' at ' + post.show_begin_time email = EmailMessage(to=[post.author.email]) email.template_name = 'post' email.global_merge_vars = { 'content': post.content, 'description': post.description_event, 'location': post.location_event, 'when': when } email.send_at = post.notify_when email.use_template_subject = True email.use_template_from = False email.send(fail_silently=False) response = email.mandrill_response[0] print response return response
def tournaments_pay_team(pp_obj, data_post): tournament = Tournament.objects.get(id=pp_obj.id_event) team = Teams.objects.get(id=pp_obj.id_payer) if tournament and team: if float(data_post['mc_gross']) == float(tournament.price) and data_post['mc_currency'] == "EUR": pp_obj.txn_id = data_post['txn_id'] team.txn_id = data_post['txn_id'] pp_obj.verified = True pp_obj.save() team.save() msg = EmailMessage(subject="Inscription valide", from_email="*****@*****.**", to=[team.admin.email], bcc=admins_mails) msg.global_merge_vars= {'NAME1': team.admin.username, 'NAMETOURNOI': tournament.name} msg.template_name= "base" ret = msg.send() logger.debug("It worked in teams !!!") if ret != 1: logger.debug("Message non envoye a: {} pour le tournoi: {}".format(team.admin.email, tournament.name)) return HttpResponse("Payment accepted") else: logger.debug("No tournament ({}) or team.admin ({})".format(tournament, team.admin)) return HttpResponse("There was shit in da payment")
def save(self, *args, **kwargs): """ Override of save to make sure hash is created with ID Sends email once this is done """ super(FormAPI, self).save(*args, **kwargs) if self.hashInit == '': hasher = hashlib.sha512() hasher.update(self.createHASH()) self.hashInit = hasher.hexdigest() formapi = FormAPI.objects.get(pk = self.id) formapi.hashInit = self.hashInit formapi.save() email = EmailMessage( to=[self.email] ) email.template_name = "confirmation email" link = self.hashInit email.global_merge_vars = {'URL': link} email.use_template_subject = True email.use_template_from = True email.send()
def get_expired_events(): today = datetime.today() expired_events_qs = Event.objects.filter(end_date=datetime.today()) if expired_events_qs: expired_events = [] for event in expired_events_qs: expired_events.append({"event_url": "http://www." + Site.objects.get_current().domain + event.get_absolute_url(), "event_title": event.title, "image_url": event.image.url}) if not settings.DEBUG: # Now send mail subject = "Alltoez | Expired Events | {}".format(today.strftime("%A, %d. %B")) msg = EmailMessage(subject=subject, from_email=("No Reply", "*****@*****.**"), to=["*****@*****.**", "*****@*****.**"]) msg.template_name = "Expired Events" msg.global_merge_vars = { "events": expired_events, "CHECK_DATE": "{}".format(today.strftime("%A, %d. %B")), "expired_count": expired_events_qs.count() } msg.send()
def notifyMoneyAdmin(account, status, info=''): message = _good if status==1: message = _bad if status ==2: message = _no_credit if status ==3: message = _units_completed if account.email: emails = [account.email] elif account.creator.email: emails = [account.creator.email] else: return msg = EmailMessage(subject=message[0], from_email="CrowdCafe <*****@*****.**>", to=emails) msg.template_name = "MONEY_ADMIN" txt = str(message[1] % info) msg.global_merge_vars = { 'MESSAGE': txt, "USER": account.title } msg.async = True msg.send()
def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse subject='New Friendship Application Received' message=("A new request to become a friend has been posted through l'Union Alsacienne Website"+ "\n\n" + "Name: " + form.cleaned_data['first_name'] + " " + form.cleaned_data['last_name'] +"\n\n" + "Email: " + form.cleaned_data['email'] + "\n\n" + "Address: " + form.cleaned_data['address'] + "\n" + form.cleaned_data['city'] + " " + form.cleaned_data['zip'] + " " + form.cleaned_data['state'] + "\r\n\n" + "Posted through l'Union Alsacienne Website"+ "\r\n") sender='*****@*****.**' recipient=['*****@*****.**','*****@*****.**','*****@*****.**'] email=EmailMessage(subject,message,sender,recipient) email.send() #send_mail(subject,message,sender,recipient,fail_silently=False) msg = EmailMessage(subject="Thank you for your application", from_email="*****@*****.**", to=[form.cleaned_data['email']]) msg.template_name = "Friendship_Confirmation_MC2" # A Mandrill template name msg.global_merge_vars = { # Merge tags in your template 'CURRENT_YEAR': str(datetime.date.today().year), 'COMPANY': 'Union Alsacienne of New York' } msg.merge_vars = { # Per-recipient merge tags form.cleaned_data['email'] : {'first_name': form.cleaned_data['first_name'],'state' : form.cleaned_data['state'],'zip' : form.cleaned_data['zip'],'city' : form.cleaned_data['city'],'address' : form.cleaned_data['address'],'last_name': form.cleaned_data['last_name'],}, } msg.send() form.save(True) return HttpResponseRedirect('/membership/payment?type=2')
def send_pud(pud): email = EmailMessage(to=[pud.author.email]) email.template_name = 'pud' email.global_merge_vars = { 'content': pud.content, 'priority': pud.priority } email.send_at = pud.created_at + datetime.timedelta(days=pud.notify_when) email.use_template_subject = True email.use_template_from = False email.send(fail_silently=False) if pud.need_repeat: if pud.repeat == 'Daily': email.send_at = email.send_at + datetime.timedelta(days=1) elif pud.repeat == 'Weekly': email.send_at = email.send_at + datetime.timedelta(weeks=1) email.send(fail_silently=False) response = email.mandrill_response[0] print response return response
def invite(request): #template = "tclassroom/invite_join_course" message = request.POST['message'] userid = request.user.id username = request.user.username parsed_mails = request.POST['list'].split('#') emails = [] me = User.objects.get(id=userid) email = me.email already = CollaboratorInvitation.objects.filter(fromuser=me, accepted=False) if (already.count() > 10): return dump_and_render_json( request, dict({ 'status': 'error', 'code': 'limited exceeded' })) tolist = [] for item in parsed_mails: append = True if (item == email): continue for sent in already: if (sent.usermail == item): append = False break if append: tolist.append(item) emails.append(CollaboratorInvitation(usermail=item, fromuser=me)) if len(emails) == 0: return dump_and_render_json( request, dict({ 'status': 'error', 'code': 'limited exceeded' })) #subject = render_to_string('teacher_invitation_subject.txt'.format(template)) mandrillappmessage = EmailMessage(subject=username + " Invitation!", to=tolist, from_email=settings.EMAIL_NO_REPLY) mandrillappmessage.template_name = "TEACHER_COLLABORATION_INVITATION" mandrillappmessage.global_merge_vars = { # Merge tags in your template 'ACTIVATE': " show invitation", 'MESSAGE': message } merge_vars = {} CollaboratorInvitation.objects.bulk_create(emails) time_threshold = datetime.now() - timedelta(seconds=3) invitations = CollaboratorInvitation.objects.filter( sent_at__gt=time_threshold, fromuser=me) value = {} for invitation in invitations: value = model_to_dict(invitation, fields=['usermail']) url = request.build_absolute_uri( reverse("teacher_invitation_response", args=[invitation.id])) value.update({'URL': url}) merge_vars[invitation.usermail] = value mandrillappmessage.merge_vars = merge_vars """ message.merge_vars = { '*****@*****.**': {'offer': "15% off anvils"}, '*****@*****.**': {'offer': "instant tunnel paint"} } msg = EmailMultiAlternatives(subject, "body", settings.EMAIL_NO_REPLY, bcc=emails) msg.attach_alternative(body, "text/html") response_ = msg.send() """ try: mandrillappmessage.send() return render_json(request, mandrillappmessage.mandrill_response) except djrill.MandrillAPIError as ex: return render_json(request, mandrillappmessage.mandrill_response)
def invite(request): from django.conf import settings from django.core.urlresolvers import reverse from django.template.loader import get_template from django.template import Context from django.core.mail import EmailMultiAlternatives #, send_mass_mail from django.template.loader import render_to_string result = {'result': None} if request.user.is_authenticated(): if not request.method == 'POST': return dump_and_render_json(request, result) id = request.POST['cid'] course = Course.objects.get(pk=id) template = "tclassroom/invite_join_course" subscribe_url = reverse("app_course_subscribe", args=[id]) subject = render_to_string('{0}_subject.txt'.format(template)) message = request.POST['text'] username = request.user.username # remove superfluous line breaks subject = " ".join(subject.splitlines()).strip() html = get_template('{0}_body.html'.format(template)) body = html.render( Context({ message: message, username: username, subscribe_url: subscribe_url })).strip() list = request.POST['list'].split('#') """ # send mass_mail datatuple = () for item in list : datatuple += (subject, body, settings.EMAIL_NO_REPLY, [item]) datatuple = (datatuple,) response_ = send_mass_mail(datatuple) result = {'result' : response_} """ emails = [] for item in list: emails.append(item) """ msg = EmailMultiAlternatives(subject, "body", settings.EMAIL_NO_REPLY, bcc=emails) msg.attach_alternative(body, "text/html") response_ = msg.send() """ from django.core.mail import EmailMessage from django.utils.translation import ugettext_lazy as _ msg = EmailMessage(subject=subject, from_email="*****@*****.**", to=emails) msg.template_name = "invitation" # A Mandrill template name """ msg.template_content = { # Content blocks to fill in 'TRACKING_BLOCK': "<a href='.../*|TRACKINGNO|*'>track it</a>" } """ hello = unicode(_("Hello")) subscribe = unicode(_("Activate")) msg.global_merge_vars = { # Merge tags in your template 'MESSAGE': message, 'URL': request.build_absolute_uri(subscribe_url), 'TEACHER': username, 'Hello': hello, 'ACTIVATE': subscribe } """ msg.merge_vars = { # Per-recipient merge tags '*****@*****.**': {'NAME': "Pat"}, '*****@*****.**': {'NAME': "Kim"} } """ result = msg.send() return dump_and_render_json(request, result) else: return dump_and_render_json(request, result)