def __init__(self, movie_name, location, movie_id, keywords, emails, date_list=None): self.email_sender = sendgrid.SendGridAPIClient( apikey=os.environ.get('SENDGRID_API_KEY')) self.from_email = Email(os.environ.get('FROM_EMAIL')) self.base_url = "https://in.bookmyshow.com/buytickets" self.subject = "BMS Alert: Booking opened in a theatre" self.movie_name_with_location = movie_name + "-" + location self.movie_id = movie_id self.keywords = keywords self.emails = emails if not date_list: current_day = datetime.datetime.today() next_day = current_day + datetime.timedelta(days=1) date_list = [ current_day.strftime("%Y%m%d"), next_day.strftime("%Y%m%d") ] self.date_list = date_list self.email_content = Content(type_='text/html', value=str( codecs.open("hall_opening_alerter/hall_opening_alerter.html", 'r').read()) \ .replace('{movie}', self.movie_name_with_location) \ .replace('{keywords}', str(self.keywords)) .replace('{status}', 'Booking started'))
def send_welcome_mail(email): sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email('*****@*****.**', name="Smeet Bhatt") subject = "Chymera VR Ad Network" content = Content("text/html", WELCOME_MESSAGE) mail = Mail(from_email, subject, Email(email), content=content) personalization = Personalization() for recepient in RECEPIENTS: personalization.add_to(Email(recepient)) print(personalization) mail.add_personalization(personalization) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers)
def send_email(rendered, subject, recipient, from_address, api_key): sg = sendgrid.SendGridAPIClient(apikey=api_key) from_email = Email(from_address) to_email = Email(recipient) subject = subject content = Content("text/html", rendered) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code > 226: msg = 'Could not send email. Following error occurred. {} Error code: {}'.format( response.body, response.status_code ) return { "message": "error", "reason": response.body }
def build_email(self): mail = Mail(from_email=self.from_email, subject=self.subject, to_email=self.from_email, content=self.email_content) personalization = Personalization() for email in self.emails: personalization.add_to(Email(email)) mail.add_personalization(personalization) return mail.get()
def send_sendgrid_mail(to_email, subject, content): """ send sendgrid mail :param to_email: :param subject: :param content: :return: """ sg = sendgrid.SendGridAPIClient(apikey=config.EMAIL_API_KEY) from_email = Email(config.FROM_EMAIL) to_email = Email(to_email) content = Content("text/plain", content) mail = Mail(from_email, subject, to_email, content) # todo try except to log error if possible response = sg.client.mail.send.post(request_body=mail.get()) logger.info(response.status_code) logger.info("mail sent")
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)
def build_reset_email(request, profile): to_email = profile.user.email if not settings.RESET_DEBUG_EMAIL\ else settings.RESET_DEBUG_EMAIL if not profile.reset_token: raise AttributeError("No reset token found") name = profile.get_full_name() reset_token = profile.reset_token domain = settings.APP_DOMAIN protocol = 'https' if request.is_secure() else 'http' from_email = Email("*****@*****.**") to_email = Email(to_email) subject = f"Reset password for {name}" body = "To reset your password, please click the link below.\n\n" \ f"{protocol}://{domain}/password-reset/?token={reset_token}" content = Content("text/plain", body) return Mail(from_email, subject, to_email, content)
def send(self, to_email=None, subject=None, content=None, content_type=None): from_email = Email(self.from_email) to_email = To(to_email) content = Content(content_type, content) mail = Mail(from_email, to_email, subject, content) return self.sendgrid_client.client.mail.send.post( request_body=mail.get())
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')
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)
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)
def forgotpwd(request): if request.method == 'GET': return render(request, 'forgotpwd.html') elif request.method == 'POST': email = request.POST['email'] try: user = User.objects.get(email__iexact=email) name = user.name alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" pw_length = 8 newpassword = "" for i in range(pw_length): next_index = random.randrange(len(alphabet)) newpassword = newpassword + alphabet[next_index] user.password = newpassword user.save() except: context = { 'error_message': "Unable to find email", 'email': request.POST['email'] } return render(request, 'forgotpwd.html', context) # try: sg = sendgrid.SendGridAPIClient( apikey= "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" ) from_email = Email("*****@*****.**") subject = "TUCAN STUDIO UK - Reseted your password" to_email = Email(email) context = {'password': newpassword} content = Content( "text/html", render_to_string('email_reset_password.html', context)) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) if 'account_id' in request.session: del request.session['account_id'] return render(request, 'after_reset_pwd.html')
def send_emails(from_email, to_emails: list, subject, content, content_type='text/plain'): from_email = Email(from_email) subject = subject content = Content(content_type, content) mail = Mail(from_email, subject, None, content) personalization = get_mock_personalization_dict(to_emails) mail.add_personalization(build_personalization(personalization)) response = client.client.mail.send.post(request_body=mail.get()) if response.status_code > 299: raise Exception(response.body)
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")
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)
def send_email_smtp1(subject, body, email, html_content): me = "Kashiyatra'19" mee=Email(me, "Kashiyatra'19") you = email your=Email(email) # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = me msg['To'] = you # Create the body of the message (a plain-text and an HTML version). # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(body, 'plain') part2 = MIMEText(html_content, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. mailserver = smtplib.SMTP('smtp.gmail.com', 587) mailserver.ehlo() # secure our email with tls encryption mailserver.starttls() # re-identify ourselves as an encrypted connection mailserver.ehlo() mailserver.login('*****@*****.**', 'waitforbiggestky19') # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. mailserver.sendmail(me, you, msg.as_string()) mailserver.quit()
def sendemailagain(request): if request.method == 'GET': return render(request, 'sendagain.html') elif request.method == 'POST': email = request.POST['email'] try: user = User.objects.get(email__iexact=email) except: context = { 'error_message': "Incorrect email.", 'email': request.POST['email'], 'password': request.POST['password'] } return render(request, 'sendagain.html', context) if str(user.activateid) != '1': sg = sendgrid.SendGridAPIClient( apikey= "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" ) from_email = Email("*****@*****.**") subject = "TUCAN STUDIO UK - Thanks for signing up" to_email = Email(email) context = {'activateid': user.activateid} content = Content("text/html", render_to_string('email_confirm.html', context)) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) return render(request, 'after_signup.html') else: context = { 'error_message': "The account is activated. <a href=\"https://supbotserver.herokuapp.com/api/signin/\">Click here to sign in</a>", 'email': request.POST['email'], 'password': request.POST['password'] } return render(request, 'sendagain.html', context)
def __init__(self, options: dict, result_parser: BaseParser): super().__init__(options, result_parser) if not os.environ.get('SENDGRID_API_KEY'): raise ValueError('SENDGRID_API_KEY 가 제공되지 않았습니다.') self.send_grid = sendgrid.SendGridAPIClient( api_key=os.environ.get('SENDGRID_API_KEY')) if not options.get('sender'): raise ValueError('option 으로 sender 가 제공되지 않았습니다.') if not options.get('recipient'): raise ValueError('option 으로 recipient 가 제공되지 않았습니다.') self.from_email = Email(options.get('sender')) self.to_email = To(options.get('recipient')) self._title = None
def send_email(self, subject, message_body, to_email=None): """ Sends an email using the send grid API :param to_email: :param subject: :param message_body: :return: """ print(to_email) content = Content("text/plain", message_body) if to_email is None: mail = Mail(self._sender_email, subject, self._admin_email, content) else: mail = Mail(self._sender_email, subject, Email(to_email), content) response = self._sg.client.mail.send.post(request_body=mail.get()) return str(response.status_code).startswith("20")
def send_email(self, subject, message_body, recipients=[]): """ Sends an email using the send grid API :param recipients: :param subject: :param message_body: :return: """ content = Content("text/plain", message_body) mail = Mail(self._sender_email, subject, self._admin_email, content) if len(recipients) > 0: recipients_personalization = Personalization() for address in recipients: recipients_personalization.add_to(email=Email(address)) mail.add_personalization(recipients_personalization) response = self._sg.client.mail.send.post(request_body=mail.get()) return str(response.status_code).startswith("20")
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'))
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)
<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) # print(x) # try:
def paypallisner(request): from logging import getLogger, StreamHandler, DEBUG logger = getLogger(__name__) handler = StreamHandler() handler.setLevel(DEBUG) logger.setLevel(DEBUG) logger.addHandler(handler) logger.debug(str(request.body.decode('utf-8'))) req = urllib.request.Request( "https://www.paypal.com/cgi-bin/webscr?cmd=_notify-validate&" + str(request.body.decode('utf-8'))) # "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_notify-validate&" + str(request.body.decode('utf-8'))) allhtml = "" with urllib.request.urlopen(req) as res: html = res.read().decode("utf-8") allhtml = allhtml + html if allhtml == "VERIFIED": dict = {} for key, value in request.POST.lists(): dict.update({key: value}) id = dict['payer_id'][0] profileid = dict['recurring_payment_id'][0] try: user = User.objects.get(paypalprofileid__iexact=profileid) except: logger.debug("no user") return HttpResponse("Error") if user.paypalid != id: logger.debug("no paypal id" + user.paypalid + ", " + id) return HttpResponse("Error") # if dict['amount_per_cycle'][0] == "10.00" and dict['initial_payment_amount'][0] == "10.00" and dict['amount'][ # 0] == "10.00" and dict['amount_per_cycle'][0] == "10.00" and dict['currency_code'][0] == "GBP" and \ # dict['payment_cycle'][0] == "Monthly": if dict['receiver_email'][ 0] == "tucanstudio_api1.tucanstudiouk.com" and dict['amount'][ 0] == "34.99" and dict['amount_per_cycle'][ 0] == "34.99" and dict['currency_code'][ 0] == "USD" and dict['payment_cycle'][ 0] == "Monthly": logger.debug("checked") if dict['txn_type'][0] == 'recurring_payment_profile_created': logger.debug("created") user.paypalemail = dict['payer_email'][0] user.paypalname = dict['first_name'][0] + " " + dict[ 'last_name'][0] user.firstdate = datetime.datetime.utcnow().replace( tzinfo=utc).strftime('%Y-%m-%dT%H:%M:%SZ') user.edate = str(dict['next_payment_date'][0])[9:] if user.detail == 0: sg = sendgrid.SendGridAPIClient( apikey= "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" ) from_email = Email("*****@*****.**") subject = "TUCAN STUDIO UK - Thank you" to_email = Email(user.email) content = Content( "text/html", render_to_string('email_copbot_mobile_signup.html')) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post( request_body=mail.get()) user.detail = 2 user.save() elif dict['txn_type'][0] == 'recurring_payment': user.detail = 2 user.edate = (dict['next_payment_date'][0])[9:] user.save() elif dict['txn_type'][0] == 'recurring_payment_profile_cancel': user.type = 0 user.save() elif dict['txn_type'][0] == 'recurring_payment_expired': user.detail = 0 user.save() elif dict['txn_type'][0] == 'recurring_payment_skipped': user.detail = 0 user.save() elif dict['txn_type'][0] == 'recurring_payment_suspended': user.detail = 0 user.save() elif dict['txn_type'][ 0] == 'recurring_payment_suspended_due_to_max_failed_payment': user.detail = 1 user.save() return HttpResponse() else: return HttpResponse()
using the following link: {url} This link is valid for one registration and is sent to the holder of Portland ticket {ticket_id} and the person who ordered that ticket. If multiple tickets were registered or ordered by you, you may receive multiple emails, each allowing you to register one ticket. If you will not be participating in our Prague conference, you can ignore this mail. For full details on the conference, see: https://www.writethedocs.org/conf/prague/2020/ If you have any further questions, please contact [email protected]. Write the Docs """ message = Mail( from_email='*****@*****.**', to_emails=p['email'], subject='Your Write the Docs Prague 2020 Virtual Pass', plain_text_content=text, ) if p['email'] != p['cc']: message.personalizations[0].add_cc(Email(p['cc'])) try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) except Exception as e: print(e)
def signup(request): if request.method == 'GET': return render(request, 'signup.html') elif request.method == 'POST': if 'tandc' in request.POST: if not str(request.POST['g-recaptcha-response']): context = { 'error_message': "Bot check is required.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) req = urllib.request.Request( "https://www.google.com/recaptcha/api/siteverify?secret=6LeBzQgUAAAAAKt953zokMxQ_vE0twJ42q_mgESx&response=" + str(str(request.POST['g-recaptcha-response']))) allhtml = "" with urllib.request.urlopen(req) as res: html = res.read().decode("utf-8") allhtml = allhtml + html jsonData = json.loads(allhtml) if (jsonData['success'] != True): context = { 'error_message': "Bot check error.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) if str(request.POST['password1']) != str( request.POST['password2']): context = { 'error_message': "Passwords are not same.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) if not str(request.POST['password1']): context = { 'error_message': "Password is required.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) email = request.POST['email'] try: user = User.objects.get(email__iexact=email) context = { 'error_message': "This email is already used.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) except: name = request.POST['name'] password = request.POST['password1'] alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" pw_length = 8 activateid = "" for i in range(pw_length): next_index = random.randrange(len(alphabet)) activateid = activateid + alphabet[next_index] user = User(email=str(email), name=str(name), password=password, activateid=activateid, firstdate=str(datetime.datetime.now())) try: sg = sendgrid.SendGridAPIClient( apikey= "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" ) from_email = Email("*****@*****.**") subject = "TUCAN STUDIO UK - Thanks for signing up" to_email = Email(email) context = {'activateid': activateid} content = Content( "text/html", render_to_string('email_confirm.html', context)) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post( request_body=mail.get()) user.save() except: context = { 'error_message': "Incorrect email.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context) context = {'name': str(name)} return render(request, 'after_signup.html', context) else: context = { 'error_message': "You need to agree to TERMS AND CONDITIONS.", 'name': request.POST['name'], 'email': request.POST['email'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'signup.html', context)
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] return mock_pers
def activate(request): if request.method == 'GET': return render(request, 'activate.html') elif request.method == 'POST': email = request.POST['email'] password = request.POST['password'] activateid = request.POST['id'] activateid = activateid[int(activateid.find("=")) + 1:int(len(activateid))] try: user = User.objects.get(email__iexact=email) if str(user.password) == password: if str(user.activateid) == "1": context = { 'error_message': "This account is already confirmed.", 'email': request.POST['email'], 'password': request.POST['password'] } return render(request, 'activate.html', context) else: if str(user.activateid) == activateid: user.activateid = 1 user.save() request.session['account_id'] = user.id # sg = sendgrid.SendGridAPIClient( # apikey="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") # from_email = Email("*****@*****.**") # subject = "TUCAN STUDIO UK - Thank you!! There is more information here." # to_email = Email(email) # content = render_to_string('templates/email.html', {'some_params': some_params}) # mail = Mail(from_email, subject, to_email, content) # response = sg.client.mail.send.post(request_body=mail.get()) try: sg = sendgrid.SendGridAPIClient( apikey= "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" ) from_email = Email("*****@*****.**") subject = "TUCAN STUDIO UK - Thanks for signing up" to_email = Email(email) content = Content( "text/html", render_to_string('email_signup_info.html')) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post( request_body=mail.get()) user.save() return HttpResponseRedirect( 'https://supbotserver.herokuapp.com/api/') except: context = { 'error_message': "Email problem.", 'email': request.POST['email'], 'password': request.POST['password'] } return render(request, 'activate.html', context) else: context = { 'error_message': "Incorrect ID.", 'email': request.POST['email'], 'password': request.POST['password'] } return render(request, 'activate.html', context) else: context = { 'error_message': "Incorrect password.", 'email': request.POST['email'], 'password': request.POST['password'] } return render(request, 'activate.html', context) except: context = { 'error_message': "Incorrect email.", 'email': request.POST['email'], 'password': request.POST['password'] } return render(request, 'activate.html', context)