def newsletter_subscribe():
    password = request.form['password']
    email = request.form['mail']
    if password == app.config["NEWSLETTER_PASSWORD"]:
        if not validate_email(email, verify=True):
            app.logger.warn("Email verification failed for '%s'" % email)
            return redirect(app.config["NEWSLETTER_VERIFY_FAILED_PATH"])

        app.logger.info("Subscribing %s" % email)

        if not app.debug:
            client = mailmanclient.Client(app.config["MAILMAN_REST_URL"],
                                          app.config["MAILMAN_REST_USER"],
                                          app.config["MAILMAN_REST_PASS"])
            newsletterList = client.get_list(
                app.config["NEWSLETTER_LIST_NAME"])

            try:
                newsletterList.get_member(email)
            except ValueError:
                newsletterList.subscribe(email, pre_approved=True)
            else:
                app.logger.warn("Already subscribed: %s", email)
                return redirect(
                    app.config["NEWSLETTER_ALREADY_SUBSCRIBED_PATH"])

        return redirect(app.config["NEWSLETTER_SUCCESS_PATH"])
    else:
        return redirect(app.config["NEWSLETTER_FAIL_PATH"])
Beispiel #2
0
def newsletter_subscribe():
    password=request.form['password']
    email=request.form['mail']
    if password == app.config["NEWSLETTER_PASSWORD"]:
        if not validate_email(email, verify=True):
            app.logger.warn("Email verification failed for '%s'" % email)
            return redirect(app.config["NEWSLETTER_VERIFY_FAILED_PATH"])

        app.logger.info("Subscribing %s" % email)

        if not app.debug:
            client = mailmanclient.Client(
                    app.config["MAILMAN_REST_URL"],
                    app.config["MAILMAN_REST_USER"],
                    app.config["MAILMAN_REST_PASS"])
            newsletterList = client.get_list(app.config["NEWSLETTER_LIST_NAME"])

            try:
                newsletterList.get_member(email)
            except ValueError:
                newsletterList.subscribe(email, pre_approved=True)
            else:
                app.logger.warn("Already subscribed: %s", email)
                return redirect(app.config["NEWSLETTER_ALREADY_SUBSCRIBED_PATH"])

        return redirect(app.config["NEWSLETTER_SUCCESS_PATH"])
    else:
        return redirect(app.config["NEWSLETTER_FAIL_PATH"])
 def test_smtp_validation_invalid(self):
     self.assertIsNotNone(DNS, 'PyDNS must be installed to run this test!')
     for email_address in self.invalid_addresses:
         result = validate_email(email_address, check_mx=True, verify=True)
         if result is None:
             pass
         else:
             self.assertFalse(result)
Beispiel #4
0
 def clean_your_email(self):
     data = self.cleaned_data['your_email']
     is_email_valid = validate_email(self.cleaned_data['your_email'],
                                     check_mx=True,
                                     verify=True)
     if not is_email_valid:
         raise forms.ValidationError(
             "This email address could not be verified!!")
     return data
Beispiel #5
0
def rsvp():
    """POST route handling the json request to dispatch an email.

    """
    try:
        json_data = request.get_json()
        json_data['message']['to'] = [{
            'email': EMAIL,
            'name': NAME,
            'type': 'to'
        }]
        if not validate_email(json_data['message']['from_email']):
            raise Exception('Malformed Data')
        else:
            # Log messages to sqlite3 database too...
            try:
                conn = sqlite3.connect('message_log.db')
                with conn:
                    ipaddr = request.remote_addr
                    conn.execute(
                        "INSERT INTO message_log VALUES(null, ?, ?, ?)", [
                            json_data['message']['text'], ipaddr,
                            json_data['message']['from_email']
                        ])
            except Exception, e:
                LOGGER.error('Error: Connecting to message log'
                             'database. Continuing: ' + e.message)

            # Send via Mandrill API
            json_data['key'] = MANDRILL_KEY
            headers = {
                'Content-type': 'application/json',
                'Accept': 'text/plain',
                'charset': 'utf8'
            }
            res = requests.post(MANDRILL_POST_URL,
                                data=json.dumps(json_data),
                                headers=headers)

            # Send via SMTP implementation commented below...
            '''
                import smtplib
                s = smtplib.SMTP('localhost')
                s.sendmail(EMAIL, json_data['message']['from_email'], json_data['message']['text'])
                s.quit()'''

            resp_code = res.status_code
            msg = "Request made: Trying to send... " + res.reason
            if resp_code == 400 or resp_code == 500:
                raise Exception(msg + " But can not send.")
    except Exception, e:
        LOGGER.error(e.message)
        resp_code = 400
        msg = "Bad Request: " + e.message
