Beispiel #1
0
    def post(self, request, *args, **kwargs):
        email = request.POST.get('email')
        phone = request.POST.get('phone', '')
        name = request.POST.get('name', '')
        total = request.POST.get('total')

        template = loader.get_template('order_email.html')
        context = {'email': email, 'phone': phone, 'name': name, 'total': total}
        html = template.render(context, request)

        sg = sendgrid.SendGridAPIClient(apikey="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")
        from_email = Email("*****@*****.**")
        to_email = Email(email)
        subject = "Order confirmation"
        content = Content("text/html", html)
        mail = Mail(from_email, subject, to_email, content)
        sg.client.mail.send.post(request_body=mail.get())

        request.session['message'] = 'Confirmation has been sent to email ' + email
        return redirect('home')
Beispiel #2
0
def send_welcome_mail(username, email):
    logger.info("Sending welcome email to customer @ {}".format(email))

    sg = sendgrid.SendGridAPIClient(apikey=config("SENDGRID_API_KEY"))
    from_email = Email("Halanx <*****@*****.**>")
    to_email = Email(email)
    subject = "Welcome to Halanx"
    html_content = render_to_string(
        'htmlemail/welcome-embedded.html', {
            'name': username,
            'email': email,
            'site': 'https://d28fujbigzf56k.cloudfront.net'
        })
    content = Content("text/html", html_content)
    mail = Mail(from_email, subject, to_email, content)
    try:
        sg.client.mail.send.post(request_body=mail.get())
        logger.info("Sent welcome email to customer @ {}".format(email))
    except Exception as e:
        logger.error(e)
Beispiel #3
0
def send_booking_invoice_email(booking_id):
    from Homes.Bookings.models import Booking
    booking = Booking.objects.get(id=booking_id)
    email = booking.tenant.customer.user.email
    logger.info("Sending booking invoice email to tenant @ {}".format(email))

    sg = sendgrid.SendGridAPIClient(apikey=config("SENDGRID_API_KEY"))
    from_email = Email("Halanx <*****@*****.**>")
    to_email = Email(email)
    subject = "House Booking Invoice #{}".format(booking.id)
    html_content = render_to_string('booking_invoice.html', {
        'booking': booking,
        'timestamp': datetime.now()
    })
    content = Content("text/html", html_content)
    mail = Mail(from_email, subject, to_email, content)
    try:
        sg.client.mail.send.post(request_body=mail.get())
        logger.info("Sent booking invoice email to tenant @ {}".format(email))
    except Exception as e:
        logger.error(e)
Beispiel #4
0
 def __init__(self, movie_name, location, movie_id, emails, date_list):
     self.email_sender = sendgrid.SendGridAPIClient(
         api_key=os.environ.get('SENDGRID_API_KEY'))
     self.from_email = Email(os.environ.get('FROM_EMAIL'))
     self.base_url = "https://in.bookmyshow.com/buytickets"
     self.location = location
     self.movie_name = movie_name
     self.movie_id = movie_id
     self.movie_name_with_location = self.movie_name + "-" + self.location
     self.subject = "BMS Alert: Booking for %s opened in location: %s" % (
         self.movie_name, self.location)
     self.emails = emails
     self.date_list = date_list
     self.email_content = Content(
         type_='text/html',
         value=str(
             codecs.open("movie_opening_alerter/movie_opening_alerter.html",
                         'r').read()).replace(
                             '{movie_name}', self.movie_name).replace(
                                 '{location}', str(self.location)).replace(
                                     '{status}', 'Booking started'))
Beispiel #5
0
def send_owner_payment_confirmation_email(payment_id):
    from Homes.Owners.models import OwnerPayment
    payment = OwnerPayment.objects.get(id=payment_id)
    email = payment.wallet.owner.user.email
    logger.info(
        "Sending payment confirmation email to owner @ {}".format(email))

    sg = sendgrid.SendGridAPIClient(apikey=config("SENDGRID_API_KEY"))
    from_email = Email("Halanx <*****@*****.**>")
    to_email = Email(email)
    subject = "Owner Payment #{}".format(payment.id)
    html_content = render_to_string('owner_payment_confirm.html',
                                    {'payment': payment})
    content = Content("text/html", html_content)
    mail = Mail(from_email, subject, to_email, content)
    try:
        sg.client.mail.send.post(request_body=mail.get())
        logger.info(
            "Sent payment confirmation email to owner @ {}".format(email))
    except Exception as e:
        logger.error(e)
