Ejemplo n.º 1
0
def validate_email_fields(provided_fields):
    # A list of class attributes from the Email model.
    required_fields = list(vars(Email()).keys())
    provided_fields = list(provided_fields)

    # Two email fields, namely: `to` and `from`, are equivalently
    # `to_email` and `from_email` in our data model.
    for i in range(len(provided_fields)):
        if provided_fields[i] == "to":
            provided_fields[i] = "to_email"
        if provided_fields[i] == "from":
            provided_fields[i] = "from_email"

    if provided_fields != required_fields:
        return False

    return True
Ejemplo n.º 2
0
def populate_contacts():
    random_value = str(random.randint(0, 1000))
    data = {
        'first_name': 'first_name_' + random_value,
        'last_name': 'last_name_' + random_value,
        'username': '******' + random_value,
    }
    emails = [random_value + '@test.com', random_value + '@test.co.uk']
    new_contact = Contact(**data)
    db.session.add(new_contact)

    for address in emails:
        new_email = Email(address, new_contact)
        db.session.add(new_email)

    db.session.commit()

    print("Created new contact")
Ejemplo n.º 3
0
def email_list_data():
    with apps.app_context():

        val = redis.rpop("email_list")

        while (val is not None):

            json_obj = json.loads(val)
            email_from = json_obj['email_from']
            email_to = json_obj['email_to']

            if type(email_to) is unicode:
                email_to = email_to.split(',')

            email_subject = json_obj['email_subject']
            email_body = json_obj['email_body']
            email_type = json_obj['email_type']
            email_password = json_obj['email_password']

            apps.config.update(
                DEBUG=True,
                #EMAIL SETTINGS
                MAIL_SERVER='smtp.gmail.com',
                MAIL_PORT=465,
                MAIL_USE_SSL=True,
                MAIL_USERNAME=email_from,
                MAIL_PASSWORD=email_password)

            mail = Mail(apps)
            send_email(email_subject, email_from, email_password, email_body,
                       email_to)

            em = Email(email_subject=email_subject,
                       email_to=email_to,
                       email_from=email_from,
                       email_body=email_body,
                       email_type=email_type)
            em.save()

            val = redis.rpop("email_list")

        return 0
Ejemplo n.º 4
0
def email_validate(statu, recieve_email=None):
    if recieve_email is None:
        if statu == 'activate':
            form = EmailValidateForm()
            if request.method == 'POST':
                if form.validate_on_submit():
                    return redirect('/validator/validation/%s' %
                                    form.email.data)
            return render_template('validate.html',
                                   title='Validate the email',
                                   form=form)
    else:
        e = Email()
        e.email = recieve_email
        if statu == 'validation':
            if not e.is_exist():
                e.generate_password()
                email_msg = Message(recipients=[recieve_email],
                                    subject='OPEN ACCESS PUBLISH validation ')
                email_msg.body = 'CLICK HERE TO VALIDATE'
                email_msg.html = "<h1>Activation</h1><p><a href='http://jinmingyi.xin:8080/captcha/%s'>Click to activate</a></p>" % e.password
                sendEmail(email_msg)
                e.validate_time = datetime.datetime.now()
                db.session.add(e)
                db.session.commit()
                return "We've already send you an validation email"
            elif not e.is_validated():
                return "<a href='/validator/resend/%s'>Didn't receive email?</a>" % recieve_email
            else:
                abort(404)
        elif statu == 'resend':
            if e.is_exist():
                if not e.is_validated():
                    email_msg = Message(
                        recipients=[recieve_email],
                        subject='OPEN ACCESS PUBLISH validation ')
                    email_msg.body = 'CLICK HERE TO VALIDATE'
                    email_msg.html = "<h1>Activation</h1><p><a href='http://jinmingyi.xin:8080/captcha/%s'>Click to activate</a></p>" % e.password
                    sendEmail(email_msg)
                    return "We've already send you an validation email"
            abort(404)
    abort(404)
