Example #1
0
    def createSubscribersFromCSV(self, file_upload):
        """
        Create all subscribers objects from csv file uploaded
        """

        # Reset old log
        self._csv_import_log = ''

        reader = csv.DictReader(file_upload, ['email', 'active', 'format'])

        # get target folder for subscribers object, or create it if not exist
        subscriber_folder = self.getSubscriberFolder()
        if subscriber_folder is None:
            self.invokeFactory('NewsletterBTree', 'subscribers')
            self.subscriber_folder_id = 'subscribers'
            subscriber_folder = getattr(self, 'subscribers')

        # remove headers
        first_row = reader.next()
        if first_row['email'] != 'email':
            return "You must add headers to the csv file : email, active, format ('email' at least)"

        # for each row, create a subscriber object
        default_format = self.default_format
        k = 0
        already_used = []
        not_valid = []
        for row in reader:

            # get the field value, or the default value
            if row['active'] == '1':
                active = True
            elif row['active'] == '0':
                active = False
            else:
                active = False

            if row['format']:
                if row['format'].lower() == 'html':
                    format = 'HTML'
                elif row['format'].lower() == 'text':
                    format = 'Text'
                else:
                    format = default_format
            else:
                format = default_format

            email = row['email']
            email = email.strip()

            # check mail address validity
            if not checkMailAddress(self, email):
                not_valid.append(email)
            else:

                # check if subscriber already exist
                if self.alreadySubscriber(email):
                    already_used.append(email)
                else:
                    newId = self._getRandomIdForSubscriber()
                    subscriber = self.createSubscriberObject(newId)

                    subscriber.edit(format=format, active=active, email=email)
                    k += 1
                    self._subscribersCount += 1

        self._logCSVImportResult(not_valid, already_used)

        msg = ''
        if k:
            msg += '%s subscribers created. ' % str(k)
        if len(already_used):
            msg += '%s users were already subscriber on this newsletter theme. ' % len(already_used)

        if len(not_valid):
            msg += '%s emails were not valid. ' % len(not_valid)

        charset = getSiteEncoding(self)
        return msg.encode(charset)
 def checkMailAddress(self, mail):
     """ Check Email address and return a boolean with the indicated result
     """
     return checkMailAddress(self, mail)
Example #3
0
 def checkMailAddress(self, mail):
     return  checkMailAddress(self, mail)