Beispiel #6
0
def sendgird_send_email(to, subject, content, attachment):
    import jsonpickle
    import base64

    SENDGRID_API_KEY = settings.SENDGRID_API_KEY
    sg = sendgrid.SendGridAPIClient(api_key=SENDGRID_API_KEY)


    from_email = "*****@*****.**"

    mail = Mail(from_email=from_email, subject=subject, to_emails=to, plain_text_content=content)
    
    if type(attachment) == list:
        for att in attachment:
            mail.add_attachment(attachment=att)
    else:
        mail.add_attachment(attachment=attachment)

    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    # res = jsonpickle.dumps(mail, indent=4)
    return response
Beispiel #7
0
def send_monthly_earning_invoice_email(monthly_earning_id):
    from Homes.Owners.models import OwnerMonthlyEarning
    monthly_earning = OwnerMonthlyEarning.objects.get(id=monthly_earning_id)
    email = monthly_earning.owner.user.email
    logger.info(
        "Sending monthly rent invoice email to owner @ {}".format(email))

    sg = sendgrid.SendGridAPIClient(apikey=config("SENDGRID_API_KEY"))
    from_email = Email("Halanx <*****@*****.**>")
    to_email = Email(email)
    subject = "Monthly Rent Invoice #{}".format(monthly_earning.id)
    html_content = render_to_string('monthly_earning_invoice.html', {
        'monthly_earning': monthly_earning,
        'timestamp': datetime.now()
    })
    content = Content("text/html", html_content)
    mail = Mail(from_email, subject, to_email, content)
    try:
        sg.client.mail.send.post(request_body=mail.get())
        logger.info(
            "Sent monthly rent invoice email to owner @ {}".format(email))
    except Exception as e:
        logger.error(e)
Beispiel #8
0
def sendemailall(request):
    if request.method == 'GET':
        return render(request, 'sendemailtest.html')
    elif request.method == 'POST':
        from django.contrib.auth import authenticate
        user = authenticate(username=request.POST['username'], password=request.POST['password'])
        if user is not None:
            file = request.FILES['file']
            texts = file.read().decode("utf-8")
            emails = ""
            for user in User.objects.all():
                sg = sendgrid.SendGridAPIClient(
                    apikey="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")
                from_email = Email("*****@*****.**")
                subject = str(request.POST['subject'])
                to_email = Email(user.email)
                content = Content("text/html", str(texts))
                mail = Mail(from_email, subject, to_email, content)
                response = sg.client.mail.send.post(request_body=mail.get())
                emails = emails + str(user.email) + "\n"
            return HttpResponse("Sent to " + str(emails))
        else:
            return HttpResponse("Incorrect account")
from django.conf import settings
from sendgrid import sendgrid, Email
from sendgrid.helpers.mail import Content, Mail, Personalization

from common.decorators import raise_api_exception
from integration_3rdparty.exceptions import ExternalAPIException

client = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID['API_KEY'])


@raise_api_exception(ExternalAPIException)
def send_email(from_email,
               to_email,
               subject,
               content,
               content_type='text/plain'):
    from_email = Email(from_email)
    to_email = Email(to_email)
    subject = subject
    content = Content(content_type, content)
    mail = Mail(from_email, subject, to_email, content)
    response = client.client.mail.send.post(request_body=mail.get())

    if response.status_code > 299:
        raise Exception(response.body)


def get_mock_personalization_dict(to_emails):
    """Get a dict of personalization mock."""
    mock_pers = dict()
    mock_pers['to_list'] = [Email(email) for email in to_emails]
