コード例 #1
0
ファイル: main.py プロジェクト: agamaloni/anyway
 def index(self):
     if request.method=='GET':
         user_emails = db_session.query(User).filter(User.new_features_subscription == True)
         email_list = []
         for user in user_emails:
             email_list.append(user.email)
             email_list.append(';')
         context = {'user_emails': email_list}
         return self.render('sendemail.html', **context)
     else:
         jsondata = request.get_json(force=True)
         users_send_email_to = db_session.query(User).filter(User.new_features_subscription == True)
         message = Mail()
         message.set_subject(jsondata['subject'].encode("utf8"))
         message.set_text(jsondata['message'].encode("utf8"))
         message.set_from('ANYWAY Team <*****@*****.**>')
         for user in users_send_email_to:
             message.add_bcc(user.email)
         try:
             status, msg = sg.send(message)
         except SendGridClientError:
             return "Error occurred while trying to send the emails"
         except SendGridServerError:
             return "Error occurred while trying to send the emails"
         return "Email/s Sent"
コード例 #2
0
 def index(self):
     if request.method == 'GET':
         user_emails = db.session.query(User).filter(
             User.new_features_subscription == True)
         email_list = []
         for user in user_emails:
             email_list.append(user.email)
             email_list.append(';')
         context = {'user_emails': email_list}
         return self.render('sendemail.html', **context)
     else:
         jsondata = request.get_json(force=True)
         users_send_email_to = db.session.query(User).filter(
             User.new_features_subscription == True)
         message = Mail()
         message.set_subject(jsondata['subject'].encode("utf8"))
         message.set_text(jsondata['message'].encode("utf8"))
         message.set_from('ANYWAY Team <*****@*****.**>')
         for user in users_send_email_to:
             message.add_bcc(user.email)
         try:
             sg.send(message)
         except SendGridClientError:
             return "Error occurred while trying to send the emails"
         except SendGridServerError:
             return "Error occurred while trying to send the emails"
         return "Email/s Sent"
コード例 #3
0
ファイル: email_stuff.py プロジェクト: adamreis/nyc-jazz
def test_emails():
    test_emails = ['*****@*****.**']

    all_shows = shows_this_week()
    text = all_shows_to_markdown(all_shows)
    html = markdown(text)

    today, next_week = week_interval()
    tomorrow = today + relativedelta(days=+1)
    date_format = "%m/%d"

    responses = []

    # make a secure connection to SendGrid
    sg = SendGridClient(SENDGRID_USER, SENDGRID_PASSWORD, secure=True)

    for email in test_emails:
        # make a message object
        message = Mail()
        message.set_subject('NYC Jazz Digest: {} to {}'.format(tomorrow.strftime(date_format), next_week.strftime(date_format)))
        message.set_html(html)
        message.set_text(text)
        message.set_from('NYC Jazz Digest <*****@*****.**>')

        # add a recipient
        message.add_to(email)

        # use the Web API to send your message
        responses.append(str(sg.send(message)))

    return '\n'.join(responses)
コード例 #4
0
ファイル: email_stuff.py プロジェクト: adamreis/nyc-jazz
def send_digest():
    sg = SendGridClient(SENDGRID_USER, SENDGRID_PASSWORD, secure=True)
    responses = []

    today, next_week = week_interval()
    tomorrow = today + relativedelta(days=+1)
    date_format = "%m/%d"
    subject = 'NYC Jazz Digest: {} to {}'.format(tomorrow.strftime(date_format), next_week.strftime(date_format))
    from_addr = 'NYC Jazz Digest <*****@*****.**>'

    all_shows = shows_this_week()
    text = all_shows_to_markdown(all_shows)
    
    for user in User.query(User.opt_out == False).fetch():
        unsubcribe_link = ROOT_URL + '/unsubscribe/' + user.uuid
        unsubscribe_phrase = "\n\nClick [here]({}) to unsubscribe.".format(unsubcribe_link)
        text += unsubscribe_phrase
        html = markdown(text)

        message = Mail()
        message.set_subject(subject)
        message.set_html(html)
        message.set_text(text)
        message.set_from(from_addr)

        # add a recipient
        message.add_to(user.email)

        # use the Web API to send your message
        responses.append(str(sg.send(message)))

    return '\n'.join(responses)
