示例#1
0
def main():

  parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description=textwrap.dedent('''\
      Command line to send email template via gMail.

      Email templates are JSON that assembles into both HTMl and TXT parts of an email.
      For email sample see: https://github.com/google/starthinker/blob/master/starthinker/task/newsletter/sample.json
 
      Example:
        - Generate an HTML page from a template, then view via browser.
          python helper.py --template sample.json > ~/Downloads/email.html

        - Send an email template via gMail.
          python helper.py --template sample.json --email_to [email protected] --email_from [email protected] -u $STARTHINKER_USER
  '''))

  # get parameters
  parser.add_argument('--template', help='template to use for email', default=None, required=True)
  parser.add_argument('--email_to', help='email to', default=None)
  parser.add_argument('--email_from', help='email from', default=None)

  # initialize project
  project.from_commandline(parser=parser, arguments=('-u', '-c', '-v'))

  # load template
  with open(project.args.template, 'r') as json_file:
    email = EmailTemplate(json.load(json_file))

  # send or print
  if project.args.email_to and project.args.email_from:
    print('EMAILING: ', project.args.email_to)
    send_email('user', project.args.email_to, project.args.email_from, None, email.get_subject(), email.get_text(), email.get_html())
  else:
    # write to STDOUT
    print(email.get_html())
    print('<pre style="width:600px;margin:0px auto;">%s</pre>' % email.get_text())
    def handle(self, *args, **kwargs):

        user = None
        accounts = Account.objects.all()

        # find user to send from
        for account in accounts:
            if account.email == kwargs['email_from']:
                user = account.get_credentials_path()

        if user:
            print("SEND USER FOUND")

            # initialize project
            project.initialize(_user=user)

            # load template
            with open(kwargs['template'], 'r') as json_file:
                email = EmailTemplate(json.load(json_file))

            # loop through accounts
            for account in accounts:
                # if account is given only do that one
                if kwargs['email_to'] is None or account.email == kwargs[
                        'email_to']:
                    if account.email in kwargs['ignore']:
                        print('IGNORING: ', account.email)
                    else:
                        print('EMAILING: ', account.email)

                        if kwargs['test']:
                            # write to STDOUT
                            print(email.get_html())
                        else:
                            # send message via email
                            send_email('user', account.email,
                                       kwargs['email_from'], None,
                                       email.get_subject(), email.get_text(),
                                       email.get_html())
                            sleep(1)
示例#3
0
def compose_email_solution_centric(owner):
    if project.verbose: print 'COMPOSING: ', owner['Account Email']

    # start an email template
    email = EmailTemplate()
    email.segment_next()
    email.greeting(owner['Account Owner'])
    email.paragraph(project.task['email']['introduction'])

    # loop through solutions
    rows = []
    for solution in owner['Solutions']:
        email.segment_next()
        email.header('Your %d Biggest %s Impact Opportunities This Week' %
                     (project.task['offers'], solution['Solution']['name']))

        # create offer matrix for each solution
        email.table(
            OFFER_SCHEMA,
            [
                (
                    offer['Variant'],
                    '%d%%' % int(offer['Score'] * 100),
                    compose_link(
                        solution['Solution']['link'],
                        {
                            'solution':
                            solution['Solution']['name'],
                            'requester':
                            owner['Account Email'],
                            'name':
                            offer['Variant'],
                            'dbm':
                            '%s:%s' %
                            (offer['Account_ID'], offer['Variant_ID'])
                            if solution['Solution']['key'] == 'DBM Partner ID'
                            else '',  # comma seperated list
                            'dcm':
                            '%s:%s' %
                            (offer['Account_ID'], offer['Variant_ID'])
                            if solution['Solution']['key'] == 'DCM Network ID'
                            else '',  # comma seperated list
                            'ds':
                            '%s:%s' %
                            (offer['Account_ID'], offer['Variant_ID'])
                            if solution['Solution']['key'] == 'DS Account ID'
                            else '',  # comma seperated list
                            'sa':
                            '%s:%s' %
                            (offer['Account_ID'], offer['Variant_ID']) if
                            solution['Solution']['key'] == 'Studio Account ID'
                            else '',  # comma seperated list
                        })) for offer in solution['Offers']
            ])

        email.paragraph(
            "Click the request link to schedule a solution for that client.  This does not deploy a solution to the client, it only contacts a specialist indicating you'd like to evaluate this solution for this client."
        )

        email.header('About ' + solution['Solution']['name'])
        email.image(solution['Solution']['image'],
                    solution['Solution']['sample'])
        email.paragraph(solution['Solution']['description'])

        email.paragraph('Product Gap', bold=True)
        email.paragraph(solution['Solution']['gap'])

        # solution pitch
        email.paragraph('Benefits', bold=True)
        email.list(solution['Solution']['pitches'])

        # solution impact
        email.table(IMPACT_SCHEMA,
                    [(i[0], '%d%%' % i[1])
                     for i in solution['Solution']['impacts'].items()])

        email.button('Learn More', project.task['link'], big=True)

    #print email.get_html()

    send_email('user', owner['Account Email'], project.task['email']['from'],
               project.task['email']['cc'], project.task['email']['subject'],
               email.get_text(), email.get_html())