Ejemplo n.º 5
0
def new_email(contact_id):
    data = contact_id.split('"')[-2:]
    id = data[0]
    my_email = Email.query.filter(Email.contact_id == contact_id).first()
    form = AddEmailForm(obj=my_email)

    if form.validate_on_submit():
        # create Email Object
        my_email = Email()
        form.populate_obj(my_email)
        database.session.add(my_email)
        try:
            database.session.commit()
            flash('Save Successfully', 'success')
            return redirect(url_for('emails', contact_id=id))
        except:
            database.session.rollback()
            flash('Error! ', 'danger')

    return render_template('web/new_email.html', form=form)
Ejemplo n.º 6
0
def write():
    if request.method == "POST":
        sendto = request.form['sendto']
        receive_man = User.query.filter_by(email=sendto).first()
        if receive_man:
            from_man = session['email']
            theme = request.form['theme']
            content = request.form['content']
            try:
                file = request.files['file']
            except:
                filename = None
            else:
                file_save_path = path.join(app.config['FILM_SOURCE_URI'], file.filename)
                file.save(file_save_path)
                filename = file.filename

            fo = Folder.query.filter_by(user_id=receive_man.id, name='默认收件箱').first()
            email = Email(send_man=from_man, attachment=filename, theme=theme, content=content, user_id=receive_man.id,
                          folder_id=fo.id)
            db.session.add(email)
            db.session.commit()
            flash(' *发送邮件成功!')
            linkman = Linkman.query.filter_by(user_id=receive_man.id).first()
            if linkman:
                linkman.last_contact = datetime.now()
                db.session.add(linkman)
                db.session.commit()
            else:
                lm = Linkman(email=receive_man.email, remark=receive_man.email, user_id=session["id"])
                db.session.add(lm)
                db.session.commit()
            global recent_linkmans
            recent_linkmans = Linkman.query.filter_by(user_id=session['id']).order_by(desc(Linkman.last_contact)).limit(
                6).all()
            return redirect(url_for('write'))
        else:
            flash(' *收信人不存在!')
            return redirect(url_for('write'))
    else:
        return render_template('write.html', folders=folders, recent_linkmans=recent_linkmans)
Ejemplo n.º 7
0
def compose(type_):
	if request.method == "GET" and type_ == "new":
		return render_template("emails/compose.html")
	elif request.method == "POST":
		receiver_email = request.form["receiver_email"]
		receiver = User.query.filter_by(email=receiver_email).first()
		if not receiver:
			if type_ == "new":
				return render_template("emails/compose.html",invalid_email=True)
			elif type_ == "email":
				return render_template("emails/showEmails.html",invalid_email=True)
		title = request.form["title"]
		description = request.form["description"]
		email = Email(sender_id=current_user.id,
					  receiver_id=receiver.id,
					  title=title,
					  description=description)
		session = db.create_scoped_session()
		session.add(email)
		session.commit()
		return redirect(url_for("showEmails",receiver_id=receiver.id))
Ejemplo n.º 8
0
 def register(self,
              emailtype,
              senderid,
              receiveremailid,
              subject,
              body,
              attachment=None):
     senderemailid = str(senderid) + '@' + constants.EMAIL_DOMAIN_APPSPOT
     email = Email()
     email.senderemailid = senderemailid
     email.receiveremailid = receiveremailid
     email.typeid = emailtype
     email.emailupdated = False
     email.subject = db.Text(subject)
     email.body = db.Text(body)
     if attachment:
         email.filename = attachment.filename
     logging.info('adding emailtype=' + str(emailtype) \
      + ', receiveremailid=' + str(receiveremailid) \
      + ', subject=' + str(subject))
     email.put()
     return 1
Ejemplo n.º 9
0
def submit(request):
    string = request.GET.get("email", "")
    string_type = request.GET.get("type", "")

    # check token #
    token = request.GET.get("nonce", "")
    if "token" not in request.session:
        return HttpResponse("Invalid token")
    elif token != request.session['token']:
        return HttpResponse("Invalid token")
    else:   #valid token
        del request.session['token']

    if len(Email.objects.filter(email=string)) == 0 and general_util.validate_register_email(string):
        email = Email()
        gSheet_services.add_email(string, string_type)
        email.email = string
        email.save()
        return HttpResponse("Success")
    else:
        if not general_util.validate_register_email(string):
            return HttpResponse("Error")
        else:
            return HttpResponse("Dup")