コード例 #5
0
ファイル: __init__.py プロジェクト: miphreal/sendgrid-python
 def test_send(self):
   m = Mail()
   m.add_to('John, Doe <*****@*****.**>')
   m.set_subject('test')
   m.set_html('WIN')
   m.set_text('WIN')
   m.set_from('*****@*****.**')
   m.add_substitution('subKey', 'subValue')
   m.add_section('testSection', 'sectionValue')
   m.add_category('testCategory')
   m.add_unique_arg('testUnique', 'uniqueValue')
   m.add_filter('testFilter', 'filter', 'filterValue')
   m.add_attachment_stream('testFile', 'fileValue')
   self.sg.send(m)
   url = self.sg._build_body(m)
   url.pop('api_key', None)
   url.pop('api_user', None)
   url.pop('date', None)
   testUrl = json.loads('''{"to[]": ["*****@*****.**"],
   "toname[]": ["John Doe"],
   "html": "WIN",
   "text": "WIN",
   "subject": "test",
   "files[testFile]": "fileValue",
   "from": "*****@*****.**",
   "headers": "",
   "fromname": "",
   "replyto": ""}''')
   testUrl['x-smtpapi'] = json.dumps(json.loads('''{"sub":{"subKey":["subValue"]},
     "section":{"testSection":"sectionValue"},
     "category":["testCategory"],
     "unique_args":{"testUnique":"uniqueValue"},
     "filters":{"testFilter":{"settings":{"filter":"filterValue"}}}}'''))
   self.assertEqual(url, testUrl)
コード例 #6
0
ファイル: users.py プロジェクト: GeorgeTG/uthportal-server
 def send_activation_mail(self):
     message = Mail()
     message.add_to(self.info['email'])
     message.set_subject('UthPortal activation')
     address = self.info['email']
     token = self.info['token']
     auth_id = self.info['auth_id']
     self.logger.debug('domain: ' + self._domain)
     #TODO: make some proper html
     message.set_html(
         "Please click on the following link to activate your account:\
         <a href={0}/api/v1/users/activate?email={1}&token={2}>Activate</a>, \
         This is your 8-digit unique user id: {3}\
         Use this in your app, when asked for it.\
         This id is used to personalize your push notifications.\
         Please don't share this ID as it is supposed to be kept secret."\
         .format(self._domain, address, token, auth_id))
     message.set_text('Token: {0}, 8-digit: {1}'.format(token, auth_id))
     message.set_from('UthPortal <%s>' % self._email_from)
     try:
         self._sg.send(message)
     except SendGridError as error:
         self.logger.error('SendGrid error: ' + str(error))
         raise NetworkError("Cannot send activation-email.", 500)
     except SendGridClientError as error:
         self.logger.error('SendGrid CLIENT error: ' + error.args[1])
         raise NetworkError('Cannot send activation e-mail.', 500)
     except SendGridServerError as error:
         self.logger.error('SendGrid SERVER error: [{0}] -> [{1}] ',format(
             error.args[0],
             error.args[1]
         ))
         raise NetworkError('Mail server currently un-available', 503)
コード例 #7
0
 def test_send(self):
     m = Mail()
     m.add_to('John, Doe <*****@*****.**>')
     m.set_subject('test')
     m.set_html('WIN')
     m.set_text('WIN')
     m.set_from('*****@*****.**')
     m.set_asm_group_id(42)
     m.add_cc('*****@*****.**')
     m.add_bcc('*****@*****.**')
     m.add_substitution('subKey', 'subValue')
     m.add_section('testSection', 'sectionValue')
     m.add_category('testCategory')
     m.add_unique_arg('testUnique', 'uniqueValue')
     m.add_filter('testFilter', 'filter', 'filterValue')
     m.add_attachment_stream('testFile', 'fileValue')
     url = self.sg._build_body(m)
     url.pop('api_key', None)
     url.pop('api_user', None)
     url.pop('date', None)
     test_url = json.loads('''
         {
             "to[]": ["*****@*****.**"],
             "toname[]": ["John Doe"],
             "html": "WIN",
             "text": "WIN",
             "subject": "test",
             "files[testFile]": "fileValue",
             "from": "*****@*****.**",
             "cc[]": ["*****@*****.**"],
             "bcc[]": ["*****@*****.**"]
         }
         ''')
     test_url['x-smtpapi'] = json.dumps(json.loads('''
         {
             "sub": {
                 "subKey": ["subValue"]
             },
             "section": {
                 "testSection":"sectionValue"
             },
             "category": ["testCategory"],
             "unique_args": {
                 "testUnique":"uniqueValue"
             },
             "filters": {
                 "testFilter": {
                     "settings": {
                         "filter": "filterValue"
                     }
                 }
             },
             "asm_group_id": 42
         }
         '''))
     
     try:
         self.assertItemsEqual(url, test_url)
     except: # Python 3+
         self.assertCountEqual(url, test_url)
