Esempio n. 1
0
def send_fax_as_email(from_, to, status, pages, error_code, error_message,
                      content, content_type):
    message = mail.Mail()
    message.from_email = mail.Email('{}{}@{}'.format(
        app.config['FAX_EMAIL_PREFIX'], from_,
        app.config['INBOUND_EMAIL_DOMAIN']))
    message.subject = 'Incoming fax'
    personalization = mail.Personalization()
    personalization.add_to(mail.Email(model.email_from_number(to)))
    message.add_personalization(personalization)
    message.add_content(
        mail.Content(
            'text/html', '''
        <table>
            <tr><th>From</th><td>{from_}</td></tr>
            <tr><th>To</th><td>{to}</td></tr>
            <tr><th>Status</th><td>{status}</td></tr>
            <tr><th>Pages</th><td>{pages}</td></tr>
            <tr><th>Fax Error Code</th><td>{error_code}</td>
            <tr><th>Fax Error Message</th><td>{error_message}</td>
        </table>
        '''.format(**locals())))

    if content:
        attachment = mail.Attachment()
        attachment.content = base64.b64encode(content).decode('ascii')
        attachment.type = content_type
        attachment.filename = 'fax.pdf'
        attachment.disposition = "attachment"
        attachment.content_id = "Fax"
        message.add_attachment(attachment)

    data = message.get()

    app.sendgrid_client.client.mail.send.post(request_body=data)
Esempio n. 2
0
def SendEmail(to_email_addresses,
              subject,
              body,
              body_html=None,
              attach_file_address=None,
              cc_email_addresses=None,
              bcc_email_addresses=None):

    from_email = "*****@*****.**"
    mail = sgm.Mail(from_email=from_email,
                    to_emails=to_email_addresses,
                    subject=subject,
                    plain_text_content=body,
                    html_content=body_html)
    mail.reply_to = sgm.ReplyTo('*****@*****.**')

    if attach_file_address != None:
        if type(attach_file_address) != list:
            attach_file_address = [attach_file_address]
        for file_address in attach_file_address:
            attachment = PrepAttachment(file_address)
            mail.add_attachment(attachment)

    if cc_email_addresses != None:
        for email_address in cc_email_addresses:
            mail.add_cc(email_address)

    if bcc_email_addresses != None:
        for email_address in bcc_email_addresses:
            mail.add_bcc(email_address)

    sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SendGridAPIKey'))
    sg.send(mail)
def send_via_sendgrid(sender_email, sender_name, receiver_email, email_subject,
                      content):
    SENDGRID_API_KEY = get_sendgrid_api_key(
    )  # make sure to create this get_sendgrid_api_key() function in utils/secrets.py first
    sg = sendgrid.SendGridAPIClient(api_key=SENDGRID_API_KEY)

    email_message = sendgrid_mail.Mail()
    email_message.set_from(sendgrid_mail.Email(sender_email, sender_name))
    email_message.set_subject(email_subject)
    email_message.add_content(sendgrid_mail.Content("text/html", content))

    personalization = sendgrid_mail.Personalization()
    personalization.add_to(sendgrid_mail.Email(receiver_email))

    email_message.add_personalization(personalization)

    try:
        response = sg.client.mail.send.post(request_body=email_message.get())

        if str(
                response.status_code
        )[:1] != "2":  # success codes start with 2, for example 200, 201, 202, ...
            logging.error("status code: " + str(response.status_code))
            logging.error("headers: " + str(response.headers))
            return logging.error("body: " + str(response.body))
    except Exception as e:
        logging.error("Error with sending via sendgrid.")
        return logging.error(e.message)
    def _create_message(
        self,
        to_email: str,
        from_email: str,
        from_email_name: str,
        subject: str,
        html_content: str,
        cc_addresses: Optional[List[str]] = None,
        text_attachment_content: Optional[str] = None,
    ) -> mail_helpers.Mail:
        """Creates the request body for the email that will be sent. Includes all required data to send a single email.

        If there are cc_addresses, it adds those to the request body for the emails.

        If there is text_attachment_content, it creates a 'text/plain' txt file attachment with the content.
        """
        message = mail_helpers.Mail(
            to_emails=to_email,
            from_email=self._create_email_address(from_email, from_email_name),
            subject=subject,
            html_content=html_content,
        )
        if cc_addresses:
            message.cc = [
                mail_helpers.Cc(email=cc_email_address)
                for cc_email_address in cc_addresses
            ]

        if text_attachment_content:
            message.attachment = self._create_text_attachment(text_attachment_content)

        return message