示例#4
0
def floodlight_email(day, alerts):

    for email, table in alerts.items():

        # build email template
        t = EmailTemplate()

        # when floodlight alerts exist
        if table:
            subject = '%d Floodlight Alerts For %s' % (len(table), day)
            t.header(subject)
            t.paragraph(
                'For the following floodlights, there are suspiciously low impressions. Please check their configurations.'
            )
            t.table([
                {
                    "name": "Date",
                    "type": "STRING"
                },
                {
                    "name": "Floodlight",
                    "type": "STRING"
                },
                {
                    "name": "Activity Id",
                    "type": "STRING"
                },
                {
                    "name": "Activity",
                    "type": "STRING"
                },
                {
                    "name": "Impressions",
                    "type": "INTEGER"
                },
            ], table)

        # when everything is OK
        else:
            subject = 'All Floodlights Normal For %s' % day
            t.header(subject)
            t.paragraph(
                'Impressions all look within statistically expected range.')

        # either way link to the configuration sheet
        t.button('Floodlight Monitoring Sheet',
                 project.task['sheet']['url'],
                 big=True)

        if project.verbose:
            print "FLOODLIGHT MONITOR EMAIL ALERTS", email, len(table)

        # send email template
        send_email(project.task['auth'], email, None, None, subject,
                   t.get_text(), t.get_html())
示例#5
0
  def handle(self, *args, **kwargs):
    day = date.today() - timedelta(days=kwargs['days'])

    email = {
        'subject':
            'Announcing Six New Open Source Modules For Ecosystems',
        'style': {
            'background': '#f2f2f2',
            'foreground': '#ffffff',
            'text': '#414347',
            'link': '#4285f4',
            'font': 'Roboto, Helvetica, Arial sans-serif;',
            'align': 'left'
        },
        'logo':
            'https://storage.googleapis.com/starthinker-ui/gTech_StarThinker.png',
        'body': {
            'sections': [{
                'header':
                    'Six New Solutions For Partners To Build New Services',
                'paragraph':
                    'In Q1, StarThinker released 6 new building blocks '
                    'available as Python, Airflow, Colab, and no-coding UI.  '
                    'These building blocks are now open sourve and availbale '
                    'for deployment by Partners.  Below is a description of '
                    'each solution and possible service or efficiency gain by '
                    'partners.',
                'grid': []
            }]
        },
        'footer': [{
            'text': 'Internal UI',
            'link': 'http://go/starthinker'
        }, {
            'text': 'Esteemed Solution Gallery',
            'link': 'http://go/esteemed/#/search/StarThinker'
        }, {
            'text': 'GitHub Solution Gallery',
            'link': 'https://google.github.io/starthinker/'
        }, {
            'text': 'Google3 Repository',
            'link': 'http://go/starthinker-google3'
        }, {
            'text': 'GOB Repository ( Official )',
            'link': 'http://go/starthinker-code'
        }, {
            'text': 'GitHub Repository',
            'link': 'https://github.com/google/starthinker'
        }],
        'copyright':
            'Copyright 2020 Google LLC'
    }

    odd = True
    for s in Script.get_scripts():
      if s.get_released() < day:
        continue
      print('SCRIPT: ', s.get_tag())

      if not s.get_image():
        continue

      row = [{
          'image': {
              'src': s.get_image(),
              'link': s.get_link_client()
          }
      }, {
          'header': '[%s](%s)' % (s.get_name(), s.get_link_client()),
          'paragraph': s.get_description()
      }]
      email['body']['sections'][0]['grid'].append(row)

      if odd:
        row.reverse()
      odd = not odd

    email = EmailTemplate(email)

    # send or print
    #if project.args.email_to and project.args.email_from:
    #  print('EMAILING: ', project.args.email_to)
    #  send_email('user', project.args.email_to, project.args.email_from, None, email.get_subject(), email.get_text(), email.get_html())
    #else:
    if 1:
      # write to STDOUT
      print(email.get_html())
      print('<pre style="width:600px;margin:0px auto;">%s</pre>' %
            email.get_text())
