当前位置: 首页>>代码示例>>Python>>正文


Python sendgrid.Mail类代码示例

本文整理汇总了Python中sendgrid.Mail的典型用法代码示例。如果您正苦于以下问题:Python Mail类的具体用法?Python Mail怎么用?Python Mail使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Mail类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_smtpapi_add_to

 def test_smtpapi_add_to(self):
     """Test that message.to gets a dummy address for the header to work"""
     m = Mail()
     m.smtpapi.add_to("[email protected]")
     m.set_from("[email protected]")
     m.set_subject("test")
     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[]": ["[email protected]"],
             "subject": "test",
             "from": "[email protected]"
         }
         """
     )
     test_url["x-smtpapi"] = json.dumps(
         json.loads(
             """
         {
             "to": ["[email protected]m"]
         }
         """
         )
     )
     self.assertEqual(url, test_url)
开发者ID:kykocamp,项目名称:sendgrid-python,代码行数:29,代码来源:__init__.py

示例2: send_email

def send_email(report, title):
    API_KEY = os.environ.get('SENDGRID_KEY')
    if API_KEY is None:
        print 'No SendGrid API key found! Please set the SENDGRID_KEY env var'
        sys.exit(1)

    sg = SendGridClient(API_KEY, raise_errors=True)

    # Backwards compatability for emails stored as strings, not lists
    emails = report['project_details']['email']
    if type(emails) is not list:
        emails = [emails]

    for address in emails:
        message = Mail()
        message.add_to(address)
        message.set_subject(title)
        message.set_html(generate_email_text(report))
        message.set_from('STACKS <[email protected]>')

        try:
            sg.send(message)
        except SendGridError as e:
            print e
        except SendGridClientError as e:
            print e
        except SendGridServerError as e:
            print e
开发者ID:bdosono,项目名称:stack,代码行数:28,代码来源:notifier.py

示例3: index

 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 <[email protected]>')
         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"
开发者ID:agamaloni,项目名称:anyway,代码行数:25,代码来源:main.py

示例4: recieve_result

def recieve_result():

    account_sid = "ACe36f8844f05de80021faa460764b6d33"
    auth_token = "f22d67391209d2a4f8f54266cd721978"
    client = TwilioRestClient(account_sid, auth_token)

    global numberTwo
    value = request.form

    fromValue = value.get("From")
    bodyValue = value.get("Body")
    toValue = value.get("To")
    # print "Body: " + bodyValue
    # print "From: " + fromValue
    # print "To: " + toValue

    value = "True"

    if str(bodyValue) == "An outage was reported in your area. We expect this to be resolved by 6pm today.":
        value = "False"

    elif str(bodyValue).strip().lower() == "yes":
        value = "yes"

    if value == "True":
        htmlForEmail = '<html><body><img src="http://wedte.com/wp-content/uploads/2013/01/PowerOutage.jpg" alt="Power Outage"><p></p><p></p><h3> We think that your house may have a power outage. If this is true, simply reply to this e-mail with any response so that the Electricty Supplier can serve you faster. <p></p><br><br></h3></body></html>'
        sg = SendGridClient(SendGridUserName, SendGridPassword)

        message = Mail()
        message.add_to(emailValue)
        message.set_subject("Is there a Power Outage at your house?")
        message.set_html(htmlForEmail)
        message.set_from(FromEmail)
        status, msg = sg.send(message)

        message = client.messages.create(
            body="We think that your house may have a power outage. If this is true, simply reply to this text with a 'yes' so that the Electricty Supplier can serve you faster.",
            to=str(personalNumber),  # Replace with your phone number
            from_=str(number),
        )  # Replace with your Twilio number

    elif value == "yes":
        value = "True"

    elif value == "no":
        value = "False"

    payload = {"powerOutage": value, "twilioNumber": number}
    r = requests.post("http://ec2-54-68-73-74.us-west-2.compute.amazonaws.com:5000/powerreply", data=payload)

    numberTwo = number

    print str(value)
    print numberTwo

    return "Test"
开发者ID:Usman-Chaudhry,项目名称:Project-Pulsar,代码行数:56,代码来源:TwilioServer.py

示例5: _send_message_with_sg

def _send_message_with_sg(send_to, send_from, subject, body):

    message = Mail()
    message.add_to(send_to)
    message.set_from(send_from)
    message.set_subject(subject)
    message.set_html(body)

    print "Sending email:({}) to :({})".format(subject, send_to)
    sg.send(message)
开发者ID:khanduri,项目名称:base_login_social,代码行数:10,代码来源:tasks.py

示例6: send_email

def send_email(name: str, address: str, subject: str, template: str, values: dict) -> bool:
    sg = SendGridClient(config.SENDGRID_API_USER, config.SENDGRID_API_KEY)

    mail = Mail()
    mail.set_from('tototo <[email protected]>')
    mail.add_to(name + ' <' + address + '>')
    mail.set_subject(subject)
    mail.set_html(render_template(template, **values))

    status, _ = sg.send(mail)

    return status == 200
开发者ID:StdCarrot,项目名称:tototo,代码行数:12,代码来源:notification.py

示例7: __init__

	def __init__(self):
		self.email_config = SendGridConfiguration.objects.all()[:1].get()
		self.sg = SendGridClient(self.email_config.api_key)
		self.message = Mail()
		self.message.set_from(self.email_config.email_from)
		self.message.set_from_name(self.email_config.email_from_name)
		self.message.set_subject(self.email_config.email_subject)
开发者ID:roofcat,项目名称:ivr-support,代码行数:7,代码来源:sendgrid_client.py

示例8: get_sendgrid_request_message

def get_sendgrid_request_message(cfg, keyid, hex, user_email):
    url_prefix = urljoin(
        cfg.config.megserver_hostname_url,
        os.path.join(cfg.config.meg_url_prefix, "revoke")
    )
    params = urlencode([("keyid", keyid), ("token", hex)])
    parsed = list(urlparse(url_prefix))
    parsed[4] = params
    revocation_link = urlunparse(parsed)

    message = Mail()
    message.add_to(user_email)
    message.set_from(cfg.config.sendgrid.from_email)
    message.set_subject(cfg.config.sendgrid.subject)
    message.set_html(EMAIL_HTML.format(keyid=keyid, link=revocation_link))
    return message
开发者ID:Argonne-National-Laboratory,项目名称:meg-server,代码行数:16,代码来源:email.py

示例9: post

    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="[email protected]",
                                      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')
开发者ID:tanadeko,项目名称:dkc-application,代码行数:38,代码来源:application.py

示例10: test_smtpapi_add_to

 def test_smtpapi_add_to(self):
     '''Test that message.to gets a dummy address for the header to work'''
     m = Mail()
     m.smtpapi.add_to('[email protected]')
     m.set_from('[email protected]')
     m.set_subject('test')
     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[]": ["[email protected]"],
             "subject": "test",
             "from": "[email protected]"
         }
         ''')
     test_url['x-smtpapi'] = json.dumps(json.loads('''
         {
             "to": ["[email protected]"]
         }
         '''))
     self.assertEqual(url, test_url)
开发者ID:Adomako-Bismark,项目名称:sendgrid-python,代码行数:23,代码来源:test_mail_v2.py

示例11: test_send

 def test_send(self):
     m = Mail()
     m.add_to('John, Doe <[email protected]>')
     m.set_subject('test')
     m.set_html('WIN')
     m.set_text('WIN')
     m.set_from('[email protected]')
     m.set_asm_group_id(42)
     m.add_cc('[email protected]')
     m.add_bcc('[email protected]')
     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[]": ["[email protected]"],
             "toname[]": ["John Doe"],
             "html": "WIN",
             "text": "WIN",
             "subject": "test",
             "files[testFile]": "fileValue",
             "from": "[email protected]",
             "cc[]": ["[email protected]"],
             "bcc[]": ["[email protected]"]
         }
         ''')
     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)
开发者ID:Adomako-Bismark,项目名称:sendgrid-python,代码行数:60,代码来源:test_mail_v2.py

示例12: threshold_not_met

def threshold_not_met(petitioner_id, organization, election, threshold, signatures, position, petition_email, admin_emails):
    petitioner = netid2name(petitioner_id)

    # Make a secure connection to SendGrid
    sg = SendGridClient('harmonica1243', 'xqBrrnNqbGuvtEUpNRs3RePW', secure=True)

    # Replace with the message that we want to send, such as the name of the person and the position
    html_petition = '<p style="text-align: left;"><b>Dear ' + petitioner + ',</b></p><p style="text-align: center;">' \
        '<p>Your petition no longer has the required number of signatures</p><ul><li><b>Organization:</b> ' \
         + organization + '</li><li><b>Election:</b> ' + election + '</li><li><b>Position:</b> ' + position + '</li>' \
        '<li><b>Number of Signatures Required:</b> ' + threshold + '</li><li><b>Number of Signatures Obtained:</b> ' \
        + signatures + '</li></ul><p>Please contact the organization directly with any questions about the petition.' \
        '</p></p><p style="text-align: left;"><b>Rice Apps Petitions</b></p>'
    html_admin = '<p style="text-align: left;"><b>Dear Organization Administrator,</b></p><p style="text-align: center;">' \
        '<p>This petition no longer has the required number of signatures</p><ul><li><b>Petition Creator:</b> ' \
        + petitioner + '</li><li><b>Organization:</b> ' + organization + '</li><li><b>Election:</b> ' + election + \
        '</li><li><b>Position:</b> ' + position + '</li><li><b>Number of Signatures Required:</b> ' + threshold + \
        '</li><li><b>Number of Signatures Obtained:</b> ' + signatures + '</li></ul><p>Please contact ' + ADMIN_ID + \
        '@rice.edu with any questions.</p></p><p style="text-align: left;"><b>Rice Apps Petitions</b></p>'

    # Make a message Object
    message = Mail()

    # Message Subject, Body and To
    message.set_subject('Petition No Longer Has Enough Signatures')
    message.set_html(html_petition)
    message.set_from('[email protected]')
    message.add_to('<' + petition_email + '>')
    sg.send(message)

    # Make a message Object
    message = Mail()

    # Message Subject, Body and To
    message.set_subject('Petition No Longer Has Enough Signatures')
    message.set_html(html_admin)
    message.set_from('[email protected]')
    for email in admin_emails:
        message.add_to('<' + email + '>')
    sg.send(message)
开发者ID:rice-apps,项目名称:petition-app,代码行数:40,代码来源:mail.py

示例13: SGEmailClient

class SGEmailClient(object):

	def __init__(self):
		self.email_config = SendGridConfiguration.objects.all()[:1].get()
		self.sg = SendGridClient(self.email_config.api_key)
		self.message = Mail()
		self.message.set_from(self.email_config.email_from)
		self.message.set_from_name(self.email_config.email_from_name)
		self.message.set_subject(self.email_config.email_subject)

	def send_report_email(self, email, report):
		template_config = TemplateReport.objects.all()[:1].get()
		user = get_object_or_404(User, pk=email)
		logger.info(user)
		html = unicode(template_config.html_template).format(
			user_name=user.first_name,
		)
		self.message.add_to(user.email)
		self.message.add_to_name(user.first_name)
		self.message.set_html(html)

		if report['report']:
			self.message.add_attachment_stream(
				report['name'] , report['report']
			)

		status, msg = self.sg.send(self.message)
		logger.info('{0} - {1}'.format(status, msg))
开发者ID:roofcat,项目名称:ivr-support,代码行数:28,代码来源:sendgrid_client.py

示例14: EmailClient

class EmailClient(object):

    def __init__(self):
        self.sg = SendGridClient(SG_API_KEY)
        self.message = Mail()
        self.message.set_from(SG_FROM)
        self.message.set_from_name(SG_FROM_NAME)

    def send_sg_email(self, correo):
        # valores de envío
        self.message.add_to(correo.correo)
        self.message.add_to_name(correo.nombre_cliente)
        self.message.set_subject(correo.asunto)
        self.message.set_html(correo.html)
        # valores personalizados
        unique_args = {
            'empresa': correo.empresa,
            'rut_receptor': correo.rut_receptor,
            'rut_emisor': correo.rut_emisor,
            'tipo_envio': correo.tipo_envio,
            'tipo_dte': correo.tipo_dte,
            'numero_folio': correo.numero_folio,
            'resolucion_receptor': correo.resolucion_receptor,
            'resolucion_emisor': correo.resolucion_emisor,
            'monto': correo.monto,
            'fecha_emision': correo.fecha_emision,
            'fecha_recepcion': correo.fecha_recepcion,
            'estado_documento': correo.estado_documento,
            'tipo_operacion': correo.tipo_operacion,
            'tipo_receptor': correo.tipo_receptor,
        }
        self.message.set_unique_args(unique_args)
        # Validacion de adjuntos
        if correo.attachs:
            for adjunto in correo.attachs:
                adj = AttachModel.query(ancestor=adjunto).get()
                self.message.add_attachment_stream(adj.nombre, adj.archivo)
        # enviando el mail
        status, msg = self.sg.send(self.message)
        # imprimiendo respuesta
        logging.info(status)
        logging.info(msg)

    def send_mail_to_user_attach(self, correo):
        # valores de envío
        self.message.add_to(correo['email'])
        self.message.add_to_name(correo['user_name'])
        self.message.set_subject(correo['subject'])
        self.message.set_html(correo['html'])
        if correo['attach']:
            self.message.add_attachment_stream(correo['attach']['name'], correo['attach']['file'])
        status, msg = self.sg.send(self.message)
        # imprimiendo respuesta
        logging.info(status)
        logging.info(msg)
开发者ID:roofcat,项目名称:etracking,代码行数:55,代码来源:mail_client.py

示例15: __init__

 def __init__(self):
     self.sg = SendGridClient(SG_API_KEY)
     self.message = Mail()
     self.message.set_from(SG_FROM)
     self.message.set_from_name(SG_FROM_NAME)
开发者ID:roofcat,项目名称:etracking,代码行数:5,代码来源:mail_client.py


注:本文中的sendgrid.Mail类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。