Esempio n. 5
0
    def create_email(
        self,
        to_list: List[str],
        subject: str,
        html_content: str,
    ) -> Type[mail.Mail]:
        """Create a new email entitie of sendgrid.

        Params:
        -------
        - to_list: List[str] - Email address list of recipients.
        - subject: str - Email subject
        - html_content: - The email content in html format

        Return:
        -------
        - email: Mail - The sendgrid emai entitie with passed data.
        """
        email: mail.Mail = mail.Mail()
        email.from_email = mail.From(self.from_email)
        email.subject = mail.Subject(subject)

        for recipient in to_list:
            email.add_to(recipient)

        email.content = mail.Content(mail.MimeType.html, html_content)
        return email
Esempio n. 6
0
 def send(
     self,
     email_from: Optional[str],
     email_to: str,
     subject: str,
     message: str,
     content_type: str = DEFAULT_EMAIL_CONTENT_TYPE,
 ) -> None:
     if self.filter and self.filter.match(email_to):
         logger.info("Filtered email to: %s", email_to)
         return
     if email_from is None:
         email_from = self.sender
     mail = sg.Mail(
         sg.Email(email_from),
         subject,
         sg.Email(email_to),
         sg.Content(content_type, message),
     )
     try:
         t1 = time.time()
         self.api.client.mail.send.post(request_body=mail.get())
         t2 = time.time()
         logger.info("Sendgrid request completed in %.3f seconds", t2 - t1)
         logger.info("Sendgrid to %s successful", email_to)
     except Exception as exc:
         logger.error("Sendgrid to %s failed: %s", email_to, str(exc))
         raise MessengerException(f"Error sending email to {email_to} via Sendgrid")
Esempio n. 7
0
    def send_results(self):
        user_query = User.query()
        sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
        from_email = mail.Email("*****@*****.**")
        subject = "The baby has landed"
        body = """Ianni Baby 2.0 has Arrived!

Let's see how you did in the betting pool """
        admin = User.query(User.email == ADMIN_EMAIL).get()
        if user_query.count() > 0 and admin:
            results = []
            for user in user_query:
                if user.date and user.email != ADMIN_EMAIL:
                    result = self.calc_score(user, admin)
                    results.append(result)
            results = sorted(results, key=lambda k: k['total'], reverse=True)
            for result in results:
                body += """

User: {} Score: {}

""".format(result['user'].name, result['total'])

            body += """

        See full results at http://ianni-baby-2.appspot.com/results."""

            for user in user_query:
                to_email = mail.Email(user.email)
                content = mail.Content('text/plain', body)
                message = mail.Mail(from_email, subject, to_email, content)
                if user.email != ADMIN_EMAIL:
                    response = sg.client.mail.send.post(
                        request_body=message.get())
Esempio n. 8
0
    def send_email(self, email: mail_.Email) -> bool:
        mail = sg_mail.Mail()
        personalization = sg_mail.Personalization()
        mail.set_from(sendgrid.Email(email.sender[1], email.sender[0]))
        mail.set_subject(email.subject)
        mail.add_content(sg_mail.Content("text/plain", email.content))

        for recipient in email.recipients:
            personalization.add_to(sendgrid.Email(recipient))

        if email.cc:
            for recipient in email.cc:
                personalization.add_cc(sendgrid.Email(recipient))

        if email.bcc:
            for recipient in email.bcc:
                personalization.add_bcc(sendgrid.Email(recipient))

        mail.add_personalization(personalization)
        response = self._sg_client.client.mail.send.post(
            request_body=mail.get())

        if response.status_code in [202, 250]:
            return True
        elif response.status_code == 421:
            raise exceptions_.ServiceRateLimitException(self.name)
        elif response.status_code in [450, 550, 551, 552, 553]:
            exceptions_.InvalidRecipientException(self.name)
        else:
            exceptions_.GenericEmailServiceException(self.name)

        return False