コード例 #8
0
ファイル: __init__.py プロジェクト: n-robles/Mailv2Test
    def test_send(self):
        m = Mail()
        m.add_to('John, Doe <*****@*****.**>')
        m.set_subject('test')
        m.set_html('WIN')
        m.set_text('WIN')
        m.set_from('*****@*****.**')
        m.set_asm_group_id(42)
        m.add_cc('*****@*****.**')
        m.add_bcc('*****@*****.**')
        m.add_substitution('subKey', 'subValue')
        m.add_section('testSection', 'sectionValue')
        m.add_category('testCategory')
        m.add_unique_arg('testUnique', 'uniqueValue')
        m.add_filter('testFilter', 'filter', 'filterValue')
        m.add_attachment_stream('testFile', 'fileValue')
        url = self.sg._build_body(m)
        url.pop('api_key', None)
        url.pop('api_user', None)
        url.pop('date', None)
        test_url = json.loads('''
            {
                "to[]": ["*****@*****.**"],
                "toname[]": ["John Doe"],
                "html": "WIN",
                "text": "WIN",
                "subject": "test",
                "files[testFile]": "fileValue",
                "from": "*****@*****.**",
                "cc[]": ["*****@*****.**"],
                "bcc[]": ["*****@*****.**"]
            }
            ''')
        test_url['x-smtpapi'] = json.dumps(
            json.loads('''
            {
                "sub": {
                    "subKey": ["subValue"]
                },
                "section": {
                    "testSection":"sectionValue"
                },
                "category": ["testCategory"],
                "unique_args": {
                    "testUnique":"uniqueValue"
                },
                "filters": {
                    "testFilter": {
                        "settings": {
                            "filter": "filterValue"
                        }
                    }
                },
                "asm_group_id": 42
            }
            '''))

        self.assertEqual(url, test_url)
コード例 #9
0
def send_email_verification(user_id, resend=False):
    if not Configuration.PUSH_ENABLED:
        return

    sendgrid = create_sendgrid()

    user = User.find(user_id)

    verify_code = wigo_db.get_new_code({
        'type': 'verify_email',
        'user_id': user_id,
        'email': user.email
    })

    verify_link = '{}://{}/c/{}'.format(
        'https' if Configuration.ENVIRONMENT != 'dev' else 'http',
        Configuration.WEB_HOST, verify_code)

    logger.info('generated verify code for user "%s", "%s"' %
                (user.email, verify_code))

    first_name = user.first_name
    if not first_name:
        first_name = user.email

    msg = Mail()

    if resend:
        msg.set_subject('Everyone deserves a second chance')
    else:
        msg.set_subject('Welcome to Wigo')

    msg.set_from('Wigo <*****@*****.**>')

    if user.first_name and user.last_name:
        msg.add_to('%s <%s>' % (user.full_name, user.email))
    else:
        msg.add_to(user.email)

    msg.set_text(
        "Hi %s\n\nPlease click the following link to verify your email address:\n\n%s\n\n"
        % (first_name, verify_link))

    msg.set_html(
        render_template('confirmation_email.html',
                        name=first_name,
                        confirmation_link=verify_link,
                        resend=resend))

    msg.add_unique_arg('user_id', user.id)
    msg.add_category('verify')
    msg.add_filter('opentrack', 'enable', 0)
    msg.add_filter('subscriptiontrack', 'enable', 1)
    msg.add_filter('subscriptiontrack', 'replace', '-UNSUB-')

    sendgrid.send(msg)
    logger.info('sent verification email to "%s"' % user.email)