Ejemplo n.º 10
0
def create_person(name, age, mail):
    output = {'person': None, 'ok': False, 'mail': mail, 'message': ''}
    person = db_session.query(Person).filter(
        Person.name == name,
        Person.age == age,
    ).order_by(Person.id.desc()).first()

    if person:
        output.update({'person': person, 'message': 'Person already added.'})
        return output

    mail_parts = mail.split('@')
    if len(mail_parts) != 2:
        output.update({'message': 'Incorrect mail provided.'})
        return output

    username, domain = mail_parts
    domain_parts = domain.split('.')
    if len(domain_parts) != 2:
        output.update({'message': 'Incorrect mail provided.'})
        return output

    person = Person(name=name, age=age)
    db_session.add(person)
    db_session.flush()

    email = Email(email=mail, person_id=person.id)
    db_session.add(email)

    db_session.commit()
    output.update({
        'ok': True,
        'person': person,
        'message': 'Person added successfully.'
    })
    return output
Ejemplo n.º 11
0
    def deserialize(self, import_buffer, target_class, tenant):
        result = ImportResult()
        EMAIL_TYPES = tuple(t[0] for t in Email.TYPES)
        PHONE_TYPES = tuple(t[0] for t in Phone.TYPES)
        PHONE_SUBTYPES = tuple(t[0] for t in Phone.SUBTYPES)
        ADDRESS_TYPES = tuple(t[0] for t in Address.TYPES)
        for vcard in vobject.readComponents(import_buffer):
            if issubclass(vcard.behavior, vobject.vcard.VCard3_0):
                contact = target_class(tenant=tenant)
                try:
                    if isinstance(contact, Contact):
                        assert vcard.getChildValue('n').family
                        assert vcard.getChildValue('n').given
                        contact.name = vcard.getChildValue('n').family
                        contact.firstname = vcard.getChildValue('n').given
                        contact.additional_names = vcard.getChildValue(
                            'n').additional or None
                        # Handle organizations ?
                        if vcard.getChildValue('bday'):
                            contact.birthday = parse(vcard.bday.value)
                    if isinstance(contact, Organization):
                        assert vcard.getChildValue('org')
                        contact.corporate_name = vcard.getChildValue('org')

                    emails = vcard.contents.get(toVName('email')) or []
                    for email in emails:
                        email_type = None
                        try:
                            email_type = email.type_param
                        except:
                            pass
                        contact.emails.append(
                            Email(type=email_type
                                  if email_type in EMAIL_TYPES else None,
                                  email=email.value))

                    phones = vcard.contents.get(toVName('tel')) or []
                    for phone in phones:
                        phone_types = []
                        phone_type = None
                        phone_subtype = None
                        try:
                            phone_types = phone.type_paramlist
                            for ptype in phone_types:
                                if ptype in PHONE_TYPES and not phone_type:
                                    phone_type = ptype
                                elif ptype in PHONE_SUBTYPES and not phone_subtype:
                                    phone_subtype = ptype
                        except:
                            pass
                        contact.phones.append(
                            Phone(type=phone_type,
                                  subtype=phone_subtype,
                                  phone=phone.value))

                    addresses = vcard.contents.get(toVName('adr')) or []
                    for address in addresses:
                        address_type = None
                        try:
                            address_type = address.type_param
                        except:
                            pass
                        contact.addresses.append(
                            Address(type=address_type
                                    if address_type in ADDRESS_TYPES else None,
                                    postoffice_box=address.value.box,
                                    street_address=address.value.street,
                                    extended_address=address.value.extended,
                                    postal_code=address.value.code,
                                    city=address.value.city,
                                    state=address.value.region,
                                    country=address.value.country))
                    contact.save()
                    result.success.append(contact)
                except:
                    record_name = vcard.getChildValue('fn')
                    if not record_name:
                        name = vcard.getChildValue('n').family
                        firstname = vcard.getChildValue('n').given
                        if name and firstname:
                            record_name = u'%s %s' % (firstname, name)
                        elif name:
                            record_name = name
                        elif firstname:
                            record_name = firstname
                    if not record_name:
                        try:
                            record_name = vcard.getChildValue('org')[0]
                        except:
                            pass
                    if not record_name:
                        record_name = _('No name')
                    result.errors.append(record_name)
        return result