Esempio n. 9
0
    def send(self,
             email_sender=None,
             email_recipient=None,
             email_subject=None,
             email_content=None,
             content_type='text/plain',
             attachment=None):
        """Send an email.

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

        The minimum required info to send email are:
        sender, recipient, subject, and content (the body)
        
        Args:
            email_sender: String of the email sender.
            email_recipient: String of the email recipient.
            email_subject: String of the email subject.
            email_content: String of the email content (aka, body).
            content_type: String of the email content type.
            attachment: A SendGrid Attachment.
        
        Returns:
            None.
        
        Raises:
            EmailSendError: An error with sending email has occurred.
        """

        if not email_sender or not email_recipient:
            self.logger.warn(
                'Unable to send email: sender={}, recipient={}'.format(
                    email_sender, email_recipient))
            raise EmailSendError

        email = mail.Mail(mail.Email(email_sender), email_subject,
                          mail.Email(email_recipient),
                          mail.Content(content_type, email_content))

        if attachment:
            email.add_attachment(attachment)

        try:
            response = self._execute_send(email)
        except (URLError, HTTPError) as e:
            self.logger.error('Unable to send email: {0} {1}'.format(
                e.code, e.reason))
            raise EmailSendError

        if response.status_code == 202:
            self.logger.info(
                'Email accepted for delivery:\n{0}'.format(email_subject))
        else:
            self.logger.error(
                'Unable to send email:\n{0}\n{1}\n{2}\n{3}'.format(
                    email_subject, response.status_code, response.body,
                    response.headers))
            raise EmailSendError
Esempio n. 10
0
def send_mail(from_email, to_email, subject, body):
    message = mail.Mail(mail.Email(from_email), subject, mail.Email(to_email),
                        mail.Content('text/plain', body))
    response = sg.client.mail.send.post(request_body=message.get())
    if not str(response.status_code).startswith('2'):
        raise ValueError(
            'sendgrid status_code: %s header: %s body: %s' %
            (response.status_code(), response.headers(), response.body()))
Esempio n. 11
0
def send_html_email_sendgrid(sender, to, subject, body, api_key):
    sg = sendgrid.SendGridAPIClient(apikey=api_key)
    to_email = sendgrid_email.Email(to)
    from_email = sendgrid_email.Email(sender)
    content = sendgrid_email.Content('text/html', body)
    message = sendgrid_email.Mail(from_email, subject, to_email, content)
    response = sg.client.mail.send.post(request_body=message.get())
    return response
Esempio n. 12
0
def send_email(app,
               template_name,
               to=None,
               to_name=None,
               sender=None,
               sender_name=None,
               cc_sender=True,
               subject=None,
               attachments=None,
               **kwargs):
    app_settings = EMAIL_APP_SETTINGS[app]
    template = app_settings['templates'][template_name]
    if sender:
        sender = mail.Email(sender, sender_name)
    from_ = mail.Email(app_settings['from_email'], sender_name
                       or app_settings['default_from_name'])
    to = mail.Email(to, to_name)
    # Forward name parameters to the template.
    kwargs['sender_name'] = sender_name or (sender.email
                                            if sender else 'anonymous')
    kwargs['to_name'] = to_name
    # Create the text and HTML bodies of the email.
    text = textwrap.dedent(template['text_body']) % kwargs
    html = app_settings['html'] % {
        'body': textwrap.dedent(template['html_body']) % kwargs,
    }
    # Construct the email and send it.
    message = mail.Mail()
    message.add_category(mail.Category(template_name))
    p = mail.Personalization()
    p.add_to(to)
    if sender:
        if cc_sender:
            p.add_cc(sender)
        message.reply_to = sender
    message.add_personalization(p)
    message.from_email = from_
    message.subject = subject or (template['subject'] % kwargs)
    message.add_content(mail.Content('text/plain', text))
    message.add_content(mail.Content('text/html', html))
    if attachments:
        # Attachments should be a list of tuples of (filename, data).
        for filename, data in attachments:
            a = mail.Attachment()
            mimetype, _ = mimetypes.guess_type(filename)
            a.filename = filename
            a.type = mimetype
            a.content = base64.b64encode(data)
            message.add_attachment(a)
    try:
        _sendgrid_api.client.mail.send.post(request_body=message.get())
    except Exception as e:
        logging.error('Failed to send email from %s to %s', from_.email,
                      to.email)
        logging.error('Sendgrid error: %r', e)
        logging.debug(json.dumps(message.get()))
        raise errors.ExternalError('Could not send email')
    logging.debug('Sent email from %s to %s', from_.email, to.email)