示例#6
0
    def handle(self, *args, **kwargs):
        day = date.today() - timedelta(days=kwargs['days'])

        email = {
            "subject":
            "Announcing Six New Open Source Modules For Ecosystems",
            "style": {
                "background": "#f2f2f2",
                "foreground": "#ffffff",
                "text": "#414347",
                "link": "#4285f4",
                "font": "Roboto, Helvetica, Arial sans-serif;",
                "align": "left"
            },
            "logo":
            "https://storage.googleapis.com/starthinker-ui/gTech_StarThinker.png",
            "body": {
                "sections": [{
                    "header":
                    "Six New Solutions For Partners To Build New Services",
                    "paragraph":
                    "In Q1, StarThinker released 6 new building blocks available as Python, Airflow, Colab, and no-coding UI.  These building blocks are now open sourve and availbale for deployment by Partners.  Below is a description of each solution and possible service or efficiency gain by partners.",
                    "grid": []
                }]
            },
            "footer": [{
                "text": "Internal UI",
                "link": "http://go/starthinker"
            }, {
                "text": "Esteemed Solution Gallery",
                "link": "http://go/esteemed/#/search/StarThinker"
            }, {
                "text": "GitHub Solution Gallery",
                "link": "https://google.github.io/starthinker/"
            }, {
                "text": "Google3 Repository",
                "link": "http://go/starthinker-google3"
            }, {
                "text": "GOB Repository ( Official )",
                "link": "http://go/starthinker-code"
            }, {
                "text": "GitHub Repository",
                "link": "https://github.com/google/starthinker"
            }],
            "copyright":
            "Copyright 2020 Google LLC"
        }

        odd = True
        for s in Script.get_scripts():
            if s.get_released() < day: continue
            print('SCRIPT: ', s.get_tag())

            if not s.get_image(): continue

            row = [{
                "image": {
                    "src": s.get_image(),
                    "link": s.get_link_client()
                }
            }, {
                "header": "[%s](%s)" % (s.get_name(), s.get_link_client()),
                "paragraph": s.get_description()
            }]
            email['body']['sections'][0]['grid'].append(row)

            if odd: row.reverse()
            odd = not odd

        email = EmailTemplate(email)

        # send or print
        #if project.args.email_to and project.args.email_from:
        #  print('EMAILING: ', project.args.email_to)
        #  send_email('user', project.args.email_to, project.args.email_from, None, email.get_subject(), email.get_text(), email.get_html())
        #else:
        if 1:
            # write to STDOUT
            print(email.get_html())
            print('<pre style="width:600px;margin:0px auto;">%s</pre>' %
                  email.get_text())
示例#7
0
import json
import argparse

from starthinker.util.project import project
from starthinker.util.email import send_email
from starthinker.util.email.template import EmailTemplate

if __name__ == "__main__":

  # get parameters
  parser = argparse.ArgumentParser()
  parser.add_argument('--template', help='template to use for email', default=None, required=True)
  parser.add_argument('--email_to', help='email to', default=None)
  parser.add_argument('--email_from', help='email from', default=None)

  # initialize project
  project.from_commandline(parser=parser)

  # load template
  with open(project.args.template, 'r') as json_file:
    email = EmailTemplate(json.load(json_file))

  # send or print
  if project.args.email_to and project.args.email_from:
    print 'EMAILING: ', project.args.email_to
    send_email('user', project.args.email_to, project.args.email_from, None, email.get_subject(), email.get_text(), email.get_html())
  else:
    # write to STDOUT
    print email.get_html()
    print '<pre style="width:600px;margin:0px auto;">%s</pre>' % email.get_text()