コード例 #10
0
 def test_send(self):
     m = Mail()
     m.add_to("John, Doe <*****@*****.**>")
     m.set_subject("test")
     m.set_html("WIN")
     m.set_text("WIN")
     m.set_from("*****@*****.**")
     m.add_substitution("subKey", "subValue")
     m.add_section("testSection", "sectionValue")
     m.add_category("testCategory")
     m.add_unique_arg("testUnique", "uniqueValue")
     m.add_filter("testFilter", "filter", "filterValue")
     m.add_attachment_stream("testFile", "fileValue")
     url = self.sg._build_body(m)
     url.pop("api_key", None)
     url.pop("api_user", None)
     url.pop("date", None)
     test_url = json.loads(
         """
         {
             "to[]": ["*****@*****.**"],
             "toname[]": ["John Doe"],
             "html": "WIN",
             "text": "WIN",
             "subject": "test",
             "files[testFile]": "fileValue",
             "from": "*****@*****.**"
         }
         """
     )
     test_url["x-smtpapi"] = json.dumps(
         json.loads(
             """
         {
             "to" : ["John, Doe <*****@*****.**>"],
             "sub": {
                 "subKey": ["subValue"]
             },
             "section": {
                 "testSection":"sectionValue"
             },
             "category": ["testCategory"],
             "unique_args": {
                 "testUnique":"uniqueValue"
             },
             "filters": {
                 "testFilter": {
                     "settings": {
                         "filter": "filterValue"
                     }
                 }
             }
         }
         """
         )
     )
     self.assertEqual(url, test_url)
コード例 #11
0
def send(sender_mail, send_to, subject, html, text=None):
    client = SendGridClient(current_app.config.get('SENDGRID_USERNAME'), current_app.config.get('SENDGRID_PASSWORD'))
    message = Mail()
    message.set_from(sender_mail)
    message.add_to(send_to)
    message.set_subject(subject)
    message.set_html(html)
    message.set_text(text)
    client.send(message)
コード例 #12
0
def sendEmail(sender, recipient, subject, html, text):
    sg = SendGridClient('ecpf', 'Iheart1!', secure=True)
    message = Mail()
    message.set_subject(subject)
    message.set_html(html)
    message.set_text(text)
    message.set_from(sender)
    message.add_to(recipient)
    sg.send(message)
    return True
コード例 #13
0
ファイル: __init__.py プロジェクト: yred/sendgrid-python
    def test_drop_to_header(self):
        m = Mail()
        m.add_to('John, Doe <*****@*****.**>')
        m.set_from('*****@*****.**')
        m.set_subject('test')
        m.set_text('test')
        m.add_bcc('John, Doe <*****@*****.**>')
        url =  self.sg._build_body(m)

        print url
コード例 #14
0
 def test_drop_to_header(self):
     smtpapi = "{}"
     m = Mail()
     m.add_to("John, Doe <*****@*****.**>")
     m.set_from("*****@*****.**")
     m.set_subject("test")
     m.set_text("test")
     m.add_bcc("John, Doe <*****@*****.**>")
     url = self.sg._build_body(m)
     self.assertEqual(smtpapi, url["x-smtpapi"])
コード例 #15
0
def sendEmail(sender, recipient, subject, html, text) :
    sg= SendGridClient('ecpf', 'Iheart1!', secure=True)
    message = Mail()
    message.set_subject(subject)
    message.set_html(html)
    message.set_text(text)
    message.set_from(sender)
    message.add_to(recipient)
    sg.send(message)
    return True
コード例 #16
0
ファイル: test.py プロジェクト: kapalani/test-sendgrid-api
def config_mail():
    message = Mail()
    message.add_to("<*****@*****.**>")
    message.add_to_name("Kumar, Palani")
    message.set_from("*****@*****.**")
    message.set_from_name("Kavin");
    message.set_subject("Test message.,")
    message.set_text("Test text")
    message.set_html("<i><b>Test HTML</b></i>")
    message.set_replyto("*****@*****.**")
    message.set_date(rfc822.formatdate())
    return message
コード例 #17
0
def config_mail():
    message = Mail()
    message.add_to("<*****@*****.**>")
    message.add_to_name("Kumar, Palani")
    message.set_from("*****@*****.**")
    message.set_from_name("Kavin")
    message.set_subject("Test message.,")
    message.set_text("Test text")
    message.set_html("<i><b>Test HTML</b></i>")
    message.set_replyto("*****@*****.**")
    message.set_date(rfc822.formatdate())
    return message