Esempio n. 13
0
def send_message(recipient, template_id, data: Optional[dict] = None) -> bool:
    """Sends a transactional email through SendGrid

    Templates are stored within SendGrid with a copy of the most recent version checked into
    version control within the root `email_templates` folder. You can define templates in either
    location, as long as you sync them up afterward (automated process for this is a WIP).

    Once you have a template, you will need to define its ID in your `.env` file.

    Then you can send it by passing recipient email, the template ID, and the dynamic data
    with which to populate the template (which data is required depends on the template).

    Returns a bool whether the email was successfully queued up by SendGrid or not.
    """
    api_key = settings.sendgrid_api_key
    sender = settings.mail_sender_address
    if not api_key or not sender:
        logger.error(
            f"Unable to send email due to missing API key <{api_key}> or sender <{sender}>."
        )
        return False
    if not template_id:
        logger.error(
            f"Template ID <{template_id}> not defined! Email has not been sent."
        )
        return False
    # Remap addresses
    if settings.debug:
        if not settings.mail_debug_recipient:
            logger.info(
                f"DEBUG: Transactional email <{template_id}> to <{recipient}> has not been sent. "
                f"Please add `MAIL_DEBUG_RECIPIENT` to your .env file if you wish to send email "
                f"while debugging."
            )
            return False
        new_recipient = settings.mail_debug_recipient
        logger.info(f"Replacing email recipient: <{recipient}>")
        recipient = new_recipient

    sendgrid_client = SendGridAPIClient(api_key=api_key)
    sender = sendgrid_helpers.Email(sender, name=settings.site_name)
    to_email = sendgrid_helpers.To(recipient)
    message = sendgrid_helpers.Mail(from_email=sender, to_emails=to_email)
    message.template_id = template_id
    if data:
        message.dynamic_template_data = data
    try:
        response = sendgrid_client.send(message)
        if response.status_code >= 400:
            logger.error(
                f"Mail delivery failed ({response.status_code}): {response.body}"
            )
            return False
        return True
    except Exception as e:
        logger.error(f"Failed to send email via SendGrid API: {e}")
        logger.error(f"Mail request: {message}")
        return False
Esempio n. 14
0
def send_email(to, subject, text):
    sg = sendgrid.SendGridAPIClient(apikey=app.config["SENDGRID_API_KEY"])
    to_email = mail.Email(to)
    from_email = mail.Email(app.config["SENDGRID_SENDER"])

    content = mail.Content('text/plain', text)
    message = mail.Mail(from_email, subject, to_email, content)

    sg.client.mail.send.post(request_body=message.get())