示例#8
0
    def handle(self, *args, **kwargs):

        # loop through accounts
        for account in Account.objects.all():
            # if account is given only do that one
            if kwargs['email'] is None or account.email == kwargs['email']:
                print('CHECKING: ', account.email)

                status = False

                # start an email template
                email = EmailTemplate()
                email.segment_next()
                email.greeting(account.name)
                email.paragraph(EMAIL_PARAGRAPH)

                # loop through recipes
                rows = []
                for recipe in account.recipe_set.all():
                    log = recipe.get_log()
                    rows.append([
                        recipe.name,
                        log.get('status'),
                        log.get('ago'),
                        'http://starthinker.corp.google.com/recipe/edit/%d/' %
                        recipe.pk
                    ])

                if rows:
                    email.segment_next()
                    email.header('Recipe Status')
                    email.table(RECIPE_SCHEMA, rows)
                    status = True

                # loop through storage
                #rows = []
                #for recipe in storage_list(account):
                #  recipe.log = logs.get(recipe.uid(), {})
                #  rows.append([recipe.name, recipe.log.get('status'), recipe.log.get('time_ago'), recipe.link_storage])

                if rows:
                    email.segment_next()
                    email.header('Storage Status')
                    email.table(RECIPE_SCHEMA, rows)
                    status = True

                    #        # if at least one solution or recipe is running....
                    #        if status:
                    #
                    #          # show one random recipe
                    #          email.segment_next()
                    #          email.header('Featured Recipes')
                    #          email.paragraph('Each week we feature three recipes that could help your client or agency project.  This weeks featured recipe is...')
                    #
                    #          # script: card ( fetch random )
                    #          for s in sample(list(Script.get_scripts()), 3):
                    #            email.header(s.get_name())
                    #            email.paragraph(s.get_description())
                    #
                    #            # solution pitch
                    #            email.paragraph('Benefits', bold=True)
                    #            email.list(s.get_pitches())
                    #
                    #            # solution impact
                    #            email.table(IMPACT_SCHEMA, [(i[0], '%d%%' % i[1]) for i in s.get_impacts().items()])
                    #
                    #            email.table(DETAILS_SCHEMA, [
                    #              ('Requires', ', '.join([r[0] for r in s.get_requirements().items() if r[1]])),
                    #              ('Categories', ', '.join(s.get_categories())),
                    #              ('Authors', mailto(s.get_authors()))
                    #            ])
                    #
                    #            email.button('Launch %s' % s.get_name(), '%s/client/edit/' % settings.CONST_URL, big=True)
                    #
                    #            if s.get_open_source():
                    #              email.button('Avaliable As Open Source', s.get_open_source(), big=True)
                    #
                    #          # loop through links
                    #          email.segment_next()
                    #          email.header('Helpful Links')
                    #          email.paragraph('Reduce solution delivery to minutes and create custom solutions that exceed clients expectations with these helpful guides and tips.')
                    for h in HELP_LINKS:
                        email.section(h['name'], h['description'], None,
                                      h['button']['link'], h['button']['text'])

                    if kwargs['test']:
                        # write to STDOUT
                        print(email.get_html())
                    else:
                        print('EMAILING: ', account.email)
                        # send message via email
                        project.initialize()
                        send_email('user', account.email, EMAIL_FROM, EMAIL_CC,
                                   EMAIL_SUBJECT, email.get_text(),
                                   email.get_html())
                        sleep(3)