Ejemplo n.º 12
0
def incoming(request):
    """
    Accept a new email message directly via the AppEngine email facility. The
    entire email message is contained in the POST body of *email*.
    
    :param HttpRequest request: A web request.
    :rtype: An HttpResponse object.
    """
    logging.info('Incoming email received.')

    try:
        msg = InboundEmailMessage(request.raw_post_data)

        usetting = UserSetting.gql('WHERE email = :1', msg.sender)
        if usetting.count() == 0:
            logging.warn('Received email from an unrecognized sender: ' +
                         msg.sender)

            return render_to_response('msg_receipt.email',
                                      mimetype='text/plain')

        if not usetting.get().is_contrib:
            logging.warn('Received email from an unauthorized contributor: ' +
                         msg.sender)

            return render_to_response('msg_receipt.email',
                                      mimetype='text/plain')

        content = ''
        for content_type, body in msg.bodies('text/plain'):
            headers = True
            date = False
            for line in str(body).split('\n'):
                if not date:
                    parts = line.split(' ')
                    line = ' '.join(parts[len(parts) - 5:])
                    date = datetime.strptime(line, '%a %b %d %H:%M:%S %Y')
                    logging.debug(str(date))

                if headers and line == '':
                    headers = False
                elif not headers:
                    content += '%s\n' % line

        if content == '':
            logging.warn('Received an email, but no text/plain bodies.')
        else:
            logging.info('Compiled plain-text email: body length=%d' %
                         len(content))

            newtitle = msg.subject.replace('\n', '').replace('\r', '')
            content = content.lstrip('\t\n\r ')
            email = Email(title=newtitle,
                          body=content,
                          date=date,
                          views=0,
                          rating=0)
            email.put()

            logging.info('Processing new data for tokens & tags')

            _process_new(email)

    except Exception, ex:
        logging.error('Error processing new email. %s' % ex)
Ejemplo n.º 13
0
def test_forward(mock_body, mock_html, mock_get):
    email = Email('message_id', 'to', Email.CONFIRMATION_SUBJECT_TEXT)
    to = '*****@*****.**'
    cc = '*****@*****.**'
    email.forward(to, cc)
Ejemplo n.º 14
0
def test_email_is_confirmation():
    email = Email('message_id', 'to', Email.CONFIRMATION_SUBJECT_TEXT)
    assert email.is_confirmation
Ejemplo n.º 15
0
                    birthday=user.birthday,
                    created_at=user.signup_date,
                    is_active=user.is_active)
    if user.default_locale_id:
        new_user.default_locale_id = user.default_locale_id
    DBSession.add(new_user)
DBSession.flush()
for client in old_DBSession.query(old_Client).all():
    new_client = Client(id=client.id,
                        user_id=client.user_id,
                        created_at=client.creation_time,
                        is_browser_client=client.is_browser_client)
    DBSession.add(new_client)
DBSession.flush()
for email in old_DBSession.query(old_Email).all():
    new_email = Email(id=email.id, user_id=email.user_id, email=email.email)
    DBSession.add(new_email)
DBSession.flush()
for passhash in old_DBSession.query(old_Passhash).all():
    new_passhash = Passhash(id=passhash.id,
                            user_id=passhash.user_id,
                            hash=passhash.hash)
    DBSession.add(new_passhash)
