Ejemplo n.º 1
0
    def generate_email(self, mail_id, thread_id, user_id='me'):
        """
        Using the mail_id and thread_id, get all contents for the
        email and generate an Email model.

        Args:
            mail_id: the message id from gmail
            thread_id: the thread id from gmail

        Returns:
            Email: an email model
        """
        try:
            # dict to gather email information
            meta = {
                "Subject": True,
                "From": True,
                "To": True,
                "Date": True,
            }

            message = self._service.users().messages() \
                        .get(userId=user_id,
                                format='full',
                                id=mail_id).execute()

            # lets check the partId of the actual content
            mime = message['payload']['mimeType']

            if mime.startswith('multipart'):
                content = self.retrieve_from_parts(message['payload']['parts'])
            else:
                content = message['payload']['body']['data']

            # don't continue to make email if no content
            if not content:
                return

            body = base64.urlsafe_b64decode(content.encode('ASCII'))

            for header in message['payload']['headers']:
                if meta.get(header['name'], False):
                    meta[header['name'].lower()] = header['value']

                    del meta[header['name']]

            # gmail provides the internal date as epoch ms
            date = datetime.fromtimestamp(
                float(message['internalDate']) / 1000)

            return models.Email(external_id=message['id'],
                                thread_id=message['threadId'],
                                body=unicode(body, 'utf-8'),
                                email_to=meta.get('to', ''),
                                email_from=meta.get('from', ''),
                                subject=meta.get('subject', ''),
                                time=date)

        except errors.HttpError as e:
            print(e)
Ejemplo n.º 2
0
 def get(self):
     # Generate emails for all entries
     entries = models.Entry.all().filter("mailed", False)
     for entry in entries:
         to = []
         for notifier in entry.notifiers:
             to.append(notifier.email)
         if to:
             values = {"entry": entry, "base_url": settings.BASE_URL}
             email = models.Email(
                 sender="Launch Notifier <entry-%s@%s.appspotmail.com>" %
                 (entry.key(), settings.APP_ID),
                 subject="[%s] %s (%s) - %s" %
                 (entry.project.name, entry.name, entry.impact,
                  entry.status.upper()),
                 to=list(set(to)),
                 html=render_to_string("mail/entry.html", values),
                 reference="entry-%s" % entry.key())
             generate_email(email)
             entry.mailed = True
             entry.put()
             for story in entry.unmailed_stories:
                 story.mailed = True
                 story.put()
         else:
             logging.info("No project members for entry %s." % entry.name)
Ejemplo n.º 3
0
    def insertDefaultData(self):
        user = models.User()
        user.first_name = 'Bill'
        user.last_name = 'Lumbergh'
        user.created = datetime.utcnow()
        for label, email in {
                'personal': '*****@*****.**',
                'work': '*****@*****.**'
        }.iteritems():
            email_obj = models.Email()
            email_obj.label = label
            email_obj.email = email
            user.emails.append(email_obj)

        for label, number in {
                'personal': '1-800-555-5555',
                'work': '1-555-555-5555'
        }.iteritems():
            phone_obj = models.PhoneNumber()
            phone_obj.label = label
            phone_obj.number = number
            user.phone_numbers.append(phone_obj)

        session = Schema().session
        session.add(user)
        session.commit()

        return 'Added user: %s %s' % (user.first_name, user.last_name)
Ejemplo n.º 4
0
def submit_form():
    form = ContactForm()
    if form.validate_on_submit():
        email = form.email.data
        subject = form.subject.data
        message = form.message.data
        em = models.Email(email=email, subject=subject, message=message)
        db.session.add(em)
        db.session.commit()
        messenger.forward_message(form.data)
        return redirect('/thankyou.html')
    return render_template('/contact.html', form=form)
Ejemplo n.º 5
0
    def batch_post(self):
        input = self.get_batch_import_content()

        group_mapping = {x.name: x.id for x in models.Group.get_all().all()}
        email_mapping = {}

        row_data = []
        values = {'org_id': g.org_id}
        param_ct = 1

        for row in input:
            if row['group'] not in group_mapping:
                group = models.Group()
                group.name = row['group']
                group.org_id = g.token_data.get('orgId')
                db.session.add(group)
                db.session.flush()
                group_mapping[group.name] = group.id

            if row['email'] not in email_mapping:
                email = models.Email.get_all().filter_by(
                    email=row['email']).first()
                if email is None:
                    email = models.Email()
                    email.org_id = g.token_data.get('orgId')
                    email.email = row['email']
                    db.session.add(email)
                    db.session.flush()

                email_mapping[email.email] = email.id

            email_parm = 'value{}'.format(param_ct)
            param_ct = param_ct + 1
            group_parm = 'value{}'.format(param_ct)
            param_ct = param_ct + 1
            values[email_parm] = email_mapping[row['email']]
            values[group_parm] = group_mapping[row['group']]
            row_data.append('select :{} as e, :{} as g\n'.format(
                email_parm, group_parm))

        s = ' union '.join(row_data)
        s = '''with insert_data as ({})
insert into group_email (email_id, group_id, org_id)
select e, g, :org_id from insert_data
  where not exists(select 1 from group_email as ge
    where ge.email_id = insert_data.e and ge.group_id = insert_data.g and ge.org_id = :org_id)'''.format(
            s)
        r = db.session.connection().execute(text(s).bindparams(**values))
        return {'recordsInserted': r.rowcount}
