def validateEmail(value):
    """Simple email validator"""
    try:
        checkEmailAddress(value)
    except EmailAddressInvalid:
        raise InvalidEmailAddress(value)
    return True
def validate_email(value):
    try:
        if value:
            checkEmailAddress(value)
    except EmailAddressInvalid:
        raise Invalid(_(u'Invalid email address'))
    return True
Beispiel #3
0
    def sendBlogSubscriptionMail(self):
        """
        envoi des informations d'inscription à la newsletter du blog
        """
        nom = self.request.get("nom", "")
        email = self.request.get("email", "")
        fromMail = "*****@*****.**"
        if not email:
            return
        try:
            checkEmailAddress(email)
        except EmailAddressInvalid:
            return
        mailer = Mailer("localhost", fromMail)
        mailer.setSubject("[INSCRIPTION NEWSLETTER BLOG]")
        mailer.setRecipients("*****@*****.**")
        mail = u""":: INSCRIPTION ::

Une demande d'inscription a été envoyée via le blog :

    * Nom : %s
    * Email : %s
""" % (
            unicode(nom, "utf-8"),
            unicode(email, "utf-8"),
        )
        mailer.sendAllMail(mail.encode("utf-8"), plaintext=True)
Beispiel #4
0
    def registeredNotify(self, new_member_id):
        """ Wrapper around registeredNotify """
        membership = getToolByName( self, 'portal_membership' )
        utils = getToolByName(self, 'plone_utils')
        member = membership.getMemberById( new_member_id )

        if member and member.getProperty('email'):
            # add the single email address
            if not utils.validateSingleEmailAddress(member.getProperty('email')):
                raise ValueError, 'The email address did not validate'

        email = member.getProperty( 'email' )
        try:
            checkEmailAddress(email)
        except EmailAddressInvalid:
            raise ValueError, 'The email address did not validate'

        pwrt = getToolByName(self, 'portal_password_reset')
        reset = pwrt.requestReset(new_member_id)

        # Rather than have the template try to use the mailhost, we will
        # render the message ourselves and send it from here (where we
        # don't need to worry about 'UseMailHost' permissions).
        mail_text = self.registered_notify_template( self
                                                   , self.REQUEST
                                                   , member=member
                                                   , reset=reset
                                                   , email=email
                                                   )

        host = self.MailHost
        encoding = getUtility(ISiteRoot).getProperty('email_charset')
        host.send(mail_text.encode(encoding))

        return self.mail_password_response( self, self.REQUEST )
Beispiel #5
0
    def update(self):
        context = self.context

        mailList = api.portal.get_registry_record('nnsh.content.configlet.IEpaper.mailList')
        if not mailList:
            return
        mailBody = self.mailBody()

        mailList = mailList.split()

        for mail in mailList:
            try:
                checkEmailAddress(mail)
                api.portal.send_email(
                    recipient=mail,
                    subject=context.Title(),
                    body=mailBody.as_string()
                )
                time.sleep(1)
            except:
                errLog = api.portal.get_registry_record('nnsh.content.configlet.IEpaper.epaperLog')
                if errLog is None:
                    errLog = ''
                errLog = u'%s: Error, %s, %s\n' % (
                    safe_unicode(time.strftime('%c')),
                    safe_unicode(context.Title()),
                    mail) + errLog
                api.portal.set_registry_record('nnsh.content.configlet.IEpaper.epaperLog', errLog)
                continue
        return
def validateaddress(value):
    try:
        checkEmailAddress(value)
    except EmailAddressInvalid:
        return False
        # raise EmailAddressInvalid(value)
    return True
Beispiel #7
0
def validateEmail(value):
    """Simple email validator"""
    try:
        checkEmailAddress(value)
    except EmailAddressInvalid:
        raise InvalidEmailAddress(value)
    return True
Beispiel #8
0
def validate_email(value):
    try:
        if value:
            checkEmailAddress(value)
    except EmailAddressInvalid:
        raise Invalid(_(u'Invalid email address'))
    return True
Beispiel #9
0
def validateaddress(value):
    if value:
        try:
            checkEmailAddress(value)
        except EmailAddressInvalid:
            raise InvalidEmailAddress(value)
    return True