Beispiel #10
0
def send_tenant_payment_confirmations(payment_id,
                                      email=True,
                                      sms=True,
                                      notification=True,
                                      payment_gateway=None):
    """
    Task to send email, sms, notification to tenant on successful payment.
    :param payment_gateway:
    :param payment_id: Tenant Payment ID
    :param email: True/False
    :param sms: True/False
    :param notification: True/False
    """
    from Homes.Tenants.models import TenantPayment
    payment = TenantPayment.objects.get(id=payment_id)
    customer = payment.wallet.tenant.customer

    if sms:
        phone_no = customer.phone_no
        logger.info(
            "Sending payment confirmation SMS to tenant @ {}".format(phone_no))
        if payment_gateway:
            msg = SUCCESSFUL_TENANT_PAYMENT_MSG.format(
                customer.user.first_name, payment.description, payment.amount,
                payment_gateway, payment.id)

        try:
            send_sms.delay(phone_no, msg)
            logger.info("Sent payment confirmation SMS to tenant @ {}".format(
                phone_no))
        except Exception as e:
            logger.error(e)

    if email:
        email = customer.user.email
        logger.info(
            "Sending payment confirmation email to tenant @ {}".format(email))

        sg = sendgrid.SendGridAPIClient(apikey=config("SENDGRID_API_KEY"))
        from_email = Email("Halanx <*****@*****.**>")
        to_email = Email(email)
        subject = "Tenant Payment #{}".format(payment.id)
        html_content = render_to_string('tenant_payment_confirm.html',
                                        {'payment': payment})
        content = Content("text/html", html_content)
        mail = Mail(from_email, subject, to_email, content)
        try:
            sg.client.mail.send.post(request_body=mail.get())
            logger.info(
                "Sent payment confirmation email to tenant @ {}".format(email))
        except Exception as e:
            logger.error(e)

    if notification:
        logger.info(
            "Sending payment confirmation notification to tenant @ {}".format(
                customer.name))
        try:
            payload = {'amount': payment.amount}
            Notification(target=customer,
                         category=TENANT_PAYMENT_SUCCESSFUL_NC,
                         payload=payload).save({
                             'amount':
                             payment.amount,
                             'payment_id':
                             payment.id,
                             'description':
                             payment.description,
                             'payment_gateway':
                             payment.transaction.payment_gateway
                         })
            logger.info(
                "Sent payment confirmation notification to tenant @ {}".format(
                    customer.name))
        except Exception as e:
            logger.error(e)
Beispiel #11
0
import os
from sendgrid import SendGridAPIClient, sendgrid
from sendgrid.helpers.mail import Mail

API_KEY = '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'
sg = sendgrid.SendGridAPIClient(API_KEY)


def enviar_mail():
    message = Mail(
        from_email='*****@*****.**',
        to_emails='*****@*****.**',
        subject='Sending with Twilio SendGrid is Fun, SUPER FUN',
        html_content=
        '<strong>and easy to do anywhere, even with Python</strong>')

    try:
        sg = SendGridAPIClient(API_KEY)
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e)


