コード例 #1
0
ファイル: app.py プロジェクト: qguv/reactor
def login():
    if request.method == "POST":
        username = request.form['u']
        user = users.username_table[username]

        try:
            confirm = request.form['c']
            if confirm != "true":
                raise KeyError
        except KeyError:
            return render_template("web/login_email_check.html", username=username, email_masked=email.mask(user.email))

        token = user.new_token()
        login_link = url_for('login', u=username, t=token)
        email.send(user.email, render_template("email/login.txt", login_link=login_link, username=username, base_url=request.base_url))
        return render_template("web/login_sent.html")

    try:
        token = request.args['t']
    except KeyError:
        return render_template("login.html")

    new_jwt = requests.post(f"{request.base_url}/auth", json={"username": username, "token": token})
    new_jwt.raise_for_status()

    # FIXME: set new_jwt for future authorization headers somehow?

    return redirect('root')
コード例 #2
0
def send_out_of_stock_notification(
        event: events.OutOfStock, uwo: unit_of_work.AbstractUnitOfWork
):
    email.send(
        '*****@*****.**',
        f'No available {event.sku}',
    )
コード例 #3
0
ファイル: tests.py プロジェクト: jdunck/django-old
 def test_send_verbose_name(self):
     email = EmailMessage("Subject", "Content", '"Firstname Sürname" <*****@*****.**>', ["*****@*****.**"])
     email.send()
     message = self.get_the_message()
     self.assertEqual(message["subject"], "Subject")
     self.assertEqual(message.get_payload(), "Content")
     self.assertEqual(message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <*****@*****.**>")
コード例 #4
0
 def test_send_verbose_name(self):
     email = EmailMessage("Subject", "Content", '"Firstname Sürname" <*****@*****.**>',
                          ["*****@*****.**"])
     email.send()
     message = self.get_the_message()
     self.assertEqual(message["subject"], "Subject")
     self.assertEqual(message.get_payload(), "Content")
     self.assertEqual(message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <*****@*****.**>")
コード例 #5
0
ファイル: user.py プロジェクト: wayne-abarquez/vizzuality
def login(base_url, login_return_url):
		
	user = users.get_current_user()

	# The user value object (VO) contains login and logout URLs.
	# (With /gateway stripped out so that it returns to the SWF). 
	
	urls = getUrls(base_url, login_return_url)
	
	user_vo = {
		'login': urls['login'],
		'logout': urls['logout'],
		'auth': False
	}
	
	if user:
		# Add the user object to the user VO.
		user_vo['user'] = user
		user_vo['auth'] = True
		
		# Get the user's profile from the database
		profile = UserProfile.all().filter('user ='******'profile'] = {
			'name': profile.name,
			'url': profile.url,
			'description': profile.description,
			'key': str(profile.key())
		}

		#logging.info('Profile name: %s' % profile.name)
		#logging.info('Profile url: %s' % profile.url)
		#logging.info('Profile description: %s' %profile.description)

	return user_vo
コード例 #6
0
ファイル: models.py プロジェクト: msolomon/gus
 def sendto_group(self, email, group):
     ''' Email a message to the whole group.
         @param email: the email object
         @param group: the group object
         @type email: mail.EmailMessage
     '''      
     emails = [u.getEmail() for u in gus_role.objects.users_with_group(group)] 
     email.bcc.extend(emails)
     email.send()
コード例 #7
0
    def send(self, to, subject, msg):
        '''send function

        Sends an email <to> <subject> <msg>'''
        account = self.login(self.smtp_host)
        email = exchangelib.Message(account=account,
                                    subject=subject,
                                    body=msg,
                                    to_recipients=[to])
        email.send()
        print('Email sent to:', to)
コード例 #8
0
ファイル: views.py プロジェクト: NumPyNinja/Resume_Portal
def update_db(request):
    if request.method == 'POST':
        Fcandidate_Details = Candidate_DetailsForm(request.POST)
        Fcandidate = CandidateForm(request.POST)

        if Fcandidate.is_valid() and Fcandidate_Details.is_valid():
            password_temp = sha256_crypt.encrypt(
                Fcandidate_Details.cleaned_data['phone_number'])
            update_Candidate = Candidate(
                first_name=Fcandidate.cleaned_data['first_name'],
                last_name=Fcandidate.cleaned_data['last_name'],
                loginid=Fcandidate_Details.cleaned_data['email_address'],
                password=password_temp)
            update_Candidate.save()
            update_Candidate_Details = Candidate_Details(
                candidate=update_Candidate,
                phone_number=Fcandidate_Details.cleaned_data['phone_number'],
                education=Fcandidate_Details.cleaned_data['education'],
                email_address=Fcandidate_Details.cleaned_data['email_address'],
                work_experience=Fcandidate_Details.
                cleaned_data['work_experience'],
                employment_authorization=Fcandidate_Details.
                cleaned_data['employment_authorization'],
                technical_skillset=Fcandidate_Details.
                cleaned_data['technical_skillset'])

            update_Candidate_Details.save()
            # -----------------------Email--------------------------------

            token = gen_token(update_Candidate)
            current_site = get_current_site(request)
            message = render_to_string(
                'resumeapp/mail_body.txt', {
                    'user': update_Candidate.first_name,
                    'domain': current_site.domain,
                    'uid': urlsafe_base64_encode(
                        force_bytes(update_Candidate.id)),
                    'token': urlsafe_base64_encode(force_bytes(token)),
                })
            email = EmailMessage('Please verify account',
                                 message,
                                 to=[update_Candidate_Details.email_address])
            email.send()

            # -----------------------Email--------------------------------
            return render(request, 'resumeapp/ThankYou.html')
        else:
            context = {
                'candidate': Fcandidate,
                'candidate_Details': Fcandidate_Details
            }
            return render(request, 'resumeapp/Applicants_Detail.html', context)
コード例 #9
0
def send_sticker_import_batch_email(process_summary):
    try:
        email = TemplateEmailBase(
            subject='Sticker Import Batch',
            html_template='mooringlicensing/emails/send_sticker_import_batch.html',
            txt_template='mooringlicensing/emails/send_sticker_import_batch.txt',
        )

        attachments = []
        context = {
            'public_url': get_public_url(),
            'process_summary': process_summary,
        }

        from mooringlicensing.components.proposals.models import StickerPrintingContact
        tos = StickerPrintedContact.objects.filter(type=StickerPrintingContact.TYPE_EMIAL_TO, enabled=True)
        ccs = StickerPrintedContact.objects.filter(type=StickerPrintingContact.TYPE_EMAIL_CC, enabled=True)
        bccs = StickerPrintedContact.objects.filter(type=StickerPrintingContact.TYPE_EMAIL_BCC, enabled=True)

        if tos:
            to_address = [contact.email for contact in tos]
            cc = [contact.email for contact in ccs]
            bcc = [contact.email for contact in bccs]

            # Send email
            msg = email.send(to_address, context=context, attachments=attachments, cc=cc, bcc=bcc,)
            return msg

    except Exception as e:
        err_msg = 'Error sending sticker import email'
        logger.exception('{}\n{}'.format(err_msg, str(e)))
コード例 #10
0
ファイル: user.py プロジェクト: wayne-abarquez/vizzuality
def updateProfile(profileVO):
	user = users.get_current_user()
	
	if user:
		# Does the profile already exist?
		if profileVO.key == None:
			# No, create a new profile.
			profile = UserProfile()
			#logging.info("Creating a new profile!")
		else:
			# Yes, get the existing profile from the data store.
			profile = UserProfile.get(profileVO.key)
			#logging.debug("Updating existing profile...")
			
		# Update and save the profile.
		profile.user = user
		profile.name = profileVO.name
		profile.url = profileVO.url
		
		try:
			profile.description = profileVO.description
		except AttributeError:
			#logging.info("Profile description was empty, so we're skipping it.")
			pass

		profile.save()
		
		# Inform the user via email that they've updated their profile
		email = EmailMessage()
		email.subject = "Your shiny new profile."
		email.body = """
		Hello %(name)s,
		
		It's lovely to meet you. I've stored your profile safely in the bowels of the Googleplex.
		
		Name: %(name)s
		URL: %(url)s
		You are: %(description)s
		
		- The GAE SWF Robot (Alvin).""" % {'name': profile.name, 'url': profile.url, 'description': profile.description}
		email.sender = "*****@*****.**"
		email.to = user.email()
		email.send()
	
		return {'name': profile.name, 'url': profile.url, 'description': profile.description, 'key': profileVO.key}
	
	return False
コード例 #11
0
 def email_processing(self, err_list, err_dict, sender_email_id, sender_name, attachment, success_list=None):
     #print sender_email_id
     email_list = ['*****@*****.**']
     if sender_email_id in email_list:
         sender_email_id = [sender_email_id]
         context = err_list
         subject = 'Response: file'
         EMAIL_HOST='outlook.office365.com'
         EMAIL_PORT=587
         SMTPSecure = 'tls'
         EMAIL_HOST_USER = "******"
         EMAIL_HOST_PASSWORD = "******"
         EMAIL_USE_TLS = True
         connection = get_connection(host=EMAIL_HOST,port=EMAIL_PORT,username=EMAIL_HOST_USER,password=EMAIL_HOST_PASSWORD,use_tls=EMAIL_USE_TLS) 
         email = EmailMessage(subject, context,'*****@*****.**',sender_email_id,connection=connection)
         email.attach_file(attachment)
         email.send(fail_silently=False)
         return 'true'
コード例 #12
0
ファイル: __init__.py プロジェクト: rfaga/deloslib
def send_mail(subject, recipient_persons, template_path=None, context_dict={}, 
              fail_silently=False, content_type='html', cc_persons=None, 
              template_string=None, reply_to=None, from_person=None, bcc=False):
    if template_path:
        temp = loader.get_template(template_path)
    elif template_string:
        temp = Template(template_string)
    context_dict['site'] = Site.objects.get_current()
    context = Context(context_dict)
    msg = temp.render(context).encode('utf-8')
    try:
        recipient_list = ["%s <%s>" % (p.name, p.get_email()) for p in recipient_persons]
    except:
        recipient_list = ["%s <%s>" % (recipient_persons.name, recipient_persons.get_email())]
    if cc_persons:
        cc_list = ["%s <%s>" % (p.name, p.get_email()) for p in cc_persons]
    else:
        cc_list = None
    
    headers = {}
    if reply_to:
        headers['reply-to'] = "%s <%s>" % (reply_to.name, reply_to.get_email())
    
    if from_person:
        from_email = "%s <%s>" % (from_person.name, from_person.get_email())
        headers['from'] = from_email
    else:
        from_email = settings.EMAIL_FROM
    
    if not bcc:
        email = EmailMessage(subject=subject, body=msg, from_email=from_email,
                to=recipient_list, cc=cc_list, headers=headers)
    else:
        email = EmailMessage(subject=subject, body=msg, from_email=from_email,
                bcc=recipient_list, cc=cc_list, headers=headers)
    email.content_subtype = content_type
    email.encoding = 'utf-8'
    
    email.send(fail_silently=fail_silently)
コード例 #13
0
    def send(self,
             subject,
             body,
             recipients,
             cc_recipients=[],
             bcc_recipients=[],
             body_type=BODY_TYPE_HTML):
        if self.email_class is None:
            raise NotImplementedError

        email = self.email_class(self.service, None)
        return email.send(subject, body, recipients, cc_recipients,
                          bcc_recipients, body_type)
コード例 #14
0
def send_error_report(_from, _to, _subject, _uploaddatetime, _uploadtype,
                      _error):
    if _uploadtype == 'vehicle':
        ut = 'Fahrzeugdaten'
    if _uploadtype == 'his':
        ut = 'Reparaturarbeiten'
    if _uploadtype == 'workshop':
        ut = 'Werkstattdaten'
    ctx = {
        'title': _subject,
        'uploaddate': _uploaddatetime.strftime('%d.%m.%Y'),
        'uploadtime': _uploaddatetime.strftime('%H:%M:%S'),
        'uploadtype': ut,
    }
    htmly = get_template('email-templates/error_report.html')
    html_content = htmly.render(ctx)
    email = EmailMessage(_subject, html_content, _from, _to)
    if _error:
        a = create_attachment(_error)
        email.attach('Importfehler.csv', a.getvalue(), 'text/csv')
    email.content_subtype = 'html'
    email.send()
    return None
コード例 #15
0
def send_mail_to_applicants(
    data,
    company_obj,
    mail_obj=None,
):
    if not mail_obj:
        try:
            mail_obj = AdminEmails.objects.filter(default_email=True,
                                                  company__id=company_obj)[0]
        except Exception as e:
            logger.info(e)
        try:
            if not mail_obj:
                mail_obj = AdminEmails.objects.all()[0]
        except Exception as e:
            logger.info(e)
            return
    backend = EmailBackend(host=mail_obj.host_address,
                           port=mail_obj.port_no,
                           username=mail_obj.email,
                           password=mail_obj.password,
                           use_tls=mail_obj.use_tls,
                           fail_silently=False)
    # with custom details (to_email, subject, message/body)
    for j in [i for i in data]:
        to = []
        to.append(j['to'])  # receiver email
        message = j['msg']  # email body
        mail_subject = j['subject']  # email subject
        email = EmailMultiAlternatives(mail_subject,
                                       message,
                                       from_email=mail_obj.email,
                                       to=to,
                                       connection=backend)
        email.attach_alternative(message, 'text/html')
        email.send()
    return
コード例 #16
0
ファイル: email_mailbox.py プロジェクト: jzoldyck/netforce
 def send_emails(self, ids, context={}):
     for email in get_model("email.message").search_browse(
         [["state", "=", "to_send"], ["mailbox_id", "in", ids]], order="id"
     ):
         email.send()
コード例 #17
0
ファイル: seret_scraper.py プロジェクト: amirdev79/righhear
def parse_theaters():
    all_theaters_response = requests.get(ALL_THEATERS_URL)
    b = BeautifulSoup(all_theaters_response.content, 'html.parser')
    mc = b.find('div', {'id': 'maincontent'})
    per_city = {}
    theaters = []
    current_city = ''
    for d in mc.find_all('div'):
        if d.attrs.get('class') and d.attrs.get('class')[0] == 'cityname':
            city_name = d.find('a').contents[0]
            current_city = city_name
            per_city[city_name] = []
            lastd = d
        elif d.attrs.get('class') and d.attrs.get('class')[0] == 'trow':
            theater_name_heb = d.find('a').contents[0]
            link = d.find('a').attrs['href']
            address = d.find('span', {'style': 'float:right;width:20%;margin-top:4px;margin-right:10px;'}).contents[
                0]
            gmaps_address = get_gmaps_info(address)
            if gmaps_address:
                address_arr = gmaps_address['formatted_address'].split(',')
                theater_city_heb = current_city
                theater_address_eng = address_arr[0]
                lat = gmaps_address['lat']
                lng = gmaps_address['lng']
            phone_elements = d.find_all('span', {'class': 'DarkGreen12'})[1:]
            phone_theater = phone_elements[0].contents[0].replace('טלפון: ', '') if phone_elements[
                0].contents else None
            phone_tickets = phone_elements[0].contents[2].replace("טל' כרטיסים: ", '') if len(
                phone_elements[0].contents) == 3 else None
            # phone_tickets =  phone_elements[0].contents[0].replace("טל' כרטיסים: ", '') if phone_tickets_elements else None

            # phone_tickets =
            # phone_theater, phone_tickets = phone_elements.contents[0].replace('טלפון: ', ''), phone_elements.contents[2].replace("טל' כרטיסים: ", ''),
            theaters.append(
                {'name_heb': theater_name_heb,
                 'city_heb': theater_city_heb,
                 'street_address': theater_address_eng,
                 'longitude': lng,
                 'latitude': lat,
                 'additional_info': {'phone_tickets': phone_tickets, 'scraper_name_heb': theater_name_heb},
                 'phone_number': phone_theater})

    theaters_lines = [','.join(CSV_THEATER_FIELDS)]
    for theater in theaters:
        theaters_lines.append(
            ','.join(['"' + str((theater.get(field, '') or '')).replace('"', '""').strip() + '"' for field in
                      CSV_THEATER_FIELDS]))

    theaters_csv_file = tempfile.NamedTemporaryFile(suffix='.csv')
    with open(theaters_csv_file.name, 'w+') as f:
        f.write('\n'.join(theaters_lines))

    email = EmailMessage(
        'Seret Theaters list',
        'See attached CSV. please update all the missing fields',
        settings.DEFAULT_EMAIL,
        [settings.DEFAULT_EMAIL],
    )
    email.attach_file(theaters_csv_file.name)
    email.send()
コード例 #18
0
 def send_emails(self, ids, context={}):
     for email in get_model("email.message").search_browse([["state", "=", "to_send"], ["mailbox_id", "in", ids]], order="id"):
         email.send()
コード例 #19
0
        msg_to_send['Subject'] = self.subject
        msg_to_send.attach(MIMEText(self.text))

        connect = smtplib.SMTP("smtp.gmail.com", 587)
        connect.ehlo()
        connect.starttls()
        connect.ehlo()
        connect.login(login, password)
        connect.sendmail(login, connect, msg_to_send.as_string())
        connect.quit()

    def receive(self, login, password, header=None):
        connect = imaplib.IMAP4_SSL("imap.gmail.com")
        connect.login(login, password)
        connect.list()
        connect.select("inbox")
        search_subject = '(HEADER Subject "%s")' % header if header else 'ALL'
        result, data = connect.uid('search', None, search_subject)
        assert data[0], 'There are no letters with current header'
        latest_email_uid = data[0].split()[-1]
        result, data = connect.uid('fetch', latest_email_uid, '(RFC822)')
        raw_email = data[0][1]
        email_message = email.message_from_string(raw_email)
        connect.logout()


if __name__ == "__main__":
    email = Email('*****@*****.**', ['*****@*****.**', '*****@*****.**'],
                  'Subject', 'Message')
    email.send('*****@*****.**', 'qwerty')
    email.receive('*****@*****.**', 'qwerty')
コード例 #20
0
def read_data():
    email = EmailMessage(
        subject='This is the mail subject',
        body='This is the body of the message',
        from_email=settings.EMAIL_HOST_USER,
        to=['*****@*****.**'],
        cc=['*****@*****.**'],
        #reply_to=['*****@*****.**'],  # when the reply or reply all button is clicked, this is the reply to address, normally you don't have to set this if you want the receivers to reply to the from_email address
    )
    email.send(fail_silently=False)
    #email.content_subtype = 'html' # if the email body contains html tags, set this. Otherwise, omit it
    # try:
    #     email.send(fail_silently=False)
    #     return HttpResponseRedirect('/')
    # except Exception:
    #     print(traceback.format_exc())
    detach_dir = './media/pdf/'  #where the pdf content will save
    m = imaplib.IMAP4_SSL("outlook.office365.com")
    m.login('yourmail', '######')
    m.select("inbox")

    resp, items = m.search(None, 'UNSEEN')  #ALL
    items = items[0].split()

    for emailid in items:
        resp, data = m.fetch(emailid, "(RFC822)")
        email_body = data[0][1]
        mail = email.message_from_bytes(email_body)
        #temp = m.store(emailid,'+FLAGS', '\\Seen')
        m.expunge()

        if mail.get_content_maintype() != 'multipart':
            continue
        #extract the exect mail
        re_mail = re.search("<.*>", mail["From"])
        re_mail = re_mail.group(0)[1:-1]
        if re_mail == 'yourmail.com':
            broker_add = UserEmail.objects.get_or_create(title=mail["Subject"],
                                                         email=re_mail)[0]
            broker_add.save()
            print("Brokers Email Address : ", re_mail)
            print("Brokers Email subject : ", mail["Subject"])
            print("Brokers Email Date : ", mail["Date"])
            print(dateparser.parse(mail["Date"]))
            for part in mail.walk():
                if part.get_content_maintype() == 'multipart':
                    continue
                if part.get('Content-Disposition') is None:
                    continue

                filename = part.get_filename()
                filetype = re.search(".pdf", filename)
                print(filetype)
                if filetype:
                    att_path = os.path.join(detach_dir, filename)
                    print(att_path)
                    save_pdf = Pdf.objects.get_or_create(user=broker_add,
                                                         pdf=att_path,
                                                         date=dateparser.parse(
                                                             mail["Date"]))[0]
                    save_pdf.save()
                    if not os.path.isfile(att_path):
                        fp = open(att_path, 'wb')
                        fp.write(part.get_payload(decode=True))
                        fp.close()
                else:
                    continue
コード例 #21
0
ファイル: views.py プロジェクト: daweili1117/draft
def payment_process(request):
    order_id = request.session.get('order_id')
    order = get_object_or_404(Order, id=order_id)

    if request.method == 'POST':
        # retrieve nonce
        nonce = request.POST.get('payment_method_nonce', None)
        # create and submit transaction
        result = braintree.Transaction.sale({
            'amount': '{:.2f}'.format(order.get_total_cost()),
            'payment_method_nonce': nonce,
            'options': {
                'submit_for_settlement': True
            }
        })
        if result.is_success:
            # mark the order as paid
            order.paid = True
            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()
            # create invoice e-mail
            subject = 'IndianExpress - Invoice no. {}'.format(order.id)
            message = 'Thank you for shopping at Indianexpress.' \
                      'Your payment has been processed successfully. ' \
                      'Invoice no. {}'.format(order.id)
            email = EmailMessage(subject,
                                 message,
                                 '*****@*****.**',
                                 [order.email])

            # if request.method == 'Get':
            #     form = OrderCreateForm(request.GET)
            #     if form.is_valid():
            #         first_name = form.cleaned_data.get('first_name')
            #         last_name = form.cleaned_data.get('last_name')
            #         email = form.cleaned_data.get('email')
            #         address = form.cleaned_data.get('address')
            #         postal_code = form.cleaned_data.get('postal_code')
            #         city = form.cleaned_data.get('city')
            #         ctx = {
            #             'first_name': first_name,
            #             'last_name': last_name,
            #             'email': email,
            #             'address': address,
            #             'postal_code': postal_code,
            #             'city': city,
            #         }
            #
            # message = render_to_string('indianexpress/orderconfrim.txt', ctx)
            # send_mail('Your Order with IndianXpress',
            #             message,
            #             '*****@*****.**',
            #             [email],)
            # return render(request, 'payment/done.html', ctx)
            #




        #
        #
        #  # create invoice e-mail
        #  subject = 'Indianexpress - Invoice no. {}'.format(order.id)
        #
        #  message = 'Thank you for shopping at Indianexpress.' \
        #            ' Your payment has been processed successfully. ' \
        #            'Invoice no. {}'.format(order.id)
        #
        #  email = EmailMessage(subject,
        #                       message,
        #                       '*****@*****.**',
        #                       [order.email])
        #  # generate PDF
        #  # html = render_to_string('orders/order/pdf.html', {'order': order})
        #  # out = BytesIO()
        #  # stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]
        #  # weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets)
        #
        #  # attach PDF file
        # # email.attach('order_{}.pdf'.format(order.id),
        # #              out.getvalue(),
        # #              'application/pdf')
        #  # send e-mail

            email.send()
            return redirect('payment:done')

        else:
            return redirect('payment:canceled')
    else:
        # generate token
        client_token = braintree.ClientToken.generate()
        return render(request,
                      'payment/process.html',
                      {'order': order,
                       'client_token': client_token})