def validateEmailAddress(value):
    """Validate an email, if provided.
    """
    if not value:
        return True

    checkEmailAddress(value)
Beispiel #11
0
    def update(self):
        """ Store the request form in annotations
        """

        form = self.request.form

        noisetype = self.request.get("noisetype")

        if noisetype == "twitter":

            # Twitter form is only submitted after a succesful tweet. We
            # don't need to worry about anything else here.
            storage.add_noise(self.context, storage.TWITTER_KEY, form)

        elif noisetype == "facebook":

            storage.add_noise(self.context, storage.FACEBOOK_KEY, form)

        elif noisetype == "email":

            # E-mail sending and storage goes here

            try:

                # double check on valid email addresses
                checkEmailAddress(self.request.get("email"))
                checkEmailAddress(self.request.get("email_rcpt"))

                body = self.request.get("email_body").replace("<br>", "\n")
                body += "\n\n{0}\n{1} {2}".format(
                    self.context.email_conclusion,
                    self.request.get("firstname"),
                                            self.request.get("lastname"))

                api.portal.send_email(
                    recipient=self.request.get("email_rcpt"),
                    sender="%s %s<%s>" % (
                        self.request.get("firstname"),
                        self.request.get("lastname"),
                        self.request.get("email")
                    ),
                    subject=self.request.get("email_subject"),
                    body=body,
                )

                storage.add_noise(self.context, storage.EMAIL_KEY, form)
            except:
                pass

        elif noisetype == "hardcopy":

            storage.add_noise(self.context, storage.HARDCOPY_KEY, form)

        if noisetype and self.context.thank_you_page:
            self.request.response.redirect(
                "{0}?email={1}&firstname={2}&lastname={3}".format(
                    self.context.thank_you_page, self.request.get("email"),
                    self.request.get("firstname"),
                    self.request.get("lastname")))
def checkEmail(value):
    try:
        checkEmailAddress(value)
    except EmailAddressInvalid:
#        portal = api.portal.get()
#        api.portal.show_message(message='Wrong Eamil format!', request=portal.REQUEST, type='warning')
        raise Invalid(_(u"Invalid email address."))
    return True
Beispiel #13
0
def checkEmail(value):
    try:
        checkEmailAddress(value)
    except EmailAddressInvalid:
        #        portal = api.portal.get()
        #        api.portal.show_message(message='Wrong Eamil format!', request=portal.REQUEST, type='warning')
        raise Invalid(_(u"Invalid email address."))
    return True
def validate_email(value):
    try:
        email = (value or u'').strip()
        if email:
            checkEmailAddress(email)
    except EmailAddressInvalid:
        raise Invalid(_(u"Invalid email address: {}".format(email)))

    return True
Beispiel #15
0
def checkMailAddress(obj, someAddr):
    """Checks the validity of a mail address"""
    # #5353 use checkEmailAddress from CMFDefault utils instead of
    # validateSingleEmailAddress from plone_utils as the plone email validator
    # is better at detecting invalid addreses
    try:
        checkEmailAddress(someAddr)
    except EmailAddressInvalid:
        return False
    return True
Beispiel #16
0
def checkMailAddress(obj, someAddr):
    """Checks the validity of a mail address"""
    # #5353 use checkEmailAddress from CMFDefault utils instead of
    # validateSingleEmailAddress from plone_utils as the plone email validator 
    # is better at detecting invalid addreses
    try:
        checkEmailAddress(someAddr)
    except EmailAddressInvalid:
        return False
    return True
 def isValidEmail(self, email):
     """ checks for valid email """
     if EMAIL_RE.search(email) == None:
         return 0
     try:
         checkEmailAddress(email)
     except EmailAddressInvalid:
         return 0
     else:
         return 1
 def isValidEmail(self, email):
     """ checks for valid email """
     if EMAIL_RE.search(email) == None:
         return 0
     try:
         checkEmailAddress(email)
     except EmailAddressInvalid:
         return 0
     else:
         return 1