Example #4
0
    def subscribeFormProcess(self, REQUEST=None):
        """Handles NewsletterTheme_subscribeForm"""

        if REQUEST is None:
            REQUEST = self.REQUEST
        errors = {}
        data = {}
        charset = getUtility(ISiteRoot).getProperty('email_charset', 'utf-8')
        if 'email' in REQUEST.form:
            # Form submitted
            if self.spam_prevention() and (
                REQUEST.get('message') != '' or REQUEST.get('title') != ''
            ):
                log.warn('HONEYPOT FILLED. SUBSCRIBE REJECTED')
                data['email'] = ''
                data['format'] = self.default_format
                return data, errors

            emailaddress = REQUEST.form.get('email', '').strip()
            data['email'] = emailaddress

            if not checkMailAddress(self, emailaddress):
                errors['email'] = self.translate('This is not a valid mail address', domain='plonegazette', context=self.REQUEST)
                return data, errors
            format = REQUEST.form.get('format', self.default_format)
            data['format'] = format
            if self.alreadySubscriber(emailaddress):
                errors['email'] = self.translate('There is already a subscriber with this address',
                                                 domain='plonegazette', context=self.REQUEST)
            if not errors:
                # Creating the new account
                self._subscribersCount += 1
                newId = self._getRandomIdForSubscriber()
                # Continue method as owner of this object for "invokeFactory" security checkings.
                # (creating new objects through invokeFactory is not possible as anonymous because an owner is required)
                oldSecurityManager = getSecurityManager()
                newSecurityManager(REQUEST, ownerOfObject(self))
                newSubscriber = self.createSubscriberObject(newId)
                newSubscriber.edit(format=format, active=0, email=emailaddress)
                setSecurityManager(oldSecurityManager)

                # Make URL for editing this object
                subscriberEditUrl = newSubscriber.absolute_url() + '/Subscriber_editForm'   # :( FIXME
                #actions_tool = getToolByName(self, 'portal_actions')
                #actions = actions_tool.listFilteredActionsFor(object=newSubscriber)
                #subscriberEditUrl = [action['url'] for action in actions['object']
                #                     if action['id'] == 'edit'][0]

                # Make and send the activation mail
                """
                mailBody = ("From: %s\r\n"
                            "To: %s\r\n"
                            "Content-Type: text/plain; charset=%s\r\n"
                            "Subject: %s\r\n\r\n")
                mailBody = mailBody % (self.authorEmail, data['email'],
                                       self.ploneCharset(), self.activationMailSubject)
                mailBody += self.activationMailTemplate % {'url': self.absolute_url() + '?active=%s&format=%s' % (newId, format), 'email': emailaddress}

                """
                mailMsg = email.Message.Message()
                mailMsg["To"] = data['email']
                mailMsg["From"] = self.authorEmail
                mailMsg["Subject"] = str(Header(safe_unicode(self.activationMailSubject), charset))
                mailMsg["Date"] = email.Utils.formatdate(localtime=1)
                mailMsg["Message-ID"] = email.Utils.make_msgid()
                mailMsg["Mime-version"] = "1.0"

                bodyText = self.activationMailTemplate % {'url': self.absolute_url() + '?active=%s&format=%s' % (newId, format), 'email': emailaddress}
                mailMsg["Content-type"] = "text/plain"
                mailMsg.set_payload(safe_unicode(bodyText).encode(charset), charset)
                #mailMsg.preamble="Mime message\n"
                mailMsg.epilogue = "\n"  # To ensure that message ends with newline

                try:
                    self.sendmail(self.authorEmail, (emailaddress,), mailMsg, subject=mailMsg['subject'])
                except Exception, e:
                    # The email could not be sent, probably the specified address doesn't exist
                    errors['email'] = translate('Email could not be sent. Error message is: ${error}', mapping={'error': str(e)}, context=REQUEST)
                    data['email'] = emailaddress
                    data['format'] = self.default_format
                    transaction.abort()
                    return data, errors

                if self.notify:
                    # Notify the NewsletterTheme owner
                    """mailBody = ("From: %s\r\n"
                                "To: %s\r\n"
                                "Content-Type: text/plain; charset=%s\r\n"
                                "Subject: %s : %s\r\n\r\n"
                                "%s\n%s")
                    mailBody = mailBody % (self.authorEmail, self.testEmail,
                                           self.ploneCharset(),
                                           self.title,
                                           translate("Newsletter new subscriber", domain='plonegazette', context=REQUEST),
                                           translate("See the new account at...", domain='plonegazette', context=REQUEST),
                                           subscriberEditUrl)
                    subject = "Subject: %s : %s" % (self.title,
                                           translate("Newsletter new subscriber", domain='plonegazette', context=REQUEST))
                    """
                    subject = "%s : %s" % (self.title,
                                           translate("Newsletter new subscriber", domain='plonegazette', context=REQUEST))
                    mailMsg = email.Message.Message()
                    mailMsg["To"] = self.testEmail
                    mailMsg["From"] = self.authorEmail
                    mailMsg["Subject"] = str(Header(safe_unicode(subject), charset))
                    mailMsg["Date"] = email.Utils.formatdate(localtime=1)
                    mailMsg["Message-ID"] = email.Utils.make_msgid()
                    mailMsg["Mime-version"] = "1.0"

                    bodyText = "%s\n%s" % (translate("See the new account at...", context=REQUEST, domain='plonegazette'),
                                           subscriberEditUrl)
                    mailMsg["Content-type"] = "text/plain"
                    mailMsg.set_payload(safe_unicode(bodyText).encode(charset), charset)
                    #mailMsg.preamble="Mime message\n"
                    mailMsg.epilogue = "\n"  # To ensure that message ends with newline

                    self.sendmail(self.authorEmail, (self.testEmail,), mailMsg, subject=mailMsg['subject'])
                data['success'] = 1
    def createSubscribersFromCSV(self, file_upload):
        """
        Create all subscribers objects from csv file uploaded
        """

        # Reset old log
        self._csv_import_log = ""

        reader = csv.DictReader(file_upload, ["email", "active", "format"])

        # get target folder for subscribers object, or create it if not exist
        subscriber_folder = self.getSubscriberFolder()
        if subscriber_folder is None:
            self.invokeFactory("NewsletterBTree", "subscribers")
            self.subscriber_folder_id = "subscribers"
            subscriber_folder = getattr(self, "subscribers")

        # remove headers
        first_row = reader.next()
        if first_row["email"] != "email":
            return "You must add headers to the csv file : email, active, format ('email' at least)"

        # for each row, create a subscriber object
        default_format = self.default_format
        k = 0
        already_used = []
        not_valid = []
        for row in reader:

            # get the field value, or the default value
            if row["active"] == "1":
                active = True
            elif row["active"] == "0":
                active = False
            else:
                active = False

            if row["format"]:
                if row["format"].lower() == "html":
                    format = "HTML"
                elif row["format"].lower() == "text":
                    format = "Text"
                else:
                    format = default_format
            else:
                format = default_format

            email = row["email"]
            email = email.strip()

            # check mail address validity
            if not checkMailAddress(self, email):
                not_valid.append(email)
            else:

                # check if subscriber already exist
                if self.alreadySubscriber(email):
                    already_used.append(email)
                else:
                    newId = self._getRandomIdForSubscriber()
                    subscriber = self.createSubscriberObject(newId)

                    subscriber.edit(format=format, active=active, email=email)
                    k += 1
                    self._subscribersCount += 1

        self._logCSVImportResult(not_valid, already_used)

        msg = ""
        if k:
            msg += "%s subscribers created. " % str(k)
        if len(already_used):
            msg += "%s users were already subscriber on this newsletter theme. " % len(already_used)

        if len(not_valid):
            msg += "%s emails were not valid. " % len(not_valid)

        charset = getSiteEncoding(self)
        return msg.encode(charset)
 def checkMailAddress(self, mail):
     return checkMailAddress(self, mail)
    def subscribeFormProcess(self, REQUEST=None):
        """Handles NewsletterTheme_subscribeForm"""

        if REQUEST is None:
            REQUEST = self.REQUEST
        errors = {}
        data = {}
        charset = getUtility(ISiteRoot).getProperty("email_charset", "utf-8")
        if "email" in REQUEST.form:
            # Form submitted
            if self.spam_prevention() and (REQUEST.get("message") != "" or REQUEST.get("title") != ""):
                log.warn("HONEYPOT FILLED. SUBSCRIBE REJECTED")
                data["email"] = ""
                data["format"] = self.default_format
                return data, errors

            emailaddress = REQUEST.form.get("email", "").strip()
            data["email"] = emailaddress

            if not checkMailAddress(self, emailaddress):
                errors["email"] = self.translate(
                    "This is not a valid mail address", domain="plonegazette", context=self.REQUEST
                )
                return data, errors
            format = REQUEST.form.get("format", self.default_format)
            data["format"] = format
            if self.alreadySubscriber(emailaddress):
                errors["email"] = self.translate(
                    "There is already a subscriber with this address", domain="plonegazette", context=self.REQUEST
                )
            if not errors:
                # Creating the new account
                self._subscribersCount += 1
                newId = self._getRandomIdForSubscriber()
                # Continue method as owner of this object for "invokeFactory" security checkings.
                # (creating new objects through invokeFactory is not possible as anonymous because an owner is required)
                oldSecurityManager = getSecurityManager()
                newSecurityManager(REQUEST, ownerOfObject(self))
                newSubscriber = self.createSubscriberObject(newId)
                newSubscriber.edit(format=format, active=0, email=emailaddress)
                setSecurityManager(oldSecurityManager)

                # Make URL for editing this object
                subscriberEditUrl = newSubscriber.absolute_url() + "/Subscriber_editForm"  # :( FIXME
                # actions_tool = getToolByName(self, 'portal_actions')
                # actions = actions_tool.listFilteredActionsFor(object=newSubscriber)
                # subscriberEditUrl = [action['url'] for action in actions['object']
                #                     if action['id'] == 'edit'][0]

                # Make and send the activation mail
                """
                mailBody = ("From: %s\r\n"
                            "To: %s\r\n"
                            "Content-Type: text/plain; charset=%s\r\n"
                            "Subject: %s\r\n\r\n")
                mailBody = mailBody % (self.authorEmail, data['email'],
                                       self.ploneCharset(), self.activationMailSubject)
                mailBody += self.activationMailTemplate % {'url': self.absolute_url() + '?active=%s&format=%s' % (newId, format), 'email': emailaddress}

                """
                mailMsg = email.Message.Message()
                mailMsg["To"] = data["email"]
                mailMsg["From"] = self.authorEmail
                mailMsg["Subject"] = str(Header(safe_unicode(self.activationMailSubject), charset))
                mailMsg["Date"] = email.Utils.formatdate(localtime=1)
                mailMsg["Message-ID"] = email.Utils.make_msgid()
                mailMsg["Mime-version"] = "1.0"

                bodyText = self.activationMailTemplate % {
                    "url": self.absolute_url() + "?active=%s&format=%s" % (newId, format),
                    "email": emailaddress,
                }
                mailMsg["Content-type"] = "text/plain"
                mailMsg.set_payload(safe_unicode(bodyText).encode(charset), charset)
                # mailMsg.preamble="Mime message\n"
                mailMsg.epilogue = "\n"  # To ensure that message ends with newline

                try:
                    self.sendmail(self.authorEmail, (emailaddress,), mailMsg, subject=mailMsg["subject"])
                except Exception, e:
                    # The email could not be sent, probably the specified address doesn't exist
                    errors["email"] = translate(
                        "Email could not be sent. Error message is: ${error}",
                        mapping={"error": str(e)},
                        context=REQUEST,
                    )
                    data["email"] = emailaddress
                    data["format"] = self.default_format
                    transaction.abort()
                    return data, errors

                if self.notify:
                    # Notify the NewsletterTheme owner
                    """mailBody = ("From: %s\r\n"
                                "To: %s\r\n"
                                "Content-Type: text/plain; charset=%s\r\n"
                                "Subject: %s : %s\r\n\r\n"
                                "%s\n%s")
                    mailBody = mailBody % (self.authorEmail, self.testEmail,
                                           self.ploneCharset(),
                                           self.title,
                                           translate("Newsletter new subscriber", domain='plonegazette', context=REQUEST),
                                           translate("See the new account at...", domain='plonegazette', context=REQUEST),
                                           subscriberEditUrl)
                    subject = "Subject: %s : %s" % (self.title,
                                           translate("Newsletter new subscriber", domain='plonegazette', context=REQUEST))
                    """
                    subject = "%s : %s" % (
                        self.title,
                        translate("Newsletter new subscriber", domain="plonegazette", context=REQUEST),
                    )
                    mailMsg = email.Message.Message()
                    mailMsg["To"] = self.testEmail
                    mailMsg["From"] = self.authorEmail
                    mailMsg["Subject"] = str(Header(safe_unicode(subject), charset))
                    mailMsg["Date"] = email.Utils.formatdate(localtime=1)
                    mailMsg["Message-ID"] = email.Utils.make_msgid()
                    mailMsg["Mime-version"] = "1.0"

                    bodyText = "%s\n%s" % (
                        translate("See the new account at...", context=REQUEST, domain="plonegazette"),
                        subscriberEditUrl,
                    )
                    mailMsg["Content-type"] = "text/plain"
                    mailMsg.set_payload(safe_unicode(bodyText).encode(charset), charset)
                    # mailMsg.preamble="Mime message\n"
                    mailMsg.epilogue = "\n"  # To ensure that message ends with newline

                    self.sendmail(self.authorEmail, (self.testEmail,), mailMsg, subject=mailMsg["subject"])
                data["success"] = 1