コード例 #18
0
    def post(self):
        application_key = ndb.Key(urlsafe=self.request.get('form-key'))
        application = application_key.get()

        not_complete = self._not_complete()
        if True in not_complete.values():  # If there is an error
            self.response.set_status(204)
            self._serve_page(errors=self._not_complete())
        else:
            applicant = self.user
            application.submit_time = datetime.now()
            application.put()

            config = ndb.Key(Settings, 'config').get()
            sg = SendGridClient(config.sendgrid_username,
                                config.sendgrid_password,
                                secure=True)

            verification_email = Mail(
                from_name="NYDKC Awards Committee",
                from_email="*****@*****.**",
                subject="DKC Application Confirmation for %s %s" %
                (applicant.first_name, applicant.last_name),
                to=applicant.email)

            template_values = {
                'applicant': applicant,
                'application': application
            }
            verification_email.set_html(
                JINJA_ENVIRONMENT.get_template(
                    'confirmation-email.html').render(template_values))
            htmlhandler = html2text.HTML2Text()
            verification_email.set_text(
                htmlhandler.handle(verification_email.html).encode("UTF+8"))

            code, response = sg.send(verification_email)
            response = json.loads(response)
            if response["message"] == "error":
                logging.error(("Problem with sending email to %s: " %
                               verification_email.to) +
                              str(response["errors"]))
                self._serve_page()
                return

            self.redirect('/application')
コード例 #19
0
    def send_email(self, request):
        # make a secure connection to SendGrid
        sg = SendGridClient(get_mail_username(), get_mail_pass(), secure=True)

        # make a message object
        message = Mail()
        message.set_subject('message subject')
        message.set_html('<strong>HTML message body</strong>')
        message.set_text('plaintext message body')
        message.set_from('*****@*****.**')

        # add a recipient
        message.add_to('John Doe <*****@*****.**>')

        # use the Web API to send your message
        sg.send(message)
        return message_types.VoidMessage()
コード例 #20
0
    def send_email(self, request):
        # make a secure connection to SendGrid
        sg = SendGridClient(get_mail_username(), get_mail_pass(), secure=True)

        # make a message object
        message = Mail()
        message.set_subject('message subject')
        message.set_html('<strong>HTML message body</strong>')
        message.set_text('plaintext message body')
        message.set_from('*****@*****.**')

        # add a recipient
        message.add_to('John Doe <*****@*****.**>')

        # use the Web API to send your message
        sg.send(message)
        return message_types.VoidMessage()
コード例 #21
0
    def get(self):
        # make a secure connection to SendGrid
        #sg = SendGridClient('userid', 'password', secure=True)
        print sg

        # make a message object
        message = Mail()
        message.set_subject('message subject')
        message.set_html('<strong>HTML message body</strong>')
        message.set_text('plaintext message body')
        message.set_from('*****@*****.**')

        # add a recipient
        message.add_to('Name <email>')

        # use the Web API to send your message
        sg.send(message)
        self.response.write('email sent.')
コード例 #22
0
def send_custom_email(user,
                      subject,
                      category,
                      html,
                      text,
                      template_params=None):
    sendgrid = create_sendgrid()

    msg = Mail()
    msg.set_from('Wigo <*****@*****.**>')

    if user.first_name and user.last_name:
        msg.add_to('%s <%s>' % (user.full_name, user.email))
    else:
        msg.add_to(user.email)

    # subject and body are required, for some reason, with the sendgrid templates
    msg.set_subject(Template(subject).render(user=user))

    # turn on email opens tracking
    msg.add_filter('opentrack', 'enable', 1)
    msg.add_filter('subscriptiontrack', 'enable', 1)
    msg.add_filter('subscriptiontrack', 'replace', '-UNSUB-')

    params = {'user': user}
    if template_params:
        params.update(template_params)

    html = render_template('custom_email_inlined.html',
                           html=Template(html).render(**params))
    msg.set_html(html)

    if text:
        text = Template(text +
                        '\n\n\nClick here to unsubscribe: -UNSUB-\n').render(
                            **params)
        msg.set_text(text)

    msg.add_unique_arg('user_id', user.id)

    if category:
        msg.add_category(category)

    sendgrid.send(msg)
コード例 #23
0
ファイル: __init__.py プロジェクト: kykocamp/sendgrid-python
 def test__build_body_unicode(self):
     """test _build_body() handles encoded unicode outside ascii range"""
     from_email = "\xd0\x9d\xd0\xb8\xd0\xba\xd0\[email protected]"
     from_name = "\xd0\x9a\xd0\xbb\xd0\xb0\xd0\xb2\xd0\xb4\xd0\xb8\xd1\x8f"
     subject = "\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0"
     text = "\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0"
     html = "\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0"
     m = Mail()
     m.add_to("John, Doe <*****@*****.**>")
     m.set_subject(subject)
     m.set_html(html)
     m.set_text(text)
     m.set_from("%s <%s>" % (from_name, from_email))
     url = self.sg._build_body(m)
     self.assertEqual(from_email, url["from"])
     self.assertEqual(from_name, url["fromname"])
     self.assertEqual(subject, url["subject"])
     self.assertEqual(text, url["text"])
     self.assertEqual(html, url["html"])
