當前位置: 首頁>>代碼示例>>Python>>正文


Python mail.Mail方法代碼示例

本文整理匯總了Python中sendgrid.helpers.mail.Mail方法的典型用法代碼示例。如果您正苦於以下問題:Python mail.Mail方法的具體用法?Python mail.Mail怎麽用?Python mail.Mail使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sendgrid.helpers.mail的用法示例。


在下文中一共展示了mail.Mail方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: send

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send(self, using_jinja=False):
        message = Mail(
            from_email=self.message.sender,
            to_emails=[self.message.recipient],
            subject=self.message.subject,
            html_content=self._build_content(using_jinja)
        )
        response = self.mailer.client.mail.send.post(request_body=message.get())

        if response.status_code < 300:
            _log.info('Email sent successfully')
        else:
            _log.error(
                'Email failed to send.  Status code: {}  '
                'Status message: {}'.format(response.status_code, response.body)
            ) 
開發者ID:MycroftAI,項目名稱:selene-backend,代碼行數:18,代碼來源:email.py

示例2: send_email

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send_email(self, to_email, from_email, subject, body):
        """Send the email

                :param to_email:   who the email is going to
                                   (e.g. 'First Last <email@example.com>')
                :param from_email: who the email is coming from
                                   (e.g. 'First Last <email@example.com>')
                :param subject:    the email subject line
                :param body:       the email body in HTML format
                :type to_email:    string
                :type from_email:  string
                :type subject:     string
                :type body:        string

                :returns: HTML status code and JSON message from SendGrid's API
                :rtype: Integer, JSON
        """
        from_email = Email(from_email)
        subject = subject
        to_email = Email(to_email)
        soup = BeautifulSoup(body, "html.parser")
        content = Content("text/plain", soup.get_text())
        mail = Mail(from_email, subject, to_email, content)
        response = self.sendgrid.client.mail.send.post(request_body=mail.get())
        return response.status_code, response.body 
開發者ID:sendgrid,項目名稱:open-source-library-data-collector,代碼行數:27,代碼來源:sendgrid_email.py

示例3: send_email

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send_email():
    recipient = request.form.get('to')
    if not recipient:
        return ('Please provide an email address in the "to" query string '
                'parameter.'), 400

    message = Mail(
        from_email=SENDGRID_SENDER,
        to_emails='{},'.format(recipient),
        subject='This is a test email',
        html_content='<strong>Example</strong> message.')
    sg = sendgrid.SendGridAPIClient(SENDGRID_API_KEY)

    response = sg.send(message)

    if response.status_code != 202:
        return 'An error occurred: {}'.format(response.body), 500

    return 'Email sent.'
# [END gae_flex_sendgrid] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:22,代碼來源:main.py

示例4: send_single_email

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send_single_email(email, subject, template, template_arguments):
    """ Send an email using the SendGrid API
        Args:
            - email :string => the user's work email (ie username@company.com)
            - subject :string => the subject line for the email
            - template :string => the template file, corresponding to the email sent.
            - template_arguments :dictionary => keyword arguments to specify to render_template
        Returns:
            - SendGrid response
    """
    load_secrets()
    env = Environment(loader=PackageLoader('yelp_beans', 'templates'))
    template = env.get_template(template)
    rendered_template = template.render(template_arguments)

    message = mail.Mail(
        from_email=mail.Email(SENDGRID_SENDER),
        subject=subject,
        to_email=mail.Email(email),
        content=Content("text/html", rendered_template)
    )

    return send_grid_client.client.mail.send.post(request_body=message.get()) 
開發者ID:Yelp,項目名稱:beans,代碼行數:25,代碼來源:send_email.py

示例5: __init__

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def __init__(self, app=None, **opts):
        if app:
            self.init_app(app)
        super(SGMail, self).__init__()
        self.from_email = None
        self.subject = None
        self._personalizations = None
        self._contents = None
        self._attachments = None
        self._template_id = None
        self._sections = None
        self._headers = None
        self._categories = None
        self._custom_args = None
        self._send_at = None
        self._batch_id = None
        self._asm = None
        self._ip_pool_name = None
        self._mail_settings = None
        self._tracking_settings = None
        self._reply_to = None 