def enviar_mail_personalizado_hotel(ciudad, hotel, habitacion, checkin,
                                    checkout, costo, personas, receptor):
    data = {
        "from": {
            "email": "*****@*****.**"
Beispiel #12
0
	<center>
	<br><img src="https://supbotserver.herokuapp.com/static/tucan_square.png" style="width:80px;height:80px;">
	<h2>Welcome to Tucan Studio</h2>
	<h3>Just a few more steps before your account is up and running, just confirm your email.</h3>
	<br><a href="https://supbotserver.herokuapp.com/api/activate/">CONFIRM EMAIL</a>
	<br><br><br><img class="social-media" src="https://supbotserver.herokuapp.com/static/copbot_website.png" style="width:25px;height:25px;">
	<img class="social-media" src="https://supbotserver.herokuapp.com/static/facebook_website.png" style="width:25px;height:25px;">
	<img class="social-media" src="https://supbotserver.herokuapp.com/static/instagram_website.png" style="width:25px;height:25px;">
	<img class="social-media" src="https://supbotserver.herokuapp.com/static/twitter_website.png" style="width:25px;height:25px;">
	<img class="social-media" src="https://supbotserver.herokuapp.com/static/youtube_website.png" style="width:25px;height:25px;">
</center>
</body>
</html>"""

sg = sendgrid.SendGridAPIClient(
    apikey=
    "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")
from_email = Email("*****@*****.**")
subject = "TUCAN STUDIO UK - Thanks for signing up"
to_email = Email("*****@*****.**")
content = Content("text/html", s)
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)

# import datetime
#
# x = datetime.datetime.now()
# x = x.replace(year = 2015, month = 12, day = 31)
Beispiel #13
0
# This is the admin section Not the Superadmin. Admin can:
#       1. view request(Messages) sent from the end user
#       2. Accept or reject the request via mails sent.
#       3. If accepted, admin can enter the money paid, made and the shipping cost and VAT then hit save.
#       4. Once saved, it is for records keeping and will goto the profits page where all Transactions are saved
#       5. If rejected, admin can view all in the rejected page and then review it later if it should be Accepted
#       6. Admin can create Feature products for any events going on. Can as well delete and start an event.
#       7. Once an event is created, status is false. If status is False it won't be seen in 'index'
#       8. The start/stop page has 2 dropdowns, 1 for the events created and the other to start/stop it.
#           if an event is started; staus = True therefore, shown in 'index' else status = False and taken out.
#       9. If an event is deleted...
#       10. admin can edit/delete an item in the feature product
#       11. anywhere you see 'pd' it means 'PageData' which is also 'context'
#

sg = sendgrid.SendGridAPIClient(api_key=SENDGRID_API_KEY)

title = "SmartAlaba Ltd"
address = "30 Wetheral Road Owerri"
phone = "+234 808 568 0969"
email = "*****@*****.**"
site = "https://smartalaba.com/"
payment_details = "SmartAlaba Ltd"+"\n"+"Bank: FCMB"+"\n"+"Account holder: SmartAlaba Ltd"+"\n"+"Bank account: 6270292029"
payment_terms = "30 days"


# landing page for admin, 'admin-index' name: 'adminhome'
@login_required
def admin_home(request):
    num_req = Message.objects.all().count()  # number of total request
    num_wtn_req = Message.objects.filter(status="Waiting").count()  # number of waiting requests
Beispiel #14
0
def PasswordResetView(request):
    parsed_post = loads(request.body)
    email = parsed_post.get('email', None)
    reset_token = parsed_post.get('reset_token', None)
    if email:
        profile = (
            UserProfile.objects
            .filter(user__email=email)
            .first())
        if not profile:
            return JsonResponse({
                "error": "Can't find user with email."
            }, status=400)

        sg = sendgrid.SendGridAPIClient(
            apikey=settings.SENDGRID_API_KEY)

        reset_token = word_hash()
        token, token_created = profile.set_reset_token(reset_token)

        if not token_created:
            return JsonResponse({'error': 'could not create token'},
                                status=400)

        mail = build_reset_email(request, profile)
        response = sg.client.mail.send.post(request_body=mail.get())

        status_code = response.status_code
        if status_code == 200 or status_code == 202:
            return JsonResponse({'status': 'reset email sent'},
                                status=status_code)
        else:
            return JsonResponse({'body': response.body.decode('utf-8')},
                                status=status_code)

    elif reset_token:
        try:
            profile = UserProfile.objects.get(
                reset_token=reset_token
            )
            user = profile.user
        except UserProfile.DoesNotExist:
            return JsonResponse({
                'error': 'could not find user matching token'
            }, status=400)
        now = timezone.now()
        expiry = profile.reset_token_expiry

        if expiry and now > expiry:
            return JsonResponse({
                'error': 'reset token has expired'
            }, status=400)

        new_password = parsed_post.get('new_password', None)
        if not new_password:
            return JsonResponse({
                'error': 'No new password'
            }, status=400)
        user.set_password(new_password)
        user.save()

        return JsonResponse({'status': 'password changed'},
                            status=200)

    return JsonResponse({'error': 'No email address or token'},
                        status=400)