Beispiel #19
0
    def test_checkEmailAddress(self):
        from Products.CMFDefault.exceptions import EmailAddressInvalid
        from Products.CMFDefault.utils import checkEmailAddress

        self.assertEqual(checkEmailAddress('*****@*****.**'), None)
        self.assertEqual(checkEmailAddress('*****@*****.**'), None)
        self.assertEqual(checkEmailAddress('*****@*****.**'), None)
        self.assertEqual(checkEmailAddress('[email protected]'), None)
        self.assertEqual(checkEmailAddress(u'*****@*****.**'), None)
        # CMF Collector issue #322
        self.assertEqual(checkEmailAddress('*****@*****.**'), None)
        # CMF Collector issue #326
        self.assertEqual(checkEmailAddress('*****@*****.**'), None)
        # CMF Collector issue #401
        self.assertEqual(checkEmailAddress("user'*****@*****.**"), None)
        # CMF Collector issue #495
        self.assertEqual(checkEmailAddress("*****@*****.**"), None)
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          'this is not an e-mail address')
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          '[email protected], [email protected]')
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          '*****@*****.**')
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          '*****@*****.**')
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          '*****@*****.**')
        # RFC 2821 local-part: max 64 characters
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          'f'*63+'*****@*****.**')
        # RFC 2821 domain: max 255 characters
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          'foo@'+'b'*242+'ar.example.com')
Beispiel #20
0
    def test_checkEmailAddress(self):
        from Products.CMFDefault.exceptions import EmailAddressInvalid
        from Products.CMFDefault.utils import checkEmailAddress

        self.assertEqual(checkEmailAddress('*****@*****.**'), None)
        self.assertEqual(checkEmailAddress('*****@*****.**'), None)
        self.assertEqual(checkEmailAddress('*****@*****.**'), None)
        self.assertEqual(checkEmailAddress('[email protected]'), None)
        self.assertEqual(checkEmailAddress(u'*****@*****.**'), None)
        # CMF Collector issue #322
        self.assertEqual(checkEmailAddress('*****@*****.**'), None)
        # CMF Collector issue #326
        self.assertEqual(checkEmailAddress('*****@*****.**'), None)
        # CMF Collector issue #401
        self.assertEqual(checkEmailAddress("user'*****@*****.**"), None)
        # CMF Collector issue #495
        self.assertEqual(checkEmailAddress("*****@*****.**"), None)
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          'this is not an e-mail address')
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          '[email protected], [email protected]')
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          '*****@*****.**')
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          '*****@*****.**')
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          '*****@*****.**')
        # RFC 2821 local-part: max 64 characters
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          'f' * 63 + '*****@*****.**')
        # RFC 2821 domain: max 255 characters
        self.assertRaises(EmailAddressInvalid, checkEmailAddress,
                          'foo@' + 'b' * 242 + 'ar.example.com')
    def validateEmail(data):
        if data.email is None:
            return True
        try:
            checkEmailAddress(data.email)
        except EmailAddressInvalid:
#            import pdb; pdb.set_trace()
            portal = api.portal.get()
            api.portal.show_message(message='Wrong Eamil format!', request=portal.REQUEST, type='error')
            raise Invalid(_(u"Invalid email address."))
        return True
Beispiel #22
0
def validateEmailAddress(value):
    """
    Validate the email address. See Products.CMFDefault.utils.checkEmailAddress
    for specifics.
    """
    if len(str(value)) != 0:
        try:
            checkEmailAddress(value)
        except EmailAddressInvalid:
            raise InvalidEmailAddress(value)
    return True
Beispiel #23
0
def check_email(value):
    """
      >>> def t(value):
      ...    try:
      ...        return check_email(value)
      ...    except InvalidEmailAddress:
      ...        return False

    Some common examples.

      >>> t('*****@*****.**')
      True
      >>> t('*****@*****.**')
      True
      >>> t('*****@*****.**')
      True
      >>> t('*****@*****.**')
      True

    Note that we only accept real-world routeable addresses

      >>> t('tmog@localhost')
      False

    Capitals are ok.

      >>> t('*****@*****.**')
      True

    This passed with the old regex.

      >>> t('[email protected].')
      False

    More fails.

      >>> t('tmog@domain@tld')
      False
      >>> t('tmog.domain.tld')
      False
      >>> t('tmog')
      False

    No international chars plz.

      >>> t('René@la-resistance.fr')
      False

    """
    try:
        checkEmailAddress(value)
    except EmailAddressInvalid:
        raise InvalidEmailAddress(value)
    return True