def email_address(email):
    """
    Verifies that the given value is a valid email address

    :param email: An email address
    :type email: str
    :return: The given value
    :rtype: str
    :raises: voluptuous.Invalid
    """
    if validate_email(email):
        return email
    else:
        raise Invalid("Invalid email address")
def email_address(email):
    """
    Verifies that the given value is a valid email address

    :param email: An email address
    :type email: str
    :return: The given value
    :rtype: str
    :raises: voluptuous.Invalid
    """
    if validate_email(email):
        return email
    else:
        raise Invalid("Invalid email address")
Beispiel #8
0
 def reset_data_validation(self, username, email):
     if len(username) < 4 or len(username) > 20:
         self.__errorMessage = string.username_range
         return False
     if not validate_email(email):
         self.__errorMessage = string.invalid_main
         return False
     userData = Users.query.filter_by(username=username).first()
     if not userData:
         self.__errorMessage = string.username_not_exist
         return False
     if userData.email != email:
         self.__errorMessage = string.mail_not_exist
         return False
     return True
def rsvp():
    """POST route handling the json request to dispatch an email.

    """
    try:
        json_data = request.get_json()
        json_data['message']['to'] = [
            {'email': EMAIL, 'name': NAME, 'type': 'to'}]
        if not validate_email(json_data['message']['from_email']):
            raise Exception('Malformed Data')
        else:
            # Log messages to sqlite3 database too...
            try:
                conn = sqlite3.connect('message_log.db')
                with conn:
                    ipaddr = request.remote_addr
                    conn.execute(
                        "INSERT INTO message_log VALUES(null, ?, ?, ?)",
                        [json_data['message']['text'], ipaddr,
                            json_data['message']['from_email']])
            except Exception, e:
                LOGGER.error('Error: Connecting to message log'
                             'database. Continuing: ' + e.message)

            # Send via Mandrill API
            json_data['key'] = MANDRILL_KEY
            headers = {'Content-type': 'application/json',
                       'Accept': 'text/plain', 'charset': 'utf8'}
            res = requests.post(MANDRILL_POST_URL,
                                data=json.dumps(json_data),
                                headers=headers)

            # Send via SMTP implementation commented below...
            '''
                import smtplib
                s = smtplib.SMTP('localhost')
                s.sendmail(EMAIL, json_data['message']['from_email'], json_data['message']['text'])
                s.quit()'''

            resp_code = res.status_code
            msg = "Request made: Trying to send... " + res.reason
            if resp_code == 400 or resp_code == 500:
                raise Exception(msg + " But can not send.")
    except Exception, e:
        LOGGER.error(e.message)
        resp_code = 400
        msg = "Bad Request: " + e.message
Beispiel #10
0
def register():
    if  request.forms.get('register','').strip():
        userid = request.forms.get('userid', '').strip()
        if firebase_check_if_user_exist(userid):
            return template('register.html',error_status="The user already exist")
        else:
            password= request.forms.get('password', '').strip()
            name = request.forms.get('name','').strip()
            email = request.forms.get('email','').strip()
            if validate_email(email):
            	firebase_add_user(userid,name,password,email)
            	print "userid:", userid, " has successfully registered"
            	return template('login.html',error_status="Account has been successfully created")
            else:
            	return template('register.html',error_status="please type in correct email")
    else:
        redirect('/web/users/register')
Beispiel #11
0
def Email(error='Invalid e-mail address.',
          error_dot='Missing dot in e-mail address.',
          error_at='Missing at in e-mail address.',
          check_mx=False):
    from validate_email_address import validate_email

    commands = [
        String(min_len=5, max_len=256),
        validate(lambda v: '.' in v, error_dot),
        validate(lambda v: '@' in v, error_at),
        validate(lambda v: validate_email(v), error),
    ]

    if check_mx:
        commands.append(validate(lambda v: check_mx_records(v), error))

    return Test(commands)