DBSession.flush()
for userblob in old_DBSession.query(old_UserBlobs).all():
    new_userblob = UserBlobs(client_id=userblob.client_id,
                             created_at=userblob.created_at,
                             name=userblob.name,
                             content=userblob.content,
                             real_storage_path=userblob.real_storage_path,
                             data_type=userblob.data_type,
Ejemplo n.º 16
0
from models import storage, Search, Email
from datetime import datetime

if __name__ == "__main__":
    testEmail = Email()
    setattr(testEmail, "email", "*****@*****.**")
    setattr(testEmail, "time_stamp", datetime.utcnow())
    storage.new(testEmail)
    storage.save()
    print(storage.query_object(Email))
Ejemplo n.º 17
0
def publish():
    '''
    If recieve a post, then regard as a publish form.
    A form will create an article class and do related work
    :return:
    '''
    if not check_session(3):
        abort(404)
    form = UploadForm()
    captcha = getCaptcha()
    msg = "You should only upload a pdf file"
    if request.method == 'POST':
        if form.validate_on_submit():
            e = Email(email=form.email.data)
            if e.is_exist() and e.is_validated():
                # Every module below are independent

                # generate an article and add it
                article = form.to_Article()
                for s in CSsubject:
                    if s == article.subject:
                        article.subject = 'Computer Sciences'
                article.id = str(1)
                a_num = int(Article.query.count())
                if a_num > 0:
                    article.id = str(
                        int(
                            Article.query.order_by(
                                Article.id.desc()).first().id) + 1)
                article.pdf = str(article.id) + '.pdf'
                filename = os.path.join(app.root_path, "static", "pdf",
                                        article.id + '.pdf')
                form.file.data.save(filename)
                db.session.add(article)

                # if a subject is not exist, then create it
                sub = Subject.query.filter_by(name=article.subject).first()
                if sub is None:
                    sub = Subject()
                    sub.name = article.subject
                    sub.super_subject = 0
                    sub.depth = 0
                    db.session.add(sub)

                # generate a record and add it
                record = IpRecord()
                record.ip = request.remote_addr
                record.page = "publish"
                record.target_id = int(article.id)
                db.session.add(record)

                # after all work done, commit it
                db.session.commit()

                # send email
                email_msg = Message(
                    recipients=[form.email.data],
                    subject='[OPEN ACCESS PUBLISH]Publish notification')
                email_msg.body = 'CLICK HERE TO VALIDATE'
                email_msg.html = "<h1>Notification</h1><p>You have published an <a href='http://jinmingyi.xin:8080/detail/%s'>article</a></p>" % (
                    str(article.id))
                sendEmail(email_msg)

                return redirect('/detail/' + str(article.id))
            else:
                msg = "You must activate your email address before you publish"

    return render_template('publish.html',
                           form=form,
                           title='Publish',
                           message=msg,
                           captcha=captcha)
Ejemplo n.º 18
0
def test_email_is_try_again():
    email = Email('message_id', 'to', Email.TRY_AGAIN_SUBJECT_TEXT)
    assert email.is_try_again
Ejemplo n.º 19
0
def test_email_is_winner():
    email = Email('message_id', 'to', Email.WINNER_SUBJECT_TEXT)
    assert email.is_winner
Ejemplo n.º 20
0
 def mark_in_database(self, subject='', to_email=''):
     email = Email(subject=subject, to_email=to_email)
     email.save()
Ejemplo n.º 21
0
def test_email_is_lottery_entry_received():
    email = Email('message_id', 'to', Email.LOTTERY_ENTRY_RECEIVED_TEXT)
    assert email.is_lottery_entry_recieved
Ejemplo n.º 22
0
def create_new_email(address, contact):
    new_email = Email(address, contact)
    db.session.add(new_email)
    db.session.commit()
    return new_email
Ejemplo n.º 23
0
def test_make_confirmation_request(mock_html, mock_get):
    email = Email('message_id', 'to', Email.CONFIRMATION_SUBJECT_TEXT)
    email.make_confirmation_request()
Ejemplo n.º 24
0
def test_email_is_lottery_payment_confirmation():
    email = Email('message_id', 'to', Email.LOTTERY_PAYMENT_CONFIRMATION)
    assert email.is_lottery_payment_confirmation