Beispiel #24
0
def validateEmailAddress(value):
    """
    Validate the email address. See Products.CMFDefault.utils.checkEmailAddress
    for specifics.
    """
    if len(str(value)) != 0:
        try:
            checkEmailAddress(value)
        except EmailAddressInvalid:
            raise InvalidEmailAddress(value)
    return True
Beispiel #25
0
    def _getValidEmailAddress(self, member):
        email = member.getProperty('email')

        # assert that we can actually get an email address, otherwise
        # the template will be made with a blank To:, this is bad
        if email is None:
            msg = _(u'No email address is registered for member: '
                    u'${member_id}', mapping={'member_id': member.getId()})
            raise ValueError(msg)

        checkEmailAddress(email)
        return email
Beispiel #26
0
def validateaddress(value):
    try:
        checkEmailAddress(value)
    except EmailAddressInvalid:
        return False
    return True
        
            
            


    
        
Beispiel #27
0
def errorEmail(useremail):
    error = ''
    if useremail == '':
        error = '必须填写邮件地址;'

    else:
        try:
            checkEmailAddress(useremail)
        except EmailAddressInvalid:
            error = '请正确填写邮件地址;'

    error = error.decode('utf', 'replace')
    return error
Beispiel #28
0
def errorEmail(useremail):
    error = ''
    if useremail == '':
        error = '必须填写邮件地址;'

    else:
        try:
            checkEmailAddress(useremail)
        except EmailAddressInvalid:
            error = '请正确填写邮件地址;'

    error = error.decode('utf', 'replace')
    return error
Beispiel #29
0
 def validateEmail(data):
     if data.email is None:
         return True
     try:
         checkEmailAddress(data.email)
     except EmailAddressInvalid:
         #            import pdb; pdb.set_trace()
         portal = api.portal.get()
         api.portal.show_message(message='Wrong Eamil format!',
                                 request=portal.REQUEST,
                                 type='error')
         raise Invalid(_(u"Invalid email address."))
     return True
Beispiel #30
0
    def registeredNotify(self, new_member_id):
        # Wrapper around registeredNotify.
        membership = getToolByName(self, 'portal_membership')
        utils = getToolByName(self, 'plone_utils')
        member = membership.getMemberById(new_member_id)

        if member and member.getProperty('email'):
            # add the single email address
            if not utils.validateSingleEmailAddress(
                    member.getProperty('email')):
                raise ValueError(_(u'The email address did not validate.'))

        email = member.getProperty('email')
        try:
            checkEmailAddress(email)
        except EmailAddressInvalid:
            raise ValueError(_(u'The email address did not validate.'))

        pwrt = getToolByName(self, 'portal_password_reset')
        reset = pwrt.requestReset(new_member_id)

        # Rather than have the template try to use the mailhost, we will
        # render the message ourselves and send it from here (where we
        # don't need to worry about 'UseMailHost' permissions).
        encoding = getUtility(ISiteRoot).getProperty('email_charset', 'utf-8')
        mail_text = self.registered_notify_template(self,
                                                    self.REQUEST,
                                                    member=member,
                                                    reset=reset,
                                                    email=email,
                                                    charset=encoding)

        # The mail headers are not properly encoded we need to extract
        # them and let MailHost manage the encoding.
        if isinstance(mail_text, unicode):
            mail_text = mail_text.encode(encoding)
        message_obj = message_from_string(mail_text.strip())
        subject = message_obj['Subject']
        m_to = message_obj['To']
        m_from = message_obj['From']
        msg_type = message_obj.get('Content-Type', 'text/plain')
        host = getToolByName(self, 'MailHost')
        host.send(mail_text,
                  m_to,
                  m_from,
                  subject=subject,
                  charset=encoding,
                  msg_type=msg_type,
                  immediate=True)

        return self.mail_password_response(self, self.REQUEST)