コード例 #24
0
 def test__build_body_unicode(self):
     """test _build_body() handles encoded unicode outside ascii range"""
     from_email = '\xd0\x9d\xd0\xb8\xd0\xba\xd0\[email protected]'
     from_name = '\xd0\x9a\xd0\xbb\xd0\xb0\xd0\xb2\xd0\xb4\xd0\xb8\xd1\x8f'
     subject = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0'
     text = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0'
     html = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0'
     m = Mail()
     m.add_to('John, Doe <*****@*****.**>')
     m.set_subject(subject)
     m.set_html(html)
     m.set_text(text)
     m.set_from("%s <%s>" % (from_name, from_email))
     url = self.sg._build_body(m)
     self.assertEqual(from_email, url['from'])
     self.assertEqual(from_name, url['fromname'])
     self.assertEqual(subject, url['subject'])
     self.assertEqual(text, url['text'])
     self.assertEqual(html, url['html'])
コード例 #25
0
ファイル: notify_email.py プロジェクト: ptere/saunterio
def send_alerts(score, threshold):
    sub_list = db.subscribers.find_one({"_id": 13722})

    for email in sub_list['emails']:
        message = Mail()
        message.add_to(email)
        message.set_subject("Nice weather alert")
        message.set_html(alert_text.format(score, threshold))
        message.set_text(alert_text.format(score, threshold))
        message.set_from('Saunter <*****@*****.**>')

        try:
            status, msg = sg.send(message)
            debug_printer.pprint(status)
            debug_printer.pprint(msg)
        except SendGridClientError:
            debug_printer.pprint(SendGridClientError)
        except SendGridServerError:
            debug_printer.pprint(SendGridServerError)
コード例 #26
0
ファイル: test_mail_v2.py プロジェクト: adeolabadmus/askavet
 def test__build_body_unicode(self):
     """test _build_body() handles encoded unicode outside ascii range"""
     from_email = '\xd0\x9d\xd0\xb8\xd0\xba\xd0\[email protected]'
     from_name = '\xd0\x9a\xd0\xbb\xd0\xb0\xd0\xb2\xd0\xb4\xd0\xb8\xd1\x8f'
     subject = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0'
     text = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0'
     html = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0'
     m = Mail()
     m.add_to('John, Doe <*****@*****.**>')
     m.set_subject(subject)
     m.set_html(html)
     m.set_text(text)
     m.set_from("%s <%s>" % (from_name, from_email))
     url = self.sg._build_body(m)
     self.assertEqual(from_email, url['from'])
     self.assertEqual(from_name, url['fromname'])
     self.assertEqual(subject, url['subject'])
     self.assertEqual(text, url['text'])
     self.assertEqual(html, url['html'])
コード例 #27
0
def sendEmailWithSendGrid(sender, to, subject, body, html):

    # make a secure connection to SendGrid
    sg = SendGridClient(username, password, secure=True)

    # make a message object
    message = Mail()
    message.set_subject(subject)
    message.set_html(html)
    message.set_text(body)
    message.set_from(sender)

    # add a recipient
    message.add_to(to)

    logging.debug("message %s" % message)

    # use the Web API to send your message
    sg.send(message)
コード例 #28
0
ファイル: voting.py プロジェクト: olala7846/ntuvb-allstar
def send_mail():
    """
    Send email with sendgrid sdk
    """
    to_email = request.form.get('to')
    subject = request.form.get('subject')
    body = request.form.get('body')
    text_body = request.form.get('text_body')
    from_email = request.form.get('from')

    utf8_body = body.encode('utf-8')
    utf8_text_body = text_body.encode('utf-8')

    message = Mail()
    message.set_subject(subject)
    message.set_html(utf8_body)
    message.set_text(utf8_text_body)
    message.set_from(from_email)
    message.add_to(to_email)
    sg.send(message)
    logger.info("Email is sent to %s" % to_email)
    return ('', 204)
コード例 #29
0
ファイル: extensions.py プロジェクト: LACMTA/places
def send_email(subject='Test email', from_email='*****@*****.**', from_name='D. Goodwin', recipients=['*****@*****.**'], text_body='Hello from Flask', html_body='Hello from <b>Flask</b>'):
	from sendgrid import SendGridClient, Mail
	api_key = 'm3tr0pl4c3s'
	api_user = '******'
	sendgrid = SendGridClient(username=api_user, password=api_key, 
		raise_errors=True,
		host='http://api.sendgrid.com',
		port=80,
		)

	message = Mail()
	message.add_to(recipients)
	message.set_from(from_email)
	message.set_from_name(from_name)
	message.set_subject(subject)
	message.set_text(text_body)
	message.set_html(html_body)

	try:
		sendgrid.send(message)
	except Exception as e:
		print "fail: %s" %(e)