Esempio n. 15
0
    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 SendGrid.
        https://github.com/sendgrid/sendgrid-python

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

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

        Returns:
            None.

        Raises:
            EmailSendError: An error with sending email has occurred.
        """

        if not email_sender or not email_recipient:
            LOGGER.warn('Unable to send email: sender=%s, recipient=%s',
                        email_sender, email_recipient)
            raise util_errors.EmailSendError

        email = mail.Mail(
            mail.Email(email_sender),
            email_subject,
            mail.Email(email_recipient),
            mail.Content(content_type, email_content)
        )

        if attachment:
            email.add_attachment(attachment)

        try:
            response = self._execute_send(email)
        except (urllib2.URLError, urllib2.HTTPError) as e:
            LOGGER.error('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
Esempio n. 16
0
def send_email_from_sendgrid(subject, body, recipient, sender):
    # sendgrid email
    sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
    to_email = mail.Email(recipient)
    from_email = mail.Email(sender)
    content = mail.Content('text/plain', body)
    message = mail.Mail(from_email, subject, to_email, content)
    # TODO: uncomment below lines in production
    response = sg.client.mail.send.post(request_body=message.get())
    print(response)
Esempio n. 17
0
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('*****@*****.**', 'Hey from OK', 'hi',
                      cc=['*****@*****.**'], reply_to='*****@*****.**')
    """
    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('*****@*****.**', 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
Esempio n. 18
0
def newAsset(auuid, tag):
  skey = DS_CLIENT.key('sessions', auuid)
  entity = datastore.Entity(key=skey)
  entity['path'] = 'gs://{}/{}'.format(BUCKET_NAME, tag)
  DS_CLIENT.put(entity)

  subject = 'Acquisition Underway ({})'.format(tag)
  content = 'Image acquisition for {} has begun.'.format(tag)
  msg = mail.Mail(SENDER, RECIPIENT, subject, content)
  SG_CLIENT.send(msg)
  return 'ok'
Esempio n. 19
0
    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
Esempio n. 20
0
def finish(auuid):
  skey = DS_CLIENT.key('sessions', auuid)
  entity = DS_CLIENT.get(skey)
  asset = entity['path'].split('/')[3]
  DS_CLIENT.delete(skey)

  subject = 'Acquisition Complete ({})'.format(asset)
  content = 'Image acquisition complete: gs://{}/{}'.format(
          BUCKET_NAME, asset)
  msg = mail.Mail(SENDER, RECIPIENT, subject, content)
  SG_CLIENT.send(msg)
  return 'ok'
Esempio n. 21
0
    def run(self):
        import pickle
        import base64
        import os
        from sendgrid.helpers import mail
        from bs4 import BeautifulSoup

        newsletter = mail.Mail(
            from_email=newsletter_cfg().sender,
            to_emails=self.receiver,
            subject=f'Chess Newsletter - {self.player}',
        )

        imgs_loc = os.path.expanduser('~/Temp/luigi/graphs/')

        for file in os.listdir(imgs_loc):
            if file.endswith('.png') and self.player in file:
                with open(os.path.join(imgs_loc, file), 'rb') as f:
                    encoded_img = base64.b64encode(f.read()).decode('utf-8')

                attachment = mail.Attachment(
                    file_content=encoded_img,
                    file_name=file,
                    file_type='image/png',
                    disposition='inline',
                    content_id=file[:-4],
                )

                newsletter.add_attachment(attachment)

        message = [
            f'<html><body> Hi {self.player},<br><br>'
            f'This week you played chess! Here\'s your performance:'
        ]

        for inp in self.input():
            with inp.open('r') as f:
                text = pickle.load(f)
                message.append(text)

        message.append('Hope you do well this upcoming week!</body></html>')

        full_message = '<br>'.join(message)

        newsletter.add_content(full_message, 'text/html')

        # add plaintext MIME to make it less likely to be categorized as spam
        newsletter.add_content(
            BeautifulSoup(full_message, 'html.parser').get_text(),
            'text/plain')

        with self.output().open('w') as f:
            pickle.dump(newsletter, f, protocol=-1)
Esempio n. 22
0
 def send(self):
     m = mail.Mail()
     m.to = self.to
     m.from_email = self._from
     m.reply_to = self.replyto
     if self.cc:
         m.cc = self.cc
     m.subject = self.subject
     m.content = self.content
     if self.attachment:
         m.attachment = self.attachment
     s = sendgrid.SendGridAPIClient(api_key=settings.SENDGRID_API_KEY)
     response = s.send(m)
    def test_can_send_email_to_single_recipient(self):
        """Test can send email to single recipient."""

        email = mail.Mail()
        email_recipient='*****@*****.**'
        util = email_util.EmailUtil('fake_sendgrid_key')
        email = util._add_recipients(email, email_recipient)

        self.assertEquals(1, len(email.personalizations))

        added_recipients = email.personalizations[0].tos
        self.assertEquals(1, len(added_recipients))
        self.assertEquals('*****@*****.**', added_recipients[0].get('email'))
Esempio n. 24
0
    def send_email(self, new_user):
        sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
        from_email = mail.Email("*****@*****.**")
        subject = "New Baby Bet User"
        to_email = mail.Email("*****@*****.**")
        body = """There is a new user for Ianni Baby 2.0 Betting Service!

Name: {}
Email: {}""".format(new_user.name, new_user.email)

        content = mail.Content('text/plain', body)
        message = mail.Mail(from_email, subject, to_email, content)
        response = sg.client.mail.send.post(request_body=message.get())
Esempio n. 25
0
def send_simple_message(recipient):
    # [START sendgrid-send]

    sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)

    to_email = mail.Email(recipient)
    from_email = mail.Email(SENDGRID_SENDER)
    subject = 'This is a test email'
    content = mail.Content('text/plain', 'Example message.')
    message = mail.Mail(from_email, subject, to_email, content)

    response = sg.client.mail.send.post(request_body=message.get())

    return response
