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 #2
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 #3
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 #4
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 #5
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()
Example #6
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 #7
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 #8
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 #9
0
 def send_password_reset_email(self, to, ctx):
     subject = render_to_string("account/email/password_reset_subject.txt", ctx)
     subject = "".join(subject.splitlines())
     message = render_to_string("account/email/password_reset.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)
     settings.SENDGRID_TEMPLATE_IDS['password_reset']
     mail.send()
Example #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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