開發者ID:frankV,項目名稱:flask-sendgrid,代碼行數:23,代碼來源:flask_sendgrid.py

示例6: test_can_send_email_to_single_recipient

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def test_can_send_email_to_single_recipient(self):
        """Test can send email to single recipient."""

        new_email = mail.Mail()
        email_recipient = 'foo@company.com'
        email_sender = 'bar@company.com'
        email_connector_config = {
            'fake_sendgrid_key': 'xyz010'
        }
        email_util = sendgrid_connector.SendgridConnector(
            email_sender,
            email_recipient,
            email_connector_config)
        new_email = email_util._add_recipients(new_email, email_recipient)

        self.assertEqual(1, len(new_email.personalizations))

        added_recipients = new_email.personalizations[0].tos
        self.assertEqual(1, len(added_recipients))
        self.assertEqual('foo@company.com', added_recipients[0].get('email')) 
開發者ID:forseti-security,項目名稱:forseti-security,代碼行數:22,代碼來源:sendgrid_connector_test.py

示例7: test_can_send_email_to_multiple_recipients

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def test_can_send_email_to_multiple_recipients(self):
        """Test can send email to multiple recipients."""

        new_email = mail.Mail()
        email_recipient = 'foo@company.com,bar@company.com'
        email_sender = 'xyz@company.com'
        email_connector_config = {
            'fake_sendgrid_key': 'xyz010'
        }
        email_util = sendgrid_connector.SendgridConnector(
            email_sender,
            email_recipient,
            email_connector_config)
        new_email = email_util._add_recipients(new_email, email_recipient)

        self.assertEqual(1, len(new_email.personalizations))

        added_recipients = new_email.personalizations[0].tos
        self.assertEqual(2, len(added_recipients))
        self.assertEqual('foo@company.com', added_recipients[0].get('email'))
        self.assertEqual('bar@company.com', added_recipients[1].get('email')) 
開發者ID:forseti-security,項目名稱:forseti-security,代碼行數:23,代碼來源:sendgrid_connector_test.py

示例8: send

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send(to_email, subject, html_content):
  """Send email."""
  sendgrid_api_key = db_config.get_value('sendgrid_api_key')
  if not sendgrid_api_key:
    logs.log_warn('Skipping email as SendGrid API key is not set in config.')
    return

  from_email = db_config.get_value('sendgrid_sender')
  if not from_email:
    logs.log_warn('Skipping email as SendGrid sender is not set in config.')
    return

  message = Mail(
      from_email=From(str(from_email)),
      to_emails=To(str(to_email)),
      subject=Subject(subject),
      html_content=HtmlContent(str(html_content)))
  try:
    sg = SendGridAPIClient(sendgrid_api_key)
    response = sg.send(message)
    logs.log(
        'Sent email to %s.' % to_email,
        status_code=response.status_code,
        body=response.body,
        headers=response.headers)
  except Exception:
    logs.log_error('Failed to send email to %s.' % to_email) 
開發者ID:google,項目名稱:clusterfuzz,代碼行數:29,代碼來源:mail.py

示例9: send_simple_message

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send_simple_message(recipient):
    # [START sendgrid-send]
    message = Mail(
        from_email=SENDGRID_SENDER,
        to_emails='{},'.format(recipient),
        subject='This is a test email',
        html_content='<strong>Example</strong> message.')

    sg = sendgrid.SendGridAPIClient(SENDGRID_API_KEY)
    response = sg.send(message)

    return response
    # [END sendgrid-send] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:15,代碼來源:main.py

示例10: send_email

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send_email(subject, to, template_name, context):
    sendgrid_client = sendgrid.SendGridAPIClient(settings.SENDGRID_API_KEY)

    from_email = settings.DEFAULT_FROM_EMAIL
    to_emails = to
    content = render_to_string(template_name, context)

    mail = Mail(from_email, to_emails, subject, content)
    return sendgrid_client.send(mail) 