Esempio n. 26
0
def testemail(content):
    # print 'test'
    # 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
    # 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
    SENDGRID_API_KEY = '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'
    SENDGRID_SENDER = '*****@*****.**'
    sg = sendgrid.SendGridAPIClient(SENDGRID_API_KEY)
    to_email = mail.Email(content[0])
    from_email = mail.Email(SENDGRID_SENDER)
    subject = '蘋果日報 X 永明金融 一Click即知你要幾錢退休'
    emailcontent_txt = """
    多謝參加《蘋果日報 X 永明金融 一Click即知你要幾錢退休》並恭喜閣下獲得HABITŪ $50電子現金券(乙張)
    閣下可憑以下電子現金券到香港HABITŪ分店,即可享$50折扣優惠。
    https://campaign.nextdigital.com.hk/sunlife2019/qrcode/""" + content[
        1] + """
    HABITŪ顧客服務熱線:3550 0084
    HABITŪ分店地址:https://www.habitu.com.hk/locations
    「HABITŪ $50電子現金券」使用條款及細則:
    1.憑此電子現金券於 HABITŪ 任何分店消費可作港幣$50使用
    2.此電子現金券適用於食物,飲品及商品(不適用於支付租場活動及其所需費用)
    3.請於點菜時出示此電子現金券
    4.堂食設最低消費及需另收加一服務費
    5.此電子現金券不能兌換現金,餘額不設找贖或退款
    6.此電子現金券若違失或被盜將不設更換
    7.如有任何爭議,Next Digital Limited 及HABITŪ 保留最終決定權
    """
    emailcontent_html = """
    <html><head></head><body>
    <p>多謝參加《蘋果日報 X 永明金融 一Click即知你要幾錢退休》並恭喜閣下獲得HABITŪ $50電子現金券(乙張)</p>
    <p>閣下可憑以下電子現金券到香港HABITŪ分店,即可享$50折扣優惠。</p>
    <img style='width:100%; max-width:300px;' src='https://campaign.nextdigital.com.hk/sunlife2019/qrcode/""" + content[
        1] + """'>
    <p>HABITŪ顧客服務熱線:3550 0084</p>
    <p>HABITŪ分店地址:<a href='https://www.habitu.com.hk/locations' target='_blank'>https://www.habitu.com.hk/locations</a></p>
    <p><b>「HABITŪ $50電子現金券」使用條款及細則:</b></p>
    <p>1.憑此電子現金券於 HABITŪ 任何分店消費可作港幣$50使用</p>
    <p>2.此電子現金券適用於食物,飲品及商品(不適用於支付租場活動及其所需費用)</p>
    <p>3.請於點菜時出示此電子現金券</p>
    <p>4.堂食設最低消費及需另收加一服務費</p>
    <p>5.此電子現金券不能兌換現金,餘額不設找贖或退款</p>
    <p>6.此電子現金券若違失或被盜將不設更換</p>
    <p>7.如有任何爭議,Next Digital Limited 及HABITŪ 保留最終決定權</p>
    </body></html>
    """
    content_text = mail.Content('text/plain', emailcontent_txt)
    content_html = mail.Content('text/html', emailcontent_html)
    message = mail.Mail(from_email, subject, to_email, content_html)
    message.add_content(content_text)
    response = sg.client.mail.send.post(request_body=message.get())
    print "email sent to " + content[0]
