Example #1
0
    def post(self, request, format=None):
        data = json.loads(request.body)
        lesson = data['lesson']
        account = data['account']
        print("lesson : %s" % lesson)
        print("account : %s" % account['email'])
        mail = EmailMultiAlternatives(
            subject="Your Subject",
            body="This is a simple text email body.",
            from_email="*****@*****.**",
            to=["*****@*****.**"],
            headers={"Reply-To": "*****@*****.**"})
        # Add template
        mail.template_id = 'f6581133-5c0b-4cc1-9a86-96a8bcd0db06'

        # Replace substitutions in sendgrid template
        mail.substitutions = {
            '%type%': 'Hatha',
            '%date%': 'mercredi 28 juin',
            '%heure%': '11h30'
        }

        # Add categories
        mail.categories = [
            'confirmation',
        ]

        mail.send()
        return Response({
            'status': 'OK',
            'message': 'Email sent'
        },
                        status=status.HTTP_200_OK)
Example #2
0
	def _send_invite(self, request, user, ticket):

		callback = request.build_absolute_uri(reverse('access_accept', args=(ticket.uid,)))
		message = _("This email is to invite you to administrate the COVID|APP website. To accept the invitation, click the following link:")

		# A text/html alternative is required by SendGrid. We can't send the email
		# with some arguments that are already defined by the template. See below,
		# near attach_alternatives
		mail = EmailMultiAlternatives(
			subject=_('Welcome'),
			body='%s: %s' % (message, callback,),
			from_email=require_setting('DEFAULT_FROM_EMAIL'),
			to=[user.email],
			headers={
				'Reply-To': require_setting('DEFAULT_FROM_EMAIL')
			}
		)

		mail.template_id = require_setting('COVIDOFF_INVITATION_EMAIL_TEMPLATE')
		mail.substitutions = {
			'-callback-': callback
		}

		# A text/html alternative is required to load the HTML template created on SendGrid,
		# but it doesn't do anything besides that. This content is not used.
		mail.attach_alternative("<p>%s: <a href='%s'>%s</a></p>" % (message, callback, callback,), "text/html")
		mail.send()
    def render_mail(self, template_prefix, email, context):
        """
        Renders an e-mail to `email`.  `template_prefix` identifies the
        e-mail that is to be sent, e.g. "password_reset_key/email_confirmation"
        """
        subject = render_to_string("{0}_subject.txt".format(template_prefix),
                                   context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()
        subject = self.format_email_subject(subject)

        from_email = self.get_from_email()

        bodies = {}
        for ext in ["html", "txt"]:
            try:
                template_name = "{0}_message.{1}".format(template_prefix, ext)
                bodies[ext] = render_to_string(template_name, context).strip()
            except TemplateDoesNotExist:
                if ext == "txt" and not bodies:
                    # We need at least one body
                    raise
        if "txt" in bodies:
            msg = EmailMultiAlternatives(subject, bodies["txt"], from_email,
                                         [email])
            if "html" in bodies:
                msg.attach_alternative(bodies["html"], "text/html")
        else:
            msg = EmailMessage(subject, bodies["html"], from_email, [email])
            msg.content_subtype = "html"  # Main content is now text/html

        msg.template_id = settings.SENDGRID_TEMPLATE_IDS[template_prefix]
        msg.substitutions = self.context_to_subs(context)
        return msg
Example #4
0
def mail_newsletter(recipients, mail):
    email_context = {
        'title': mail.subject,
        'message': mail.text,
        'base_url': settings.EMAIL_ABS_URL,
        'sponsors': Sponsor.objects.all(),
    }
    email_html = render_to_string('newsletter/email_newsletter.html',
                                  email_context)
    email_plaintext = render_to_string('newsletter/email_newsletter.txt',
                                       email_context)
    to = [x.email for x in recipients]
    # Create a map of emails to unsub tokens for the email merge
    unsub_tokens = {
        recipient.email: {
            'unsub_url':
            '{hostname}{path}'.format(
                hostname=settings.EMAIL_ABS_URL,
                path=reverse('unsub_with_id',
                             kwargs={'token': recipient.unsubscribe_token}))
        }
        for recipient in recipients
    }
    sender = '{name} <{email}>'.format(name=mail.sender_name,
                                       email=mail.sender_email)

    email = EmailMultiAlternatives(mail.subject, email_plaintext, sender, to)
    email.attach_alternative(email_html, 'text/html')
    email.merge_data = unsub_tokens
    email.merge_global_data = {'subject': mail.subject}
    email.template_id = '615bcf44-fdfd-4632-8403-38987eb9074b'
    email.send()
Example #5
0
def set_random_password_and_send_email(sender,
                                       instance=None,
                                       created=False,
                                       **kwargs):
    """Set random password and send user an email."""
    if created and not instance.password:
        # Generate random password
        password = User.objects.make_random_password(length=14)
        instance.set_password(password)
        instance.save()

        # Send email with password
        mail = EmailMultiAlternatives(
            subject='Welcome to Strand',
            body=f'Your password is "{password}"',
            from_email='Jacob Wallenberg <*****@*****.**>',
            to=[instance.email],
            headers={},
        )
        mail.template_id = settings.NEW_ACCOUNT_TEMPLATE_ID  # Template ID from Sendgrid
        mail.substitutions = {
            '%email%': instance.email,
            '%password%': password
        }
        mail.attach_alternative(
            '<p><b>Welcome to Strand!</b></p>'
            f'<p>Your password is {password}</p>', 'text/html')
        mail.send()
Example #6
0
	def _send_invite(self, request, user, ticket):

		callback = request.build_absolute_uri(reverse('access_accept', args=(ticket.uid,)))
		message = _("This email is to help you recover your password. If you're not trying to recover your password, please ignore it. In order to continue, click on the following link:")

		# A text/html alternative is required by SendGrid. We can't send the email
		# with some arguments that are already defined by the template. See below,
		# near attach_alternatives
		mail = EmailMultiAlternatives(
			subject=_('Password recovery'),
			body='%s: %s' % (message, callback,),
			from_email=require_setting('DEFAULT_FROM_EMAIL'),
			to=[user.email],
			headers={
				'Reply-To': require_setting('DEFAULT_FROM_EMAIL')
			}
		)

		mail.template_id = require_setting('COVIODFF_RECOVERY_EMAIL_TEMPLATE')
		mail.substitutions = {
			'-callback-': callback
		}

		# A text/html alternative is required to load the HTML template created on SendGrid,
		# but it doesn't do anything besides that. This content is not used.
		mail.attach_alternative("<p>%s: <a href='%s'>%s</a></p>" % (message, callback, callback,), "text/html")
		mail.send()
Example #7
0
 def send_email(self,
                subject=None,
                body=None,
                sg_template_on=False,
                sg_template=None,
                template=None,
                campaign=None):
     from anymail.message import AnymailMessage
     from django.core.mail import send_mail, EmailMultiAlternatives
     from django.utils.html import strip_tags
     if template is not None:
         try:
             html_content = render_to_string(
                 f"contact_management/{template}", self.__dict__)
         except:
             html_content = None
         note = template
     else:
         html_content = None
         note = body
     if html_content is not None:
         plain_content = strip_tags(html_content)
     else:
         plain_content = body
     message = EmailMultiAlternatives(subject, plain_content,
                                      DEFAULT_FROM_EMAIL, [self.email])
     if sg_template_on == True:
         message.template_id = sg_template
         template = sg_template
     message.metadata = {
         "account_id": self.account_name,
         "contact_id": self.id,
         "template": template,
         "campaign": campaign,
         "email_source": "VCM",
         "contact_type": "LEAD",
         "FIRST_NAME": self.first_name,
         "LAST_NAME": self.last_name,
         "ACCOUNT_NAME": self.account_name,
         'DATETIME': datetime.now().isoformat()
     }
     if html_content is not None:
         message.attach_alternative(html_content, "text/html")
     message.track_clicks = True
     message.track_opens = True
     try:
         message.send()
         status = message.anymail_status
         status.message_id
         n = Note(lead=self,
                  date=datetime.now(),
                  note=note,
                  follow_up_date=datetime.now() + timedelta(days=14),
                  contact_type='EMAIL')
         n.save()
         print(f"email sent to {self}")
     except:
         print('message did not send to', self)
Example #8
0
def send(recipients,
         subject,
         template_name=None,
         context=None,
         content=None,
         template_id=None,
         logger=logger,
         sendgrid_templates=settings.SENDGRID_TEMPLATES,
         generic_id=generic_id):
    """
    Send an email to an email address. If there is a SendGrid template id
    configured for the given template name, create substitutions from `context`
    so that `-key-` in the template is replaced by the value of `key` in
    `context`.

    If there is no such SendGrid template, falls back to using a Django
    template in <templates>/email.

    """
    assert template_name or template_id, "missing argument"
    context = {} if context is None else context

    if not template_id:
        try:
            # TODO Use site config for template lookup
            template_id = sendgrid_templates[template_name]
        except KeyError:
            if generic_id:
                try:
                    context = render_generic_body(template_name, context)
                    template_id = generic_id
                except TemplateDoesNotExist:
                    pass

    if not template_id:
        # Fall back to Django templates
        return send_template(recipients, subject, template_name, context)

    substitutions = {"-{}-".format(k): str(v) for k, v in context.items()}
    recipients = recipients if isinstance(recipients, list) else [recipients]

    mail = EmailMultiAlternatives(
        from_email=f"{settings.EMAIL_NAME} <{settings.EMAIL_ADDRESS}>",
        subject=subject,
        body="",
        to=recipients)
    mail.template_id = template_id
    mail.substitutions = substitutions
    mail.alternatives = [(" ", "text/html")]

    if content:
        mail.attach_alternative(content, "text/html")

    mail.send()
    if logger:
        logger.info("Email sent to %s", recipients)
    return True
Example #9
0
def send_welcome_mail(to_mail, **kwargs):
    mail = EmailMultiAlternatives(
        subject="Your Subject",
        body="This is a simple text email body.",
        from_email=FROM_EMAIL,
        to=[to_mail],
    )
    mail.template_id = 'd-c40ad5d0f3a24a7e8dc79f8850d3ef12'
    # mail.substitutions = kwargs
    mail.attach_alternative("<p>a</p>", "text/html")
    mail.send()
Example #10
0
def send(recipients, subject, template_name=None, context=None, content=None,
         template_id=None, logger=logger, 
         sendgrid_templates=settings.SENDGRID_TEMPLATES, generic_id=generic_id):
    """
    Send an email to an email address. If there is a SendGrid template id
    configured for the given template name, create substitutions from `context`
    so that `-key-` in the template is replaced by the value of `key` in
    `context`.

    If there is no such SendGrid template, falls back to using a Django
    template in <templates>/email.

    """
    assert template_name or template_id, "missing argument"
    context = {} if context is None else context

    if not template_id:
        try:
            # TODO Use site config for template lookup
            template_id = sendgrid_templates[template_name]
        except KeyError:
            if generic_id:
                try:
                    context = render_generic_body(template_name, context)
                    template_id = generic_id
                except TemplateDoesNotExist:
                    pass

    if not template_id:
        # Fall back to Django templates
        return send_template(recipients, subject, template_name, context)

    substitutions = {"-{}-".format(k): str(v) for k, v in context.items()}
    recipients = recipients if isinstance(recipients, list) else [recipients]

    mail = EmailMultiAlternatives(
        from_email=f"{settings.EMAIL_NAME} <{settings.EMAIL_ADDRESS}>",
        subject=subject,
        body="",
        to=recipients
    )
    mail.template_id = template_id
    mail.substitutions = substitutions
    mail.alternatives = [(" ", "text/html")]

    if content:
        mail.attach_alternative(content, "text/html")

    mail.send()
    if logger:
        logger.info("Email sent to %s", recipients)
    return True
Example #11
0
 def send_invitation_email(self, to, ctx):
     subject = render_to_string("account/email/invite_user_subject.txt", ctx)
     message = render_to_string("account/email/invite_user.txt", ctx)
     mail = EmailMultiAlternatives(
         subject=subject,
         body=message,
         from_email=settings.DEFAULT_FROM_EMAIL,
         to=to
     )
     mail.attach_alternative(message, "text/html")
     mail.substitutions = self.ctx_to_subs(ctx)
     mail.template_id = settings.SENDGRID_TEMPLATE_IDS['invitation']
     mail.send()
Example #12
0
 def send_confirmation_email(self, to, ctx):
     subject = render_to_string("account/email/email_confirmation_subject.txt", ctx)
     subject = "".join(subject.splitlines())  # remove superfluous line breaks
     message = render_to_string("account/email/email_confirmation_message.txt", ctx)
     mail = EmailMultiAlternatives(
       subject=subject,
       body=message,
       from_email=settings.DEFAULT_FROM_EMAIL,
       to=to
     )
     mail.attach_alternative(message, "text/html")
     mail.substitutions = self.ctx_to_subs(ctx)
     mail.template_id = settings.SENDGRID_TEMPLATE_IDS['confirmation']
     mail.send()
Example #13
0
 def send_password_change_email(self, to, ctx):
     subject = render_to_string("account/email/password_change_subject.txt", ctx)
     subject = "".join(subject.splitlines())
     message = render_to_string("account/email/password_change.txt", ctx)
     mail = EmailMultiAlternatives(
       subject=subject,
       body=message,
       from_email=settings.DEFAULT_FROM_EMAIL,
       to=to
     )
     mail.attach_alternative(message, "text/html")
     mail.substitutions = self.ctx_to_subs(ctx)
     mail.template_id = settings.SENDGRID_TEMPLATE_IDS['password_change']
     mail.send()
def register(request):
    """
    User Registration view
    """

    if request.user.is_authenticated:
        messages.error(request, "You are registered and logged in already!")
        return redirect('index')
    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        if form.is_valid():
            form.save()
            user = User.objects.get(email=request.POST.get('email'))
            # Create new profile for the user
            profile = UserProfile(
                user=user,
                img=request.POST.get('img'),
                phone=request.POST.get('phone'),
                description=request.POST.get('description'),
                terms=True,
            )
            profile.save()
            user = auth.authenticate(username=request.POST.get('username'),
                                     password=request.POST.get('password1'))

            if user:
                auth.login(request, user)
                messages.success(
                    request, "You have successfully registered and logged in")
                mail = EmailMultiAlternatives(
                    subject="Registration",
                    body="Thank you",
                    from_email="The Key Keepers <*****@*****.**>",
                    to=[f"{user.email}"],
                    headers={"Reply-To": "*****@*****.**"})
                mail.template_id = registration_email_template_id
                mail.send()
                messages.success(request,
                                 "Confirmation email has been sent to you.")
                return redirect('profile')
            else:
                messages.error(request, "Unable to log you in!")
        else:
            messages.error(request, "Please fix errors to continue!")
    else:
        form = UserProfileForm()
    return render(request, "register.html", {'form': form})
Example #15
0
def sendgrid_send(recipients,
                  subject,
                  substitutions,
                  template_id,
                  from_email='HackUPC Team <*****@*****.**>'):
    mail = EmailMultiAlternatives(
        subject=subject,
        body='-',
        from_email=from_email,
        to=recipients,
    )
    # Add template
    mail.attach_alternative("<p>Invite email to HackUPC</p>", "text/html")
    mail.template_id = template_id
    # Replace substitutions in sendgrid template
    mail.substitutions = substitutions
    mail.send()
Example #16
0
def send_email(filename, email):
    mail = EmailMultiAlternatives(
        subject="{}".format(filename),
        body="Here's your song mateio.",
        from_email="Youtube downloader <*****@*****.**>",
        to=["{}".format(email)],
        reply_to=["*****@*****.**"],
    )
    mail.template_id = 'c00b4864-3192-4650-9ca4-e83772f929d3'

    mail.attach_alternative("<p>Here's your song!</p>", "text/html")

    with open('{}'.format(filename), 'rb') as file:
        mail.attachments = [('{}'.format(filename), file.read(),
                             'application/mp3')]

    mail.send()
    def send_pdf(params):
        mail = EmailMultiAlternatives(
            subject=params['subject'],
            body=params['body'],
            from_email="The Key Keepers <*****@*****.**>",
            to=params['to'],
            headers={"Reply-To": "*****@*****.**"})
        mail.template_id = params['template_id']

        pdf = Invoice.render_to_file('invoice.html', params)

        with open(str(pdf[1]), 'rb') as file:
            mail.attachments = [(str(pdf[0]), file.read(), 'application/pdf')]

        try:
            mail.send()
        except Exception as e:
            print(e)
Example #18
0
def send_mail(
    subject: str,
    html_body: str,
    from_email: str,
    to: List[str],
    categories: List[str] = None,
    reply_to: str = None,
    headers: dict = None,
    preheader: str = None,
    template_id: str = None,
):
    """Send mail using the dynamic template specified by template_id.

    This template should include these variables:
    - Subject: {{ subject }}
    - Preheader: {{ preheader }}
    - Somewhere in the template: {{{ body }}}

    Tip: to display a name for the from_email, use this format:
    - `"Name" <*****@*****.**>`
    """
    if headers is None:
        headers = dict()
    headers["Reply-To"] = reply_to

    raw_body = strip_tags(html_body)
    mail = EmailMultiAlternatives(subject=subject,
                                  body=raw_body,
                                  from_email=from_email,
                                  to=to,
                                  headers=headers)
    if not template_id:
        template_id = settings.TEMPLATE_ID

    mail.template_id = template_id
    mail.dynamic_template_data = dict(body=html_body,
                                      subject=subject,
                                      preheader=preheader)
    if categories:
        mail.categories = categories

    mail.send()
Example #19
0
    def post(self, request, format=None):
        data = json.loads(request.body)

        type = data['type']
        name = data['name']
        email = data['email']
        tel = data['tel']
        message = data['message']

        mail = EmailMultiAlternatives(
            subject="Subject",
            body="Body",
            from_email="*****@*****.**",
            to=["*****@*****.**"],
            headers={"Reply-To": "*****@*****.**"})

        # Add template (ContactMessage)
        mail.template_id = '4f9c3e44-7d6f-4ff8-a8f2-99018e998aff'

        # Replace substitutions in sendgrid template
        mail.substitutions = {
            '%type%': type,
            '%email%': email,
            '%nom%': name,
            '%message%': message,
            '%tel%': tel
        }

        # Add categories
        mail.categories = [
            'contact',
        ]

        mail.send()

        return Response({
            'status': 'OK',
            'message': 'Email sent'
        },
                        status=status.HTTP_200_OK)
Example #20
0
    def send_email(self,
                   subject=None,
                   body=None,
                   sg_template_on=False,
                   sg_template=None,
                   template=None,
                   campaign=None):
        from anymail.message import AnymailMessage
        from django.core.mail import send_mail, EmailMultiAlternatives
        from django.utils.html import strip_tags
        if template is not None:
            try:
                html_content = render_to_string(
                    f"contact_management/{template}", self.__dict__)
            except:
                html_content = None
            note = template
        else:
            html_content = None
            note = body
        if html_content is not None:
            plain_content = strip_tags(html_content)
        else:
            plain_content = body

        message = EmailMultiAlternatives(subject, plain_content,
                                         DEFAULT_FROM_EMAIL, [self.email])

        if sg_template_on == True:
            message.template_id = sg_template
            template = sg_template
            note = f"SENDGRID TEMPLATE {sg_template}"

        message.metadata = {
            "account_id": self.account.id,
            "contact_id": self.id,
            "template": template,
            "campaign": campaign,
            "email_source": "VCM",
            "contact_type": "CONTACT",
            "FIRST_NAME": self.first_name,
            "LAST_NAME": self.last_name,
            "ACCOUNT_NAME": self.account.name,
            'DATETIME': datetime.now().isoformat(),
        }

        if html_content is not None:
            message.attach_alternative(html_content, "text/html")
        message.track_clicks = True
        message.track_opens = True
        try:
            print('we are here')
            print(template)
            message.send()
            print('we just sent??')
            status = message.anymail_status
            status.message_id
            print(status.message_id, 'MID!!')

            n = Note(contact=self,
                     date=datetime.now(),
                     note=note,
                     follow_up_date=datetime.now() + timedelta(days=14),
                     contact_type='EMAIL')
            print(n, 'NOTE')
            n.save()
            print(n.follow_up_date, 'NOTE SAVED')
        except Exception as errors:
            print(errors, 'this is the erro!')
            print('message did not send to', self)
Example #21
0
def drop_ride(request, ride_id):
    user = request.user
    init_User(user.username)
    ride = Rides.objects.get(pk=ride_id)
    rider = Users.objects.get(netid=user.username)
    idnum = str(ride.id)
    context = {
        'start': ride.get_start_destination_display(),
        'end': ride.get_end_destination_display(),
        'time': ride.date_time,
        'netid': user.username,
    }

    if rider.pools.filter(pk=ride_id).exists():
        rider = Users.objects.get(netid=user.username)
        ride.usrs.remove(rider)
        if (ride.usrs.count() > 0):
            ride.seats += 1
        rider.pools.remove(ride)
        ride.save()
        rider.save()

        # list of all the riders
        riders_emails = []
        riders_firstnames = ""
        riders_fullnames = ""
        for rider in ride.usrs.all():
            riders_emails.append(rider.netid + '@princeton.edu')
            riders_firstnames = riders_firstnames + ", " + rider.first_name
            riders_fullnames = riders_fullnames + rider.first_name + " " + rider.last_name + ', '

        riders_firstnames = riders_firstnames.lstrip(', ')
        # put 'and' and delete comma if only two riders
        split_firsts = riders_firstnames.split(', ')
        num_riders = len(split_firsts)
        if num_riders == 2:
            riders_firstnames = (' and ').join(split_firsts)
        elif num_riders > 2:
            riders_firstnames = (', ').join(split_firsts[0:(num_riders - 1)])
            riders_firstnames = riders_firstnames + ', and ' + split_firsts[num_riders - 1]

        riders_fullnames = riders_fullnames.rstrip(', ')

        # email to dropper
        date_obj_str = ride.date_time.strftime('%m/%d/%Y %I:%M %p')[0:date_length]
        time_obj_str = ride.date_time.strftime('%m/%d/%Y %I:%M %p')[date_length:] + ' EST'

        mail_to_dropper= EmailMultiAlternatives(
            subject= 'Ride #' + str(ride.id) + ' To ' + ride.get_end_destination_display(),
            body= 'Idk what goes here?',
            from_email= 'Princeton Go <*****@*****.**>',
            to=[user.username + '@princeton.edu']
            )
        # Add template
        mail_to_dropper.template_id = '4f75a67a-64a9-47f5-9a59-07646a578b9f'

        # Replace substitutions in template
        message = 'You have dropped a ride. For your records, below you can find the ride information.'
        theUser = Users.objects.get(netid=user.username)
        closing = 'Thank you for using Princeton Go!'
        mail_to_dropper.substitutions = {'%names%': theUser.first_name, '%body%': message, '%date%': date_obj_str,
                                         '%time%': time_obj_str, '%destination%': ride.get_start_destination_display() + ' to ' + ride.get_end_destination_display(),
                                         '%riders%': riders_fullnames, '%seats%': ride.seats, '%closing%': closing}

        mail_to_dropper.attach_alternative(
        "<p>This is a simple HTML email body</p>", "text/html" #don't know what this does but it doesn't work w/o it, don't delete
        )
        mail_to_dropper.send()

        # email to everyone in the ride

        mail_to_riders = EmailMultiAlternatives(
            subject= 'Ride #' + str(ride.id) + ' To ' + ride.get_end_destination_display(),
            body= 'Idk what goes here?',
            from_email= 'Princeton Go <*****@*****.**>',
            to=riders_emails
            )
        # Add template
        mail_to_riders.template_id = '4f75a67a-64a9-47f5-9a59-07646a578b9f'

        # Replace substitutions in template
        message = theUser.first_name + ' ' + theUser.last_name +' has dropped your ride. We have increased the number of available seats, as you can see below in the ride information.'
        closing = 'Thank you for using Princeton Go! We hope you enjoy your ride.'
        mail_to_riders.substitutions = {'%names%': riders_firstnames, '%body%': message, '%date%': date_obj_str,
                                        '%time%': time_obj_str, '%destination%': ride.get_start_destination_display() + ' to ' + ride.get_end_destination_display(),
                                        '%riders%': riders_fullnames, '%seats%': ride.seats, '%closing%': closing}

        mail_to_riders.attach_alternative(
        "<p>This is a simple HTML email body</p>", "text/html" #don't know what this does but it doesn't work w/o it, don't delete
        )
        mail_to_riders.send()

        #make sure this is the last thing done in the view
        if (ride.usrs.count() == 0):
            ride.delete()
    return render(request, 'app/drop_ride.html', context)
Example #22
0
def confirm_join_ride(request, ride_id):
    user = request.user
    ride = get_object_or_404(Rides, pk=ride_id)
    rider = Users.objects.get(netid=user.username)
    context = {

        'Riders': ride.usrs.all(),
        'title': 'Successfully Joined Ride',
        'start': ride.start_destination,
        'dest': ride.get_end_destination_display(),
        'date': ride.date_time,
        'netid': user.username,
        'rtype': request.path.split('/')[1],
    }

    if not rider.pools.filter(pk=ride_id).exists():
        name = "netid"+str(ride_id)
        init_User(user.username)
        rider.save()
        rider.pools.add(ride)
        rider.save()
        ride.usrs.add(rider)
        ride.seats -= 1
        ride.save()

        # email to everyone in the ride

        # list of all the riders
        riders_emails = []
        riders_firstnames = ""
        riders_fullnames = ""
        for rider in ride.usrs.all():
            riders_emails.append(rider.netid + '@princeton.edu')
            riders_firstnames = riders_firstnames + ", " + rider.first_name
            riders_fullnames = riders_fullnames + rider.first_name + " " + rider.last_name + ', '
        riders_firstnames = riders_firstnames.lstrip(', ')
        # put 'and' and delete comma if only two riders
        split_firsts = riders_firstnames.split(', ')
        num_riders = len(split_firsts)
        if num_riders == 2:
            riders_firstnames = (' and ').join(split_firsts)
        else:
            riders_firstnames = (', ').join(split_firsts[0:(num_riders - 1)])
            riders_firstnames = riders_firstnames + ', and ' + split_firsts[num_riders - 1]

        riders_fullnames = riders_fullnames.rstrip(', ')

        date_obj_str = ride.date_time.strftime('%m/%d/%Y %I:%M %p')[0:date_length]
        time_obj_str = ride.date_time.strftime('%m/%d/%Y %I:%M %p')[date_length:] + ' EST'

        mail_to_riders = EmailMultiAlternatives(
            subject= 'Ride #' + str(ride.id) + ' To ' + ride.get_end_destination_display(),
            body= 'Idk what goes here?',
            from_email= 'Princeton Go <*****@*****.**>',
            to=riders_emails
            )
        # Add template
        mail_to_riders.template_id = '4f75a67a-64a9-47f5-9a59-07646a578b9f'

        # Replace substitutions in template
        theUser = Users.objects.get(netid=user.username)
        message = theUser.first_name + ' ' + theUser.last_name +' has joined your ride! Below you can find the information for this ride, and you can coordinate how to get to your destination.'
        closing = 'Thank you for using Princeton Go! We hope you enjoy your ride.'
        mail_to_riders.substitutions = {'%names%': riders_firstnames, '%body%': message, '%date%': date_obj_str,
                                        '%time%': time_obj_str, '%destination%': ride.get_start_destination_display() + ' to ' + ride.get_end_destination_display(),
                                        '%riders%': riders_fullnames, '%seats%': ride.seats, '%closing%': closing}

        mail_to_riders.attach_alternative(
        "<p>This is a simple HTML email body</p>", "text/html" #don't know what this does but it doesn't work w/o it, don't delete
        )
        mail_to_riders.send()

    return render(request, 'app/confirmed_join.html', context)
Example #23
0
def confirmation_new_request(request):
    user = request.user
    init_User(user.username)
    start = request.session['start']
    dest = request.session['dest']
    number_going = request.session['number_going']
    date = request.session['date']
    time = request.session['time']

    rtype = request.path.split('/')[1]
    ride = Rides(ride_type=rtype, start_destination = start, end_destination=dest,
                 other_destination="", date_time=date + " " + time, req_date_time=timezone.now(),
                 seats = number_going, soon=False)

    ride.save()
    rider = Users.objects.get(netid=user.username)
    rider.save()
    rider.pools.add(ride)
    rider.save()
    ride.usrs.add(rider)
    ride.save()

    datetime_object = datetime.strptime(ride.date_time, '%Y-%m-%d %H:%M')

    context = {
        'Title': 'New Airport Confirmation',
        'start': start,
        'dest': dest,
        'number_going': number_going,
        'date': datetime_object.date(),
        'time': datetime_object.time(),
        'netid': user.username,
        'rtype': request.path.split('/')[1],
    }

    datetime_object = datetime.strptime(ride.date_time, '%Y-%m-%d %H:%M')
    date_obj_str = datetime_object.strftime('%m/%d/%Y %I:%M %p')[0:date_length]
    time_obj_str = datetime_object.strftime('%m/%d/%Y %I:%M %p')[date_length:] + ' EST'

    mail = EmailMultiAlternatives(
        subject= 'Ride #' + str(ride.id) + ' To ' + ride.get_end_destination_display(),
        body= 'Idk what goes here?',
        from_email= 'Princeton Go <*****@*****.**>',
        to=[user.username + '@princeton.edu']
        )
    # Add template
    mail.template_id = '4f75a67a-64a9-47f5-9a59-07646a578b9f'

    # Replace substitutions in template
    message = 'Your ride request has been created! Below you can find the information for your ride.'
    theUser = Users.objects.get(netid=user.username)
    closing = 'As others join your ride, you will get notified by email, and you can coordinate how to get to your destination. Thank you for using Princeton Go! We hope you enjoy your ride.'
    mail.substitutions = {'%names%': theUser.first_name, '%body%': message, '%date%': date_obj_str,
                          '%time%': time_obj_str, '%destination%': start + ' to ' + dest,
                          '%riders%': theUser.first_name + " " + theUser.last_name, '%seats%': number_going,
                          '%closing%': closing}

    mail.attach_alternative(
    "<p>This is a simple HTML email body</p>", "text/html"
    )
    mail.send()

    return render(request, 'app/confirmed_ride.html', context)
Example #24
0
def send_templated_email(
        to,
        template_subj, template_text, template_html=None,
        template_id=None, substitutions={},
        from_email=settings.EMAIL_SENDER, headers={}, cc=[], bcc=[]):
    """Send templated Email.

    This is new Version, which uses SendGrid HTML Template to be sent.
    """
    print colored("***" * 27, "green")
    print colored("*** INSIDE `%s`" % inspect.stack()[0][3], "green")

    try:
        # ---------------------------------------------------------------------
        # Prepare Email to be sent
        subj_content = render_to_string(
            template_subj["name"],
            template_subj["context"],
        )
        subj_content = "".join(subj_content.splitlines())

        text_content = render_to_string(
            template_text["name"],
            template_text["context"],
        )

        mail = EmailMultiAlternatives(
            subject=subj_content,
            body=text_content,
            from_email=from_email,
            to=to,
            cc=cc,
            bcc=bcc,
            headers=headers,
        )

        # ---------------------------------------------------------------------
        # --- 1. Add Template ID
        # --- 2. Replace Substitutions in SendGrid Template
        if template_id:
            mail.template_id = template_id
            mail.substitutions = substitutions

        # ---------------------------------------------------------------------
        # --- Attach Alternative
        if template_html:
            html_content = render_to_string(
                template_html["name"],
                template_html["context"],
            )
            mail.attach_alternative(html_content, "text/html")

        # ---------------------------------------------------------------------
        # --- Send Email
        mail.send()

        return True

    except Exception as e:
        print colored("###" * 27, "white", "on_red")
        print colored("### EXCEPTION @ `{module}`: {msg}".format(
            module=inspect.stack()[0][3],
            msg=str(e),
            ), "white", "on_red")

        # ---------------------------------------------------------------------
        # --- Save the Log
        papertrail.log(
            event_type="exception-send-templated-email",
            message="Exception: Send templated Email",
            data={
                "to":           to,
                "from":         from_email,
                "message":      str(e),
            },
            # timestamp=timezone.now(),
            targets={},
            )

    return False