Beispiel #31
0
    def _getValidEmailAddress(self, member):
        email = member.getProperty('email')

        # assert that we can actually get an email address, otherwise
        # the template will be made with a blank To:, this is bad
        if email is None:
            msg = _(
                u'No email address is registered for member: '
                u'${member_id}',
                mapping={'member_id': member.getId()})
            raise ValueError(msg)

        checkEmailAddress(email)
        return email
    def testPropertiesValidity(self, props, member=None):

        """ Verify that the properties supplied satisfy portal's requirements.

        o If the properties are valid, return None.
        o If not, return a string explaining why.

        This is a customized version of the CMFDefault version: we also
        check if the email property is writable before verifying it.
        """
        if member is None:  # New member.

            username = props.get('username', '')
            if not username:
                return _(u'You must enter a valid name.')

            if not self.isMemberIdAllowed(username):
                return _(u'The login name you selected is already in use or '
                         u'is not valid. Please choose another.')

            email = props.get('email')
            if email is None:
                return _(u'You must enter an email address.')

            try:
                checkEmailAddress(email)
            except EmailAddressInvalid:
                return _(u'You must enter a valid email address.')

        else:  # Existing member.
            if not hasattr(member, 'canWriteProperty') or \
                    member.canWriteProperty('email'):

                email = props.get('email')

                if email is not None:

                    try:
                        checkEmailAddress(email)
                    except EmailAddressInvalid:
                        return _(u'You must enter a valid email address.')

                # Not allowed to clear an existing non-empty email.
                existing = member.getProperty('email')

                if existing and email == '':
                    return _(u'You must enter a valid email address.')

        return None
Beispiel #33
0
    def isValidEmail(self, email):
        plone_version = api.env.plone_version()
        portal_registration = getToolByName(self, 'portal_registration')

        if plone_version < '5.0':
            # Checks for valid email.
            if PLONE5_EMAIL_RE.search(email) == None:
                return 0
            try:
                checkEmailAddress(email)
            except EmailAddressInvalid:
                return 0
            else:
                return 1
        return portal_registration.isValidEmail(email)
    def testPropertiesValidity(self, props, member=None):
        """ Verify that the properties supplied satisfy portal's requirements.

        o If the properties are valid, return None.
        o If not, return a string explaining why.

        This is a customized version of the CMFDefault version: we also
        check if the email property is writable before verifying it.
        """
        if member is None:  # New member.

            username = props.get('username', '')
            if not username:
                return _(u'You must enter a valid name.')

            if not self.isMemberIdAllowed(username):
                return _(u'The login name you selected is already in use or '
                         u'is not valid. Please choose another.')

            email = props.get('email')
            if email is None:
                return _(u'You must enter an email address.')

            try:
                checkEmailAddress(email)
            except EmailAddressInvalid:
                return _(u'You must enter a valid email address.')

        else:  # Existing member.
            if not hasattr(member, 'canWriteProperty') or \
                    member.canWriteProperty('email'):

                email = props.get('email')

                if email is not None:

                    try:
                        checkEmailAddress(email)
                    except EmailAddressInvalid:
                        return _(u'You must enter a valid email address.')

                # Not allowed to clear an existing non-empty email.
                existing = member.getProperty('email')

                if existing and email == '':
                    return _(u'You must enter a valid email address.')

        return None
Beispiel #35
0
    def __call__(self, value, *args, **kwargs):

        Wrongs=[]
        for email in value:
            
            try:
                checkEmailAddress(email)
            except EmailAddressInvalid:

                Wrongs.append(email)
        if len(Wrongs)==1:
            return _(u"The next email address is invalid: %s") % (Wrongs[0])
        elif len(Wrongs)>1:
            spanWrong=", ".join(Wrongs)
            return _(u"The nexts email addresses are invalid: %s ") % (spanWrong)
        else:
            pass