def Cleaning_email_pandas(Body_):
    Body_ = str(Body_).lower()

    Body_ = re.sub(
        r'''(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))''',
        " ", Body_)
    Body_ = re.sub(
        r'''(?i)\b((?:http?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))''',
        " ", Body_)

    Body_ = [x for x in Body_ if validate_email(x) != True]
    Body_ = "".join(Body_)

    URLS = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', Body_)
    Body_ = [x for x in Body_ if x not in URLS]
    Body_ = "".join(Body_)

    Body_ = remove_text_inside_brackets(Body_, brackets="<>[]")

    #        Body_ = re.sub(r'''(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]
    #          +[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))
    #          +(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
    #          ''', " ", Body_)
    #
    for j in range(1, 5):
        try:

            New_Text = find_and_replace(Body_)
            Body_ = New_Text
        except ValueError:
            pass

    Body_ = re.sub(r"@|--|/hou/|cc:|to:|subject:|sent:|/corp/|/lon/|re:|", "",
                   Body_)
    Body_ = re.sub(r"enron@enron|/na/|enronenron|original message|from:", "",
                   Body_)

    Body_ = Remove_text_htm_end(Body_)
    Body_ = re.sub(r"--", "", Body_)

    print(Body_)

    return Body_
Beispiel #13
0
def contact():
    try:
        email = request.POST.get("email", "").strip()
        name = request.POST.get("name", "").strip()
        message = request.POST.get("message", "").strip()
        recaptcha_response = request.POST.get("g-recaptcha-response",
                                              "").strip()
        logger.info(
            'Received form:\nemail: %s\nname: %s\nip: %s\nmessage: %s' %
            (email, name, request.remote_addr, message))

        if not email:
            raise Exception('Missing email')
        elif not name:
            raise Exception('Missing name')
        elif not message:
            raise Exception('Missing message')
        elif not validate_email(email):
            raise Exception('Invalid email address')
        else:
            recaptcha_data = {
                'secret': config['recaptcha_secret'],
                'response': recaptcha_response,
                'remoteip': request.remote_addr
            }
            verify_response = requests.post(
                'https://www.google.com/recaptcha/api/siteverify',
                data=recaptcha_data)

            data = verify_response.json()
            if not data or not data['success']:
                logger.info('recaptcha response %s' % verify_response.text)
                raise Exception('Recaptcha fail')
            else:
                send_mail(config['recipient'], email, name, message)
    except Exception, e:
        logger.error(e.message)
        logger.info('no email sent')
        if e.message == 'Recaptcha fail':
            return redirect('/')
        else:
            return redirect("/#whoops")
Beispiel #14
0
def register():
    if request.forms.get('register', '').strip():
        userid = request.forms.get('userid', '').strip()
        if firebase_check_if_user_exist(userid):
            return template('register.html',
                            error_status="The user already exist")
        else:
            password = request.forms.get('password', '').strip()
            name = request.forms.get('name', '').strip()
            email = request.forms.get('email', '').strip()
            if validate_email(email):
                firebase_add_user(userid, name, password, email)
                print "userid:", userid, " has successfully registered"
                return template(
                    'login.html',
                    error_status="Account has been successfully created")
            else:
                return template('register.html',
                                error_status="please type in correct email")
    else:
        redirect('/web/users/register')
Beispiel #15
0
 def registration(self, username, password, repassword, email):
     if len(username) < 4 or len(username) > 20:
         self.__errorMessage = string.username_range
         return False
     if not validate_email(email):
         self.__errorMessage = string.invalid_main
         return False
     if password != repassword:
         self.__errorMessage = string.pass_mach
         return False
     if len(password) < 4 or len(password) > 50:
         self.__errorMessage = string.pass_range
         return False
     userCheck = Users.query.filter_by(username=username).first()
     if userCheck:
         self.__errorMessage = string.username_exist
         return False
     emailCheck = Users.query.filter_by(email=email).first()
     if emailCheck:
         self.__errorMessage = string.email_exist
         return False
     return True
Beispiel #16
0
def index(request):
    	c = {}

	c.update(csrf(request)) #gets permission for post


		    # if this is a POST request we need to process the form data
        if request.method == 'POST':
        # create a form instance and populate it with data from the request:
                form = SubscriberForm(request.POST)
        # check whether it's valid:
                if form.is_valid():
                    #check if the email is in the correct format
                	is_valid = validate_email(form.cleaned_data['emailAddress'])
                    #is_valid = validate_email('*****@*****.**',verify=True)
                        if (is_valid==True):
                            #check if the email is in the database
                            flag = Subscriber.objects.filter(email=form.cleaned_data['emailAddress']).exists()
                            if (flag == False):
                                #declare subscriber object and save it
                                sub = Subscriber(email=form.cleaned_data['emailAddress'], city=form.cleaned_data['location'])
                                sub.save()

                                #send to confirmation page once done

                                return render_to_response('weather/confirmation.html', c)




#render this page if correct informaiton is not sent
	return render_to_response('weather/signup.html', c)