示例#9
0
def floodlight_email(day, alerts):

    for email, table in alerts.items():

        # build email template
        t = EmailTemplate()
        t.align('center')
        t.section(True)

        # when floodlight alerts exist
        issues = sum(1 for row in table if row[5] != 'NORMAL')

        if issues > 0: subject = '%d Floodlight Alerts For %s' % (issues, day)
        else: subject = 'All Floodlights Normal For %s' % day

        t.header(subject)
        t.paragraph(
            'The following floodlights are being monitored.  A status of LOW or HIGH inidcates impressions have changed significantly for the day.  A status of NORMAL means impressions are close to the average for the past 7 days.'
        )
        t.table([
            {
                "name": "Date",
                "type": "STRING"
            },
            {
                "name": "Floodlight",
                "type": "STRING"
            },
            {
                "name": "Activity Id",
                "type": "STRING"
            },
            {
                "name": "Activity",
                "type": "STRING"
            },
            {
                "name": "Impressions",
                "type": "INTEGER"
            },
            {
                "name": "Status",
                "type": "STRING"
            },
        ], table)

        t.paragraph(
            'Your monitored floodlights and recipients are listed in the sheet below.'
        )

        # either way link to the configuration sheet
        t.button('Floodlight Monitoring Sheet',
                 sheets_url(project.task['auth'],
                            project.task['sheet']['sheet']),
                 big=True)
        t.section(False)

        if project.verbose:
            print("FLOODLIGHT MONITOR EMAIL ALERTS", email, len(table))

        # send email template
        send_email(project.task['auth'], email, None, None, subject,
                   t.get_text(), t.get_html())
示例#10
0
def floodlight_email(
        day: str, alerts: dict[str, list[str, str, str, str, int,
                                         str]]) -> None:
    """ Send an email to each alert group with status of all activities.

  The email template will contain all activities for each email address specified in the input sheet.

  Args:
    day - the latest day that was present in all combined reports, used for title of email.
    alerts - Each email in the sheet with a list of activities and statuses.

  Returns:
    Nothing.
  """

    for email, table in alerts.items():

        # build email template
        t = EmailTemplate()
        t.align('center')
        t.section(True)

        # when floodlight alerts exist
        issues = sum(1 for row in table if row[5] != 'NORMAL')

        if issues > 0:
            subject = '%d Floodlight Alerts For %s' % (issues, day)
        else:
            subject = 'All Floodlights Normal For %s' % day

        t.header(subject)
        t.paragraph(
            'The following floodlights are being monitored.  A status of LOW or HIGH inidcates impressions have changed significantly for the day.  A status of NORMAL means impressions are close to the average for the past 7 days.'
        )
        t.table([
            {
                'name': 'Date',
                'type': 'STRING'
            },
            {
                'name': 'Floodlight',
                'type': 'STRING'
            },
            {
                'name': 'Activity Id',
                'type': 'STRING'
            },
            {
                'name': 'Activity',
                'type': 'STRING'
            },
            {
                'name': 'Impressions',
                'type': 'INTEGER'
            },
            {
                'name': 'Status',
                'type': 'STRING'
            },
        ], table)

        t.paragraph(
            'Your monitored floodlights and recipients are listed in the sheet below.'
        )

        # either way link to the configuration sheet
        t.button('Floodlight Monitoring Sheet',
                 sheets_url(project.task['auth'],
                            project.task['sheet']['sheet']),
                 big=True)
        t.section(False)

        if project.verbose:
            print('FLOODLIGHT MONITOR EMAIL ALERTS', email, len(table))

        # send email template
        send_email(project.task['auth'], email, None, None, subject,
                   t.get_text(), t.get_html())
示例#11
0
if __name__ == "__main__":

    # get parameters
    parser = argparse.ArgumentParser()
    parser.add_argument('--template',
                        help='template to use for email',
                        default=None,
                        required=True)
    parser.add_argument('--email_to', help='email to', default=None)
    parser.add_argument('--email_from', help='email from', default=None)

    # initialize project
    project.from_commandline(parser=parser)

    # load template
    with open(project.args.template, 'r') as json_file:
        email = EmailTemplate(json.load(json_file))

    # send or print
    if project.args.email_to and project.args.email_from:
        print('EMAILING: ', project.args.email_to)
        send_email('user', project.args.email_to,
                   project.args.email_from, None, email.get_subject(),
                   email.get_text(), email.get_html())
    else:
        # write to STDOUT
        print(email.get_html())
        print('<pre style="width:600px;margin:0px auto;">%s</pre>' %
              email.get_text())