Beispiel #36
0
    def registeredNotify(self, new_member_id):
        # Wrapper around registeredNotify.
        membership = getToolByName(self, 'portal_membership')
        utils = getToolByName(self, 'plone_utils')
        member = membership.getMemberById(new_member_id)

        if member and member.getProperty('email'):
            # add the single email address
            if not utils.validateSingleEmailAddress(
                    member.getProperty('email')):
                raise ValueError(_(u'The email address did not validate.'))

        email = member.getProperty('email')
        try:
            checkEmailAddress(email)
        except EmailAddressInvalid:
            raise ValueError(_(u'The email address did not validate.'))

        pwrt = getToolByName(self, 'portal_password_reset')
        reset = pwrt.requestReset(new_member_id)

        # Rather than have the template try to use the mailhost, we will
        # render the message ourselves and send it from here (where we
        # don't need to worry about 'UseMailHost' permissions).
        encoding = getUtility(ISiteRoot).getProperty('email_charset', 'utf-8')
        mail_text = self.registered_notify_template(
            self, self.REQUEST, member=member, reset=reset, email=email,
            charset=encoding)

        # The mail headers are not properly encoded we need to extract
        # them and let MailHost manage the encoding.
        if isinstance(mail_text, unicode):
            mail_text = mail_text.encode(encoding)
        message_obj = message_from_string(mail_text.strip())
        subject = message_obj['Subject']
        m_to = message_obj['To']
        m_from = message_obj['From']
        msg_type = message_obj.get('Content-Type', 'text/plain')
        host = getToolByName(self, 'MailHost')
        host.send(mail_text, m_to, m_from, subject=subject, charset=encoding,
                  msg_type=msg_type, immediate=True)

        return self.mail_password_response(self, self.REQUEST)
Beispiel #37
0
    def testPropertiesValidity(self, props, member=None):

        """ Verify that the properties supplied satisfy portal's requirements.

        o If the properties are valid, return None.
        o If not, return a string explaining why.
        """
        if member is None: # New member.

            username = props.get('username', '')
            if not username:
                return _(u'You must enter a valid name.')

            if not self.isMemberIdAllowed(username):
                return _(u'The login name you selected is already in use or '
                         u'is not valid. Please choose another.')

            email = props.get('email')
            if email is None:
                return _(u'You must enter an email address.')

            try:
                checkEmailAddress(email)
            except ValidationError:
                return _(u'You must enter a valid email address.')

        else: # Existing member.
            email = props.get('email')

            if email is not None:
                try:
                    checkEmailAddress(email)
                except ValidationError:
                    return _(u'You must enter a valid email address.')

            # Not allowed to clear an existing non-empty email.
            existing = member.getProperty('email')

            if existing and email == '':
                return _(u'You must enter a valid email address.')

        return None
Beispiel #38
0
    def testPropertiesValidity(self, props, member=None):
        """ Verify that the properties supplied satisfy portal's requirements.

        o If the properties are valid, return None.
        o If not, return a string explaining why.
        """
        if member is None:  # New member.

            username = props.get('username', '')
            if not username:
                return _(u'You must enter a valid name.')

            if not self.isMemberIdAllowed(username):
                return _(u'The login name you selected is already in use or '
                         u'is not valid. Please choose another.')

            email = props.get('email')
            if email is None:
                return _(u'You must enter an email address.')

            try:
                checkEmailAddress(email)
            except ValidationError:
                return _(u'You must enter a valid email address.')

        else:  # Existing member.
            email = props.get('email')

            if email is not None:
                try:
                    checkEmailAddress(email)
                except ValidationError:
                    return _(u'You must enter a valid email address.')

            # Not allowed to clear an existing non-empty email.
            existing = member.getProperty('email')

            if existing and email == '':
                return _(u'You must enter a valid email address.')

        return None
Beispiel #39
0
 def _validate(self, value):
     super(EmailLine, self)._validate(value)
     checkEmailAddress(value)
     return True
