Exemplo n.º 1
0
    def createSubscribersFromCSV(self, file_upload):
        """
        Create all subscribers objects from csv file uploaded
        """

        # Reset old log
        self._csv_import_log = ''

        filename = file_upload.filename
        filedatas = file_upload.read()
        var_directory = self.Control_Panel.getCLIENT_HOME()

        dialect = csv.excel

        # first, create a temp file on file system
        self._createTempFile(var_directory, filename, filedatas)

        # open temp csv file
        reader = csv.DictReader(open('%s/%s' % (var_directory, filename)), ['email', 'active', 'format'], dialect=dialect)

        # 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 _('csv_headers_error',
                     default=u"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

        # remove temp csv file
        os.remove('%s/%s' % (var_directory, filename))

        self._logCSVImportResult(not_valid, already_used)

        msg = _('csv_import_report',
                default=u"""${count_created} subscribers created.
${count_already_there} users were already subscriber on this newsletter theme.
${count_not_valid} emails were not valid.""",
                mapping={'count_created': k,
                         'count_already_there': len(already_used),
                         'count_not_valid': len(not_valid)})
        return msg
Exemplo n.º 2
0
 def checkMailAddress(self, mail):
     return checkMailAddress(self, mail)
Exemplo n.º 3
0
    def subscribeFormProcess(self, REQUEST=None):
        """Handles NewsletterTheme_subscribeForm"""

        if REQUEST is None:
            REQUEST = self.REQUEST
        errors = {}
        data = {}
        charset = self.ploneCharset()
        if REQUEST.form.has_key('email'):
            # Form submitted
            emailaddress = REQUEST.form.get('email', '').strip()
            data['email'] = emailaddress

            if not emailaddress:
                errors['email'] = translate(_('input_required',
                                              default=u'Input is required but no input given'),
                                            context=REQUEST)
                return data, errors

            if not checkMailAddress(self, emailaddress):
                errors['email'] = translate(_('invalid_email_address',
                                              default=u'This is not a valid mail address'),
                                            context=REQUEST)
                return data, errors
            format = REQUEST.form.get('format', self.default_format)
            data['format'] = format
            if self.alreadySubscriber(emailaddress):
                errors['email'] = translate(_('already_subscribed',
                                              default=u'There is already a subscriber with this address'),
                                            context=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), 'utf8'))
                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=self)
                    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), 'utf8'))
                    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_charset(charset)
                    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