Ejemplo n.º 6
0
    def batch_delete(self):
        input = self.get_batch_import_content()

        group_mapping = {x.name: x.id for x in models.Group.get_all().all()}
        email_mapping = {}
        statements = []

        for row in input:
            if row['email'] not in email_mapping:
                email = models.Email.get_all().filter_by(
                    email=row['email']).first()
                if email is None:
                    email = models.Email()
                    email.org_id = g.token_data.get('orgId')
                    email.email = row['email']
                    db.session.add(email)
                    db.session.flush()

                email_mapping[email.email] = email.id

            if row['group'] not in group_mapping:
                pass
                #continue

            values = {
                'org': g.org_id,
                'email': email_mapping[row['email']],
                'group': group_mapping[row['group']]
            }

            statements.append(
                text(
                    'delete from group_email where org_id=:org and email_id=:email and group_id=:group'
                ).bindparams(**values))

        affected = 0
        for s in statements:
            affected += db.session.connection().execute(s).rowcount

        return {'recordsDeleted': affected}
Ejemplo n.º 7
0
  def add_to_group(self, group_name, email_address):
    group = models.Group.get_all().filter_by(name=group_name).first()
    if group is None:
      group = models.Group()
      group.name = group_name
      group.org_id = g.token_data.get('orgId')
      db.session.add(group)

    email = models.Email.get_all().filter_by(email=email_address).first()
    if email is None:
      email = models.Email()
      email.org_id = g.token_data.get('orgId')
      email.email = email_address
      db.session.add(email)

    rec = models.GroupEmail.get_all().filter_by(email_id=email.id, group_id=group.id).first()
    if rec is None:
      rec = self.create_record(models.GroupEmail)
      rec.email_id = email.id
      rec.group_id = group.id
      db.session.flush()

    return rec
Ejemplo n.º 8
0
    def post(self, key):
        self.check_user()
        entry = models.Entry.get(key)
        status = decode(self.request.get("status"))
        text = decode(self.request.get("text"))

        # For email notifications
        values = {
            "entry": entry,
            "base_url": settings.BASE_URL,
            "text": text,
            "person": self.person
        }
        cc = []
        for notifier in entry.notifiers:
            cc.append(notifier.email)
        cc_list = list(set(cc))
        sender = ("%s %s via wandoulabs.com <entry-%s@%s.appspotmail.com>" %
                  (self.person.given_name, self.person.family_name,
                   entry.key(), settings.APP_ID))

        if entry.status != status:
            entry.status = status
            if entry.status == "ready":
                new_story(self,
                          "declared <em>%s</em> is ready to launch" %
                          entry.name,
                          entry=entry)
                for relier in entry.reliers:
                    # Reliers' launch statuses are in sync with dependent.
                    relier.status = entry.status
                    new_story(self,
                              "declared <em>%s</em> is ready to launch" %
                              entry.name,
                              entry=relier)
                    relier.put()

                # Send launch notifications
                email = models.Email(
                    sender=sender,
                    subject=unicode(u"[上线准备就绪][%s] %s" %
                                    (entry.project.name, entry.name)),
                    to=[db.Email("*****@*****.**")],
                    cc=cc_list,
                    html=render_to_string("mail/ready_notification.html",
                                          values))
                services.generate_email(email)

            elif entry.status == "completed":
                new_story(self,
                          "completed <em>%s</em>" % entry.name,
                          entry=entry)
                # Send completed notifications
                email = models.Email(
                    sender=sender,
                    subject=unicode(u"[开发完成][%s] %s" %
                                    (entry.project.name, entry.name)),
                    to=[db.Email("*****@*****.**")],
                    cc=cc_list,
                    html=render_to_string("mail/complete_notification.html",
                                          values))
                services.generate_email(email)

            elif entry.status == "launched":
                # Reliers' launch statuses are in sync with dependent.
                entry.launched_at = datetime.datetime.now()
                new_story(self,
                          "launched <em>%s</em>" % entry.name,
                          entry=entry)
                for relier in entry.reliers:
                    relier.status = entry.status
                    relier.launched_at = entry.launched_at
                    new_story(self,
                              "launched <em>%s</em>" % entry.name,
                              entry=relier)
                    relier.put()
                # Send announcement notifications
                email = models.Email(
                    sender=sender,
                    subject=unicode(u"[发布成功][%s] %s" %
                                    (entry.project.name, entry.name)),
                    to=[db.Email("*****@*****.**")],
                    cc=cc_list,
                    html=render_to_string("mail/launch_notification.html",
                                          values))
                services.generate_email(email)
            else:
                new_story(self,
                          "changed status to <em>%s</em>" % status,
                          entry=entry)
            entry.put()
        if text:
            new_story(self, text, entry=entry, type="comment")
        # TODO: Make texts more funny and useful
        memcache.flush_all()
        self.redirect("/entries/" + key)