Beispiel #40
0
    def __call__(self):

        request = self.context.REQUEST
        language = self.context.portal_languages.getPreferredLanguage()
        messages = IStatusMessage(request)

        portal = self.context.portal_url.getPortalObject()
        url = "/%s/get-involved/become-a-national-partner/feedback" % language

        organisation    = request.get('organisation', '')
        address         = request.get('address', '')
        postal_code     = request.get('postal_code', '')
        city            = request.get('city', '')
        country         = request.get('country', '')
        firstname       = request.get('firstname', '')
        lastname        = request.get('lastname', '')
        sector          = request.get('sector', '')
        email           = request.get('email', '')
        telephone       = request.get('telephone', '')
        checkboxlist    = request.get('checkboxlist', [])
        other           = request.get('other_activities_text', '')

        required_fields = {
            "organisation" : organisation,
            "address" : address,
            "postal_code" : postal_code,
            "city" : city,
            "country" : country,
            "firstname" : firstname,
            "lastname" : lastname,
            "sector" : sector,
            "email" : email,
            "telephone" : telephone
            }

        error_messages = self.get_translated_validation_messages()["messages"]
        has_errors = False
        for required_field in required_fields.keys():
            if (required_field == "email"):
                try:
                    checkEmailAddress(required_fields.get(required_field, ""))
                except EmailAddressInvalid:
                    has_errors = True
                    messages.add(
                        error_messages[required_field]["email"],
                        type=u"error")
            elif required_fields[required_field].strip() == "":
                has_errors = True
                messages.add(
                    error_messages[required_field]["required"],
                    type=u"error")
        if has_errors:
            form_path = (
                "%s/@@national-campaign-partner-application-form-2012"
                % "/".join(self.context.getPhysicalPath()))
            request.RESPONSE.setHeader(
                'X-Deliverance-Page-Class', 'general form')
            return self.context.restrictedTraverse(
                form_path)(form = request.form)

        checkboxes = {}
        for c in checkboxlist:
            args = c.split('_', 1)
            if args[1]=='other':
                args[1] = other
            checkboxes[int(args[0])] = args[1]

        cb_list = ['0' for x in range(10)]
        for k in checkboxes.keys():
            cb_list[k] = '1'

        checkboxint=''.join(cb_list)

        if 1:
            now = DateTime().ISO()

            query = insert_hw2012_charter % dict(
                        Organisation    = organisation,
                        Address         = address,
                        Postalcode      = postal_code,
                        City            = city,
                        Country         = country,
                        Firstname       = firstname,
                        Lastname        = lastname,
                        Function        = sector,
                        Email           = email,
                        Telephone       = telephone,
                        Commitment      = checkboxint,
                        Commitment_other = other,
                        Date            = now,
                        Sector          = sector,
                        Language  = language
                        )
            try:
                self.conn.execute(query)
            except Exception, e:
                raise e
Beispiel #41
0
 def constraint(self, value):
     checkEmailAddress(value)
     return super(Email, self).constraint(value)
Beispiel #42
0
 def _validate(self, value):
     super(EmailLine, self)._validate(value)
     checkEmailAddress(value)
     return True
Beispiel #43
0
def validateaddress(value):
    try:
        checkEmailAddress(value)
    except EmailAddressInvalid:
        raise InvalidEmailAddress(value)
    return True
def is_email(value):
    if not isinstance(value, (list, tuple, set)):
        value = [value]
    for v in value:
        checkEmailAddress(v)
    return True
Beispiel #45
0
def validate_email(email):
    try:
        checkEmailAddress(email)
    except EmailAddressInvalid:
        raise EmailAddressInvalid(email)
    return True