コード例 #30
0
    def post(self):
        application_key = ndb.Key(urlsafe=self.request.get('form-key'))
        application = application_key.get()

        not_complete = self._not_complete()
        if True in not_complete.values(): # If there is an error
            self.response.set_status(204)
            self._serve_page(errors=self._not_complete())
        else:
            applicant = self.user
            application.submit_time = datetime.now()
            application.put()

            config = ndb.Key(Settings, 'config').get()
            sg = SendGridClient(config.sendgrid_username, config.sendgrid_password, secure=True)

            verification_email = Mail(from_name="NYDKC Awards Committee",
                                      from_email="*****@*****.**",
                                      subject="DKC Application Confirmation for %s %s" % (applicant.first_name, applicant.last_name),
                                      to=applicant.email
            )

            template_values = {
                'applicant': applicant,
                'application': application
            }
            verification_email.set_html(JINJA_ENVIRONMENT.get_template('confirmation-email.html').render(template_values))
            htmlhandler = html2text.HTML2Text()
            verification_email.set_text(htmlhandler.handle(verification_email.html).encode("UTF+8"))

            code, response = sg.send(verification_email)
            response = json.loads(response)
            if response["message"] == "error":
                logging.error(("Problem with sending email to %s: " % verification_email.to) + str(response["errors"]))
                self._serve_page()
                return

            self.redirect('/application')
コード例 #31
0
    def post(self):
        applicant = self.user
        application_key = ndb.Key(urlsafe=self.request.get('form-key'))
        application = application_key.get()

        if self._no_verify() or application.submit_time:
            logging.info("Attempt to modify verification by %s", applicant.email)
            self._serve_page()
            return

        task = self.request.get('task')
        if task != 'applicant':
            user_id = self.user.get_id()
            token = self.user_model.create_signup_token(user_id)
            verification_url = self.uri_for('verification', type='v', user_id=user_id, signup_token=token, _full=True)
            logging.info(verification_url)

            config = ndb.Key(Settings, 'config').get()
            sg = SendGridClient(config.sendgrid_username, config.sendgrid_password, secure=True)

            verification_email = Mail(from_name="NYDKC Awards Committee",
                                      from_email="*****@*****.**",
                                      subject="Distinguished Key Clubber Application Verification for %s %s" % (applicant.first_name, applicant.last_name)
            )

            verifier = ""
            if task == 'ltg':
                application.verification_ltg_email = self.request.get('ltg-email')
                application.verification_ltg_token = token
                application.verification_ltg_sent = True
                verification_email.add_to(application.verification_ltg_email)
                verifier = "Lieutenant Governor " + applicant.ltg.title()
            elif task == 'club-president':
                application.verification_club_president_email = self.request.get('club-president-email')
                application.verification_club_president_token = token
                application.verification_club_president_sent = True
                verification_email.add_to(application.verification_club_president_email)
                verifier = "Club President " + applicant.club_president.title()
            elif task == 'faculty-advisor':
                application.verification_faculty_advisor_email = self.request.get('faculty-advisor-email')
                application.verification_faculty_advisor_token = token
                application.verification_faculty_advisor_sent = True
                verification_email.add_to(application.verification_faculty_advisor_email)
                verifier = "Faculty Advisor " + applicant.faculty_advisor.title()

            template_values = {
                'applicant': applicant,
                'verification_url': verification_url,
                'verifier': verifier
            }
            verification_email.set_html(JINJA_ENVIRONMENT.get_template('verification-email.html').render(template_values))
            htmlhandler = html2text.HTML2Text()
            verification_email.set_text(htmlhandler.handle(verification_email.html).encode("UTF+8"))
            verification_email.add_unique_arg('user_id', user_id)

            code, response = sg.send(verification_email)
            response = json.loads(response)
            if response["message"] == "error":
                logging.error(("Problem with sending email to %s: " % verification_email.to) + str(response["errors"]))
                self._serve_page()
                return
        else:
            application.verification_applicant = True
            application.verification_applicant_date = datetime.now()

        application.put()
        self._serve_page()