Esempio n. 27
0
def send_simple_message(recipient):

    sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)

    to_email = mail.Email(recipient)
    from_email = mail.Email(SENDGRID_SENDER)
    subject = 'SpikeySales weekly lightning deal!'
    text = """Hurry up and grab the weekly lightning deal on Pedigree and other top dog feed brands."""
    content = mail.Content('text/plain', text)

    message = mail.Mail(from_email, subject, to_email, content)
    response = sg.client.mail.send.post(request_body=message.get())

    return response
Esempio n. 28
0
def send_message(sender,
                 recipients,
                 subject,
                 body_text,
                 body_html,
                 attachments=None,
                 ccs=None,
                 bccs=None,
                 categories=None,
                 send=True):
    mail = sgh.Mail()
    mail.from_email = sgh.Email(sender.email, sender.name)
    mail.subject = subject

    for recipient in recipients:
        personalization = sgh.Personalization()
        personalization.add_to(sgh.Email(recipient.email, recipient.name))

        if ccs:
            for cc in ccs:
                personalization.add_cc(sgh.Email(cc.email))
        if bccs:
            for bcc in bccs:
                personalization.add_bcc(sgh.Email(bcc.email))
        mail.add_personalization(personalization)

    mail.add_content(sgh.Content("text/plain", body_text))
    mail.add_content(sgh.Content("text/html", body_html))

    if attachments:
        for attach in attachments:
            attachment = sgh.Attachment()
            attachment.set_content(attach.content)
            attachment.set_type(attach.type)
            attachment.set_filename(attach.filename)
            attachment.set_disposition(attach.disposition)
            attachment.set_content_id(attach.content_id)
            mail.add_attachment(attachment)
    if categories:
        for category in categories:
            mail.add_category(sgh.Category(category))
    if send:
        if os.environ.get('REDIS_URL') is not None:
            send_email.delay(body=mail.get())
        else:
            import sendgrid
            sg_api = sendgrid.SendGridAPIClient(
                apikey=constants.SENDGRID_API_KEY)
            return sg_api.client.mail.send.post(request_body=mail.get())
Esempio n. 29
0
def sendmail(group_id, to_addr=None, plain_text=None, creole_text=None, html=None, subject=None, from_addr=None):
    config = current_app.config
    #
    # do sanity checks first
    #
    if not config.get('HAS_SENDMAIL', False):
        return msg.bug("Sendmail not active in config.")
    if group_id not in config.get("SENDGRID_UNSUBSCRIBE_GROUPS", {}):
        return msg.bug("Sendgrid unsubscribe group_id {} not found.".format(group_id))
    from_header = from_addr or config.get("SENDGRID_DEFAULT_FROM_ADDRESS", None)
    if not from_header:
        return msg.bug("missing 'from' address.")
    to_header = to_addr
    if not to_header:
        return msg.bug("missing 'to' address.")
    subject_header = subject or config.get("SENDGRID_DEFAULT_SUBJECT", None)
    if not from_header:
        return msg.bug("missing subject.")
    if plain_text:
        body = plain_text
        mimetype = "text/plain"
    if creole_text:
        body = parsing.creole2html(creole_text)
        mimetype = "text/html"
    if html:
        body = html
        mimetype = "text/html"
    if not body:
        return msg.bug("missing body contents (via 'creole_text' or 'html' parameters.")
    #
    # 
    #
    # email_id = uuid.uuid4()
    # message.set_headers({'X-Fondum-EmailID': str(email_id)});
    try:
        sg = sendgrid.SendGridAPIClient(apikey=config['SENDGRID_API_KEY'])
        message = h.Mail(
            h.Email(from_header),
            subject_header,
            h.Email(to_header),
            h.Content(mimetype, body)
        )
        message.asm = h.ASM(group_id)
        response = sg.client.mail.send.post(request_body=message.get())
    except sg_except.UnauthorizedError as e:
        return msg.bug("SENDGRID unauthorized error (check SENDGRID_API_KEY): {}".format(str(e)))
    except Exception as e:
        return msg.bug("SENDGRID general error: {}".format(str(e)))
    return msg.success("Message sent to {}".format(to_header))
    def test_can_send_email_to_single_recipient(self):
        """Test can send email to single recipient."""

        new_email = mail.Mail()
        email_recipient = '*****@*****.**'
        email_sender = '*****@*****.**'
        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('*****@*****.**', added_recipients[0].get('email'))