Beispiel #46
0
    def __call__(self, form=None, errors={}):
        self.form = form
        self.errors = errors
        request = self.context.REQUEST
        if 'form.submitted' not in request.form:
            return super(
                NationalPartnerForm, self).__call__(self.context, self.request)

        language = self.context.portal_languages.getPreferredLanguage()
        messages = IStatusMessage(request)
        portal = getToolByName(self, 'portal_url').getPortalObject()
        from_address = portal.getProperty('email_from_address', '')

        url = "/%s/get-involved/get-your-certificate/feedback" % language

        organisation = request.get('organisation', '')
        address = request.get('address', '')
        postal_code = request.get('postal_code', '')
        city = request.get('city', '')
        country = request.get('country', '')
        firstname = request.get('firstname', '')
        lastname = request.get('lastname', '')
        sector = request.get('sector', '')
        email = request.get('email', '')
        telephone = request.get('telephone', '')
        checkboxlist = request.get('checkboxlist', [])
        other = request.get('other_activities_text', '')
        privacy = request.get('privacy', False)

        required_fields = {
            "organisation": organisation,
            "address": address,
            "postal_code": postal_code,
            "city": city,
            "country": country,
            "firstname": firstname,
            "lastname": lastname,
            "sector": sector,
            "email": email,
            "telephone": telephone,
            "privacy": privacy,
        }

        error_messages = self.get_translated_validation_messages()["messages"]
        has_errors = False
        errors = {}
        for required_field in required_fields.keys():
            if required_field == "email":
                try:
                    checkEmailAddress(required_fields.get(required_field, ""))
                except EmailAddressInvalid:
                    has_errors = True
                    messages.add(
                        error_messages[required_field]["email"],
                        type=u"error")
                    errors[required_field] = error_messages[required_field]["email"]
            elif required_field == 'privacy':
                if not required_fields.get(required_field, False):
                    has_errors = True
                    messages.add(
                        error_messages[required_field]["required"],
                        type=u"error")
                    errors[required_field] = error_messages[required_field]["required"]
            elif required_fields[required_field].strip() == "":
                has_errors = True
                messages.add(
                    error_messages[required_field]["required"],
                    type=u"error")
                errors[required_field] = error_messages[required_field]["required"]
        if has_errors:
            if 'form.submitted' in request.form:
                del request.form['form.submitted']
            form_path = (
                "%s/@@get-campaign-certificate"
                % "/".join(self.context.getPhysicalPath()))
            return self.context.restrictedTraverse(
                form_path)(form=request.form, errors=errors)

        checkboxes = {}
        for c in checkboxlist:
            args = c.split('_', 1)
            if args[1] == 'other':
                args[1] = other
            checkboxes[int(args[0])] = args[1]

        checkbox_keys = [
            'seminars',
            'competitions',
            'audiovisual',
            'advertising',
            'partnerships',
            'good_neighbour',
            'hazard_spotting',
            'inspections',
            'initiatives',
        ]
        checkbox_options = {}
        for i, key in enumerate(checkbox_keys):
            checkbox_options[key] = checkboxes.get(i, '')

        participant_details = {
            'organisation': organisation,
            'address': address,
            'postal_code': postal_code,
            'city': city,
            'country': country,
            'firstname': firstname,
            'lastname': lastname,
            'sector': sector,
            'email': email,
            'telephone': telephone,
            'other': other,
        }
        participant_details.update(checkbox_options)
        self.store_participant_details(participant_details)

        try:
            logit(" ... calling generatePDF, language: %s" % language)
            logit(" ... calling generatePDF")
            pdf = generatePDF(
                self.context,
                company=organisation,
                language=language,
                firstname=firstname,
                lastname=lastname,
                checkboxes=checkboxes,
                usePDFTK=0
            )

            logit(" ... generatePDF called!")
            send_charter_email(
                self.context,
                pdf=pdf,
                to=email,
                sender="Healthy Workplaces <%s>" % from_address,
                body=translate(email_template, target_language=language,).encode('utf-8'),
                language=language,
            )
        #XXX Too many things could possibly go wrong. So we catch all.
        except Exception, e:
            exception = self.context.plone_utils.exceptionString()
            logit("Exception: " + exception)
            raise
            return request.RESPONSE.redirect(
                url + '?portal_status_message=' + str(e))
Beispiel #47
0
def validateaddress(value):
    try:
        checkEmailAddress(value)
        return True
    except Exception:
        return False
Beispiel #48
0
def validate_email(email):
    try:
        checkEmailAddress(email)
    except EmailAddressInvalid:
        raise EmailAddressInvalid(email)
    return True
Beispiel #49
0
def checkEmail(value):
    try:
        checkEmailAddress(value)
    except EmailAddressInvalid:
        raise Invalid(_(u"Invalid email address."))
    return True