開發者ID:jllorencetti,項目名稱:pets,代碼行數:11,代碼來源:services.py

示例11: send_email_message

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
        """ Send email message via sendgrid-python.

        Args:
            recipient: Email address or tuple of (Name, Email-address).
            subject: Subject line.
            html_message: The message body in HTML.
            text_message: The message body in plain text.
        """

        if not current_app.testing:  # pragma: no cover
            try:
                # Prepare Sendgrid helper objects
                from sendgrid.helpers.mail import Email, Content, Substitution, Mail
                from_email = Email(sender_email, sender_name)
                to_email = Email(recipient)
                text_content = Content('text/plain', text_message)
                html_content = Content('text/html', html_message)
                # Prepare Sendgrid Mail object
                # Note: RFC 1341: text must be first, followed by html
                mail = Mail(from_email, subject, to_email, text_content)
                mail.add_content(html_content)
                # Send mail via the Sendgrid API
                response = self.sg.client.mail.send.post(request_body=mail.get())
                print(response.status_code)
                print(response.body)
                print(response.headers)
            except ImportError:
                raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE)
            except Exception as e:
                print(e)
                print(e.body)
                raise 
開發者ID:lingthio,項目名稱:Flask-User,代碼行數:35,代碼來源:sendgrid_email_adapter.py

示例12: send

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send(self, message, envelope_from=None):
        assert message.send_to, "No recipients have been added"
        assert message.sender, (
                "The message does not specify a sender and a default sender "
                "has not been configured")
        if message.has_bad_headers():
            raise BadHeaderError
        if message.date is None:
            message.date = time.time()
        sgmessage = SGMail(
            from_email=Email(message.sender),
            to_emails=[To(addressee) for addressee in sanitize_addresses(message.recipients)],
            subject=message.subject,
            plain_text_content=message.body,
            html_content=message.html)
        if message.cc:
            for recipient in list(sanitize_addresses(message.cc)):
                sgmessage.add_cc(recipient)
        if message.bcc:
            for recipient in list(sanitize_addresses(message.bcc)):
                sgmessage.add_bcc(recipient)
        if message.attachments:
            for flask_attachment in message.attachments:
                attachment = Attachment()
                attachment.file_content = FileContent(base64.b64encode(flask_attachment.data).decode())
                attachment.file_type = FileType(flask_attachment.content_type)
                attachment.file_name = FileName(flask_attachment.filename)
                attachment.disposition = Disposition(flask_attachment.disposition)
                sgmessage.add_attachment(attachment)
        sg = SendGridAPIClient(self.mail.api_key)
        response = sg.send(sgmessage)
        #sys.stderr.write("SendGrid status code: " + str(response.status_code) + "\n")
        #sys.stderr.write(str(response.body) + "\n")
        #sys.stderr.write("SendGrid response headers: " + str(response.headers) + "\n")
        if response.status_code >= 400:
            raise Exception("Failed to send e-mail message to SendGrid")
        email_dispatched.send(message, app=current_app._get_current_object()) 
開發者ID:jhpyle,項目名稱:docassemble,代碼行數:39,代碼來源:sendgrid_mail.py

示例13: send_email

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send_email(cls, to_email, subject, html_content, from_email='proton_framework@apricity.co.in'):
        """
        PROTONs postman.

        :param to_email: valid email to which email needs to be sent to.
        :param subject: Email subject
        :param html_content: Email content.(Can include HTML markups)
        :param from_email: valid email from which email has to be sent from. (default: proton_framework@apricity.co.in)
        :return: A dictionary containing email status code, email body and email headers.
        """
        try:

            message = Mail(
                from_email=from_email,
                to_emails=to_email,
                subject=subject,
                html_content=ProtonEmail.__email_decorator(html_content))
            response = cls.__sg.send(message)
            return {
                'email_status_code': response.status_code,
                'email_body': response.body,
                'email_headers': response.headers
            }

        except Exception as e:
            cls.email_logger.exception('[Email]: Unable to send email. Details to follow.')
            cls.email_logger.exception(str(e)) 