コード例 #32
0
ファイル: python3_exp.py プロジェクト: ChillarAnand/01
                return t_group['id']


template_id = get_template_id_by_name(template_name)

message = Mail()
message.add_filter('templates', 'enable', '1')
message.add_filter('templates', 'template_id', template_id)
message.set_subject(None)
for to_addr in to_addrs:
    message.add_to(to_addr)
for key, value in context.items():
    message.add_substitution("%{}%".format(key), value)
message.set_from('Foo <*****@*****.**>')
message.set_html('  ')
message.set_text('  ')
message.set_subject('  ')












# scrapy
コード例 #33
0
ファイル: python3_exp.py プロジェクト: narala558/documents
                return t_group['id']


template_id = get_template_id_by_name(template_name)

message = Mail()
message.add_filter('templates', 'enable', '1')
message.add_filter('templates', 'template_id', template_id)
message.set_subject(None)
for to_addr in to_addrs:
    message.add_to(to_addr)
for key, value in context.items():
    message.add_substitution("%{}%".format(key), value)
message.set_from('Foo <*****@*****.**>')
message.set_html('  ')
message.set_text('  ')
message.set_subject('  ')

# scrapy

# xpath selection

# find td with `dc.identifier.uri` as text and get text of its sibling
url = response.xpath(
    '//td[contains(., "dc.identifier.uri")]/following-sibling::td/text()')

# find element with class `file-link` and get `href` of `a` inside it
pdf = response.xpath('//*[contains(@class, "file-link")]//a/@href')

from pygments.lexers import guess_lexer, guess_lexer_for_filename
guess_lexer('#!/usr/bin/python\nprint "Hello World!"')
コード例 #34
0
    def post(self):
        applicant = self.user
        application_key = ndb.Key(urlsafe=self.request.get('form-key'))
        application = application_key.get()

        if self._no_verify() or application.submit_time:
            logging.info("Attempt to modify verification by %s",
                         applicant.email)
            self._serve_page()
            return

        task = self.request.get('task')
        if task != 'applicant':
            user_id = self.user.get_id()
            token = self.user_model.create_signup_token(user_id)
            verification_url = self.uri_for('verification',
                                            type='v',
                                            user_id=user_id,
                                            signup_token=token,
                                            _full=True)
            logging.info(verification_url)

            config = ndb.Key(Settings, 'config').get()
            sg = SendGridClient(config.sendgrid_username,
                                config.sendgrid_password,
                                secure=True)

            verification_email = Mail(
                from_name="NYDKC Awards Committee",
                from_email="*****@*****.**",
                subject=
                "Distinguished Key Clubber Application Verification for %s %s"
                % (applicant.first_name, applicant.last_name))

            verifier = ""
            if task == 'ltg':
                application.verification_ltg_email = self.request.get(
                    'ltg-email')
                application.verification_ltg_token = token
                application.verification_ltg_sent = True
                verification_email.add_to(application.verification_ltg_email)
                verifier = "Lieutenant Governor " + applicant.ltg.title()
            elif task == 'club-president':
                application.verification_club_president_email = self.request.get(
                    'club-president-email')
                application.verification_club_president_token = token
                application.verification_club_president_sent = True
                verification_email.add_to(
                    application.verification_club_president_email)
                verifier = "Club President " + applicant.club_president.title()
            elif task == 'faculty-advisor':
                application.verification_faculty_advisor_email = self.request.get(
                    'faculty-advisor-email')
                application.verification_faculty_advisor_token = token
                application.verification_faculty_advisor_sent = True
                verification_email.add_to(
                    application.verification_faculty_advisor_email)
                verifier = "Faculty Advisor " + applicant.faculty_advisor.title(
                )

            template_values = {
                'applicant': applicant,
                'verification_url': verification_url,
                'verifier': verifier
            }
            verification_email.set_html(
                JINJA_ENVIRONMENT.get_template(
                    'verification-email.html').render(template_values))
            htmlhandler = html2text.HTML2Text()
            verification_email.set_text(
                htmlhandler.handle(verification_email.html).encode("UTF+8"))
            verification_email.add_unique_arg('user_id', str(user_id))

            code, response = sg.send(verification_email)
            response = json.loads(response)
            if response["message"] == "error":
                logging.error(("Problem with sending email to %s: " %
                               verification_email.to) +
                              str(response["errors"]))
                self._serve_page()
                return
        else:
            application.verification_applicant = True
            application.verification_applicant_date = datetime.now()

        application.put()
        self._serve_page()