# Create your views here.
Beispiel #17
0
 def post(self):
     email = self.get_body_argument('email')
     username = self.get_body_argument('username')
     password = self.get_body_argument('password')
     passwordConfirm = self.get_body_argument('passwordConfirm')
     messages = []
     user = self.user_exists(email)
     # Validations
     # if user exists
     if user:
         messages.append("Email already exists")
     # if email invalid format
     if not validate_email(email):
         messages.append("Invalid email address")
     # checks if username is not an empty string
     if username == "":
         messages.append("Input username")
     # checks if passwords match
     if password != passwordConfirm:
         messages.append("Passwords do not match")
     # checks password length is valid
     if len(password) < 8:
         messages.append("Password length must by greater than 7")
     # if errors occured, display errors and redirect to signup
     if messages:
         return self.render_template("signup.html",
                                     {'messages': tuple(messages)})
     # create hashed & salted user password
     # tornado.escape.utf8 converts string to byte string
     # https://github.com/pyca/bcrypt#password-hashing
     hashed_password = bcrypt.hashpw(tornado.escape.utf8(password),
                                     bcrypt.gensalt())
     # create user
     user = Users.create(email=email,
                         username=username,
                         hashed_password=hashed_password)
     self.set_secure_cookie("blog_user", str(user.id))
     return self.redirect("/")
Beispiel #18
0
def contact():
    try:
        email = request.POST.get("email", "").strip()
        name = request.POST.get("name", "").strip()
        message = request.POST.get("message", "").strip()
        recaptcha_response = request.POST.get("g-recaptcha-response", "").strip()
        logger.info('Received form:\nemail: %s\nname: %s\nip: %s\nmessage: %s'
                    % (email, name, request.remote_addr, message))

        if not email:
            raise Exception('Missing email')
        elif not name:
            raise Exception('Missing name')
        elif not message:
            raise Exception('Missing message')
        elif not validate_email(email):
            raise Exception('Invalid email address')
        else:
            recaptcha_data = { 'secret': config['recaptcha_secret'],
                               'response': recaptcha_response,
                               'remoteip': request.remote_addr }
            verify_response = requests.post('https://www.google.com/recaptcha/api/siteverify',
                                            data=recaptcha_data)

            data = verify_response.json()
            if not data or not data['success']:
                logger.info('recaptcha response %s' % verify_response.text)
                raise Exception('Recaptcha fail')
            else:
                send_mail(config['recipient'], email, name, message);
    except Exception, e:
        logger.error(e.message)
        logger.info('no email sent')
        if e.message == 'Recaptcha fail':
            return redirect('/')
        else:
            return redirect("/#whoops")
Beispiel #19
0
#https://pypi.python.org/pypi/validate-email-address

HOST='localhost'
DB='extraccion_emails'
USER='******'
PASSWORD=''
TARGET_TABLE='paginas_amarillas_es_es'


db=MySQLdb.connect(host=HOST, user=USER, passwd=PASSWORD, db=DB, charset="utf8", init_command = "set names utf8", cursorclass=DictCursor)
cursor=db.cursor()

cursor.execute('SELECT * FROM {0}'.format(TARGET_TABLE))

t_inicial = time.time()
counter = 0
for item in cursor:
    counter += 1
    if validate_email(item['email'],check_mx=True):
        checked = 1
    else:
        checked = 0
    try:
        cursor.execute('UPDATE {0} set checked={1} where email="{2}"'.format(TARGET_TABLE,checked,item['email']))
    except Exception as e:
        print "[err] :: {0}".format(e)
        continue
t_final = time.time()
t = t_final - t_inicial
print "{0} registros. Tiempo: {1}".format(counter,t)
Beispiel #20
0
 def valid_email(self, email, check_mx=True):
     """ Checks if the email is valid """
     return validate_email(email, check_mx=check_mx)
 def test_re_validation_invalid(self):
     for email_address in self.invalid_addresses:
         self.assertFalse(validate_email(email_address))
 def test_re_validation_valid(self):
     for email_address in self.valid_addresses:
         self.assertTrue(validate_email(email_address))
Beispiel #23
0
 def isEmailValid(self):
     return validate_email(self.__email)
Beispiel #24
0
 def clean_your_email(self):
 	data = self.cleaned_data['your_email']
 	is_email_valid = validate_email(self.cleaned_data['your_email'], check_mx=True, verify=True)
 	if not is_email_valid:
 		raise forms.ValidationError("This email address could not be verified!")
 	return data
 def email(email):
     if validate_email(email):
         return True
     else:
         return False