開發者ID:PruthviKumarBK,項目名稱:PROTON,代碼行數:29,代碼來源:email.py

示例14: send

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send(self, email_sender=None, email_recipient=None,
             email_subject=None, email_content=None, content_type=None,
             attachment=None):
        """Send an email.

        This uses the SendGrid API.
        https://github.com/sendgrid/sendgrid-python

        The minimum required info to send email are:
        sender, recipient, subject, and content (the body)

        Args:
            email_sender (str): The email sender.
            email_recipient (str): The email recipient.
            email_subject (str): The email subject.
            email_content (str): The email content (aka, body).
            content_type (str): The email content type.
            attachment (Attachment): A SendGrid Attachment.

        Raises:
            EmailSendError: An error with sending email has occurred.
        """
        if not email_sender or not email_recipient:
            LOGGER.warning('Unable to send email: sender=%s, recipient=%s',
                           email_sender, email_recipient)
            raise util_errors.EmailSendError

        email = mail.Mail()
        email.from_email = mail.Email(email_sender)
        email.subject = email_subject
        email.add_content(mail.Content(content_type, email_content))

        email = self._add_recipients(email, email_recipient)

        if attachment:
            email.add_attachment(attachment)

        try:
            response = self._execute_send(email)
        except urllib.error.HTTPError as e:
            LOGGER.exception('Unable to send email: %s %s',
                             e.code, e.reason)
            raise util_errors.EmailSendError

        if response.status_code == 202:
            LOGGER.info('Email accepted for delivery:\n%s',
                        email_subject)
        else:
            LOGGER.error('Unable to send email:\n%s\n%s\n%s\n%s',
                         email_subject, response.status_code,
                         response.body, response.headers)
            raise util_errors.EmailSendError 
開發者ID:forseti-security,項目名稱:forseti-security,代碼行數:54,代碼來源:sendgrid_connector.py

示例15: send_email

# 需要導入模塊: from sendgrid.helpers import mail [as 別名]
# 或者: from sendgrid.helpers.mail import Mail [as 別名]
def send_email(to, subject, body, cc=(), from_name='Ok',
               link=None, link_text="Sign in",
               template='email/notification.html', reply_to=None, **kwargs):
    """ Send an email using sendgrid.
    Usage: send_email('student@okpy.org', 'Hey from OK', 'hi',
                      cc=['test@example.com'], reply_to='ta@cs61a.org')
    """
    try:
        sg = _get_sendgrid_api_client()
    except ValueError as ex:
        logger.error('Unable to get sendgrid client: %s', ex)
        return False

    if not link:
        link = url_for('student.index', _external=True)

    html = render_template(template, subject=subject, body=body,
                           link=link, link_text=link_text, **kwargs)
    mail = sg_helpers.Mail()
    mail.set_from(sg_helpers.Email('no-reply@okpy.org', from_name))
    mail.set_subject(subject)
    mail.add_content(sg_helpers.Content("text/html", emailFormat(html)))

    if reply_to:
        mail.set_reply_to(sg_helpers.Email(reply_to))

    personalization = sg_helpers.Personalization()
    personalization.add_to(sg_helpers.Email(to))
    for recipient in cc:
        personalization.add_cc(sg_helpers.Email(recipient))

    mail.add_personalization(personalization)

    try:
        response = sg.client.mail.send.post(request_body=mail.get())
    except HTTPError:
        logger.error("Could not send the email", exc_info=True)
        return False

    if response.status_code != 202:
        logger.error("Could not send email: {} - {}"
                     .format(response.status_code, response.body))
        return False
    return True 
開發者ID:okpy,項目名稱:ok,代碼行數:46,代碼來源:utils.py


注:本文中的sendgrid.helpers.mail.Mail方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。