def send_forgot_password_email(self, name: str, email: str,
                                   new_password: str) -> bool:
        """
        Send email to a user containing their new system generated password
        """

        text_version = self.text_template.format(username=name,
                                                 password=new_password)
        html_version = flask.render_template(self.html_template,
                                             username=name,
                                             password=new_password)

        sg = sendgrid.SendGridAPIClient(apikey=self.api_key)

        from_email = Email(self.sender_email)
        to_email = Email(email)
        subject = self.email_subject
        content_text = Content("text/plain", text_version)
        send_new_password_email = Mail(from_email, subject, to_email,
                                       content_text)
        content_html = Content("text/html", html_version)
        send_new_password_email.add_content(content_html)

        try:
            email_response = sg.client.mail.send.post(
                request_body=send_new_password_email.get())
            logger.info("Sent forgot password email to {} with "
                        "response code : {}".format(
                            email, email_response.status_code))
            return True
        except http.client.IncompleteRead as e:
            logger.error("Sendgrid API Key may not be set correctly", e)
            return False
Ejemplo n.º 2
0
    def send_email(self,
                   to_email,
                   subject,
                   from_email=None,
                   html=None,
                   text=None,
                   *args,
                   **kwargs):  # noqa
        if not any([from_email, self.default_from]):
            raise ValueError("Missing from email and no default.")
        if not any([html, text]):
            raise ValueError("Missing html or text.")

        self.from_email = Email(from_email or self.default_from)
        self.subject = subject

        personalization = Personalization()

        if type(to_email) is list:
            for email in self._extract_emails(to_email):
                personalization.add_to(email)
        elif type(to_email) is Email:
            personalization.add_to(to_email)
        elif type(to_email) is str:
            personalization.add_to(Email(to_email))

        self.add_personalization(personalization)

        content = Content("text/html", html) if html else Content(
            "text/plain", text)
        self.add_content(content)

        return self.client.mail.send.post(request_body=self.get())
Ejemplo n.º 3
0
def send_mail(from_email,
              _to_email,
              subject,
              body,
              html=False,
              from_name="Gitcoin.co",
              cc_emails=None):
    """Send email via SendGrid."""
    # make sure this subscriber is saved
    if not settings.SENDGRID_API_KEY:
        print('No SendGrid API Key set. Not attempting to send email.')
        return
    to_email = _to_email
    get_or_save_email_subscriber(to_email, 'internal')

    # setup
    from_name = str(from_name)
    subject = str(subject)
    sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)
    from_email = Email(from_email, from_name)
    to_email = Email(to_email)
    contenttype = "text/plain" if not html else "text/html"

    # build content
    content = Content(contenttype, html) if html else Content(
        contenttype, body)
    if settings.IS_DEBUG_ENV:
        to_email = Email(
            settings.CONTACT_EMAIL
        )  # just to be double secret sure of what were doing in dev
        subject = _("[DEBUG] ") + subject
    mail = Mail(from_email, subject, to_email, content)
    response = None

    # build personalization
    if cc_emails:
        p = Personalization()
        p.add_to(to_email)
        for cc_addr in set(cc_emails):
            cc_addr = Email(cc_addr)
            if settings.IS_DEBUG_ENV:
                cc_addr = to_email
            if cc_addr._email != to_email._email:
                p.add_to(cc_addr)
        mail.add_personalization(p)

    # debug logs
    print(f"-- Sending Mail '{subject}' to {_to_email}")

    # send mails
    try:
        response = sg.client.mail.send.post(request_body=mail.get())
    except UnauthorizedError:
        print(
            f'-- Sendgrid Mail failure - Unauthorized - Check sendgrid credentials'
        )
    except HTTPError as e:
        print(f'-- Sendgrid Mail failure - {e}')

    return response
Ejemplo n.º 4
0
    def test_helloEmailAdditionalContent(self):
        """Tests bug found in Issue-451 with Content ordering causing a crash"""

        self.maxDiff = None
        """Minimum required to send an email"""
        mail = Mail()

        mail.from_email = Email("*****@*****.**")

        mail.subject = "Hello World from the SendGrid Python Library"

        personalization = Personalization()
        personalization.add_to(Email("*****@*****.**"))
        mail.add_personalization(personalization)

        mail.add_content(
            Content("text/html", "<html><body>some text here</body></html>"))
        mail.add_content(Content("text/plain", "some text here"))

        self.assertEqual(
            json.dumps(mail.get(), sort_keys=True),
            '{"content": [{"type": "text/plain", "value": "some text here"}, '
            '{"type": "text/html", '
            '"value": "<html><body>some text here</body></html>"}], '
            '"from": {"email": "*****@*****.**"}, "personalizations": '
            '[{"to": [{"email": "*****@*****.**"}]}], '
            '"subject": "Hello World from the SendGrid Python Library"}')

        self.assertTrue(isinstance(str(mail), str))
Ejemplo n.º 5
0
    def test_unicode_values_in_substitutions_helper(self):

        """ Test that the Substitutions helper accepts unicode values """

        self.maxDiff = None

        """Minimum required to send an email"""
        mail = Mail()

        mail.from_email = Email("*****@*****.**")

        mail.subject = "Testing unicode substitutions with the SendGrid Python Library"

        personalization = Personalization()
        personalization.add_to(Email("*****@*****.**"))
        personalization.add_substitution(Substitution("%city%", u"Αθήνα"))
        mail.add_personalization(personalization)

        mail.add_content(Content("text/plain", "some text here"))
        mail.add_content(
            Content(
                "text/html",
                "<html><body>some text here</body></html>"))

        expected_result = {
            "content": [
                {
                    "type": "text/plain",
                    "value": "some text here"
                },
                {
                    "type": "text/html",
                    "value": "<html><body>some text here</body></html>"
                }
            ],
            "from": {
                "email": "*****@*****.**"
            },
            "personalizations": [
                {
                    "substitutions": {
                        "%city%": u"Αθήνα"
                    },
                    "to": [
                        {
                            "email": "*****@*****.**"
                        }
                    ]
                }
            ],
            "subject": "Testing unicode substitutions with the SendGrid Python Library",
        }

        self.assertEqual(
            json.dumps(mail.get(), sort_keys=True),
            json.dumps(expected_result, sort_keys=True)
        )
Ejemplo n.º 6
0
def send_mail(api_key, subject, content, to=['*****@*****.**']):
    sg = sendgrid.SendGridAPIClient(apikey=api_key)

    mail = Mail(Email("*****@*****.**", "Open State Foundation"),
                subject, Email(to[0], to[0]))

    mail.add_content(Content("text/plain", content))
    mail.add_content(Content("text/html", content))

    sg.client.mail.send.post(request_body=mail.get())
Ejemplo n.º 7
0
    def _prepare_sendgrid_data(self):
        self.ensure_one()
        s_mail = Mail()
        s_mail.set_from(Email(self.email_from))
        if self.reply_to:
            s_mail.set_reply_to(Email(self.reply_to))
        s_mail.add_custom_arg(CustomArg('odoo_id', self.message_id))
        html = self.body_html or ' '

        p = re.compile(r'<.*?>')  # Remove HTML markers
        text_only = self.body_text or p.sub('', html.replace('<br/>', '\n'))

        s_mail.add_content(Content("text/plain", text_only))
        s_mail.add_content(Content("text/html", html))

        test_address = config.get('sendgrid_test_address')

        # We use only one personalization for transactional e-mail
        personalization = Personalization()
        personalization.set_subject(self.subject or ' ')
        addresses = list()
        if not test_address:
            if self.email_to and self.email_to not in addresses:
                personalization.add_to(Email(self.email_to))
                addresses.append(self.email_to)
            for recipient in self.recipient_ids:
                if recipient.email not in addresses:
                    personalization.add_to(Email(recipient.email))
                    addresses.append(recipient.email)
            if self.email_cc and self.email_cc not in addresses:
                personalization.add_cc(Email(self.email_cc))
        else:
            _logger.info('Sending email to test address {}'.format(
                test_address))
            personalization.add_to(Email(test_address))
            self.email_to = test_address

        if self.sendgrid_template_id:
            s_mail.set_template_id(self.sendgrid_template_id.remote_id)

        for substitution in self.substitution_ids:
            personalization.add_substitution(Substitution(
                substitution.key, substitution.value))

        s_mail.add_personalization(personalization)

        for attachment in self.attachment_ids:
            s_attachment = Attachment()
            # Datas are not encoded properly for sendgrid
            s_attachment.set_content(base64.b64encode(base64.b64decode(
                attachment.datas)))
            s_attachment.set_filename(attachment.name)
            s_mail.add_attachment(s_attachment)

        return s_mail.get()
Ejemplo n.º 8
0
    def _build_sg_mail(self, email):
        mail = Mail()
        mail.set_from(Email(email.from_email))
        mail.set_subject(email.subject)

        personalization = Personalization()
        for e in email.to:
            personalization.add_to(Email(e))
        for e in email.cc:
            personalization.add_cc(Email(e))
        for e in email.bcc:
            personalization.add_bcc(Email(e))
        personalization.set_subject(email.subject)
        mail.add_content(Content("text/plain", email.body))
        if isinstance(email, EmailMultiAlternatives):
            for alt in email.alternatives:
                if alt[1] == "text/html":
                    mail.add_content(Content(alt[1], alt[0]))
        elif email.content_subtype == "html":
            mail.contents = []
            mail.add_content(Content("text/plain", ' '))
            mail.add_content(Content("text/html", email.body))

        if hasattr(email, 'categories'):
            for c in email.categories:
                mail.add_category(Category(c))

        if hasattr(email, 'template_id'):
            mail.set_template_id(email.template_id)
            if hasattr(email, 'substitutions'):
                for k, v in email.substitutions.items():
                    personalization.add_substitution(Substitution(k, v))

        for k, v in email.extra_headers.items():
            mail.add_header({k: v})

        for attachment in email.attachments:
            if isinstance(attachment, MIMEBase):
                attach = Attachment()
                attach.set_filename(attachment.get_filename())
                attach.set_content(base64.b64encode(attachment.get_payload()))
                mail.add_attachment(attach)
            elif isinstance(attachment, tuple):
                attach = Attachment()
                attach.set_filename(attachment[0])
                base64_attachment = base64.b64encode(attachment[1])
                if sys.version_info >= (3, ):
                    attach.set_content(str(base64_attachment, 'utf-8'))
                else:
                    attach.set_content(base64_attachment)
                attach.set_type(attachment[2])
                mail.add_attachment(attach)

        mail.add_personalization(personalization)
        return mail.get()
Ejemplo n.º 9
0
def send_post2():
    from_email = Email("*****@*****.**")
    to_email = To("*****@*****.**")
    subject = "Sending with SendGrid is Fun"
    html_content = Content(MimeType.html, request.args["html_content"])
    plain_content = Content(MimeType.text, request.args["plain_content"])

    mail = Mail(from_email, to_email, subject, plain_content, html_content)

    sg = SendGridAPIClient(api_key='SENDGRID_API_KEY')
    response = sg.client.mail.send.post(request_body=mail.get())
Ejemplo n.º 10
0
    def send(self, notification):
        '''
        Accepts a notification and sends an email using included data.
        If SENDGRID_REPORTING_KEY and EMAIL_REPORT_SENDER are available
        in config, it uses Sendgrid to deliver the email. Otherwise, it
        uses plain SMTP through send_email()
        '''
        user = notification.user

        to = notification.email or user.email
        full_name = user.get_nice_name()
        first_name = user.first_name or user.get_nice_name()

        if (hasattr(config, "SENDGRID_REPORTING_KEY")
                and hasattr(config, "EMAIL_REPORT_SENDER")):
            from sendgrid.helpers.mail import (Email, Mail, Personalization,
                                               Content, Substitution)
            import sendgrid

            self.sg_instance = sendgrid.SendGridAPIClient(
                apikey=config.SENDGRID_REPORTING_KEY)

            mail = Mail()
            mail.from_email = Email(config.EMAIL_REPORT_SENDER,
                                    "Mist.io Reports")
            personalization = Personalization()
            personalization.add_to(Email(to, full_name))
            personalization.subject = notification.subject
            sub1 = Substitution("%name%", first_name)
            personalization.add_substitution(sub1)
            if "unsub_link" in notification:
                sub2 = Substitution("%nsub%", notification.unsub_link)
                personalization.add_substitution(sub2)
            mail.add_personalization(personalization)

            mail.add_content(Content("text/plain", notification.body))
            if "html_body" in notification:
                mail.add_content(Content("text/html", notification.html_body))

            mdict = mail.get()
            try:
                return self.sg_instance.client.mail.send.post(
                    request_body=mdict)
            except urllib2.URLError as exc:
                logging.error(exc)
                exit()
            except Exception as exc:
                logging.error(str(exc.status_code) + ' - ' + exc.reason)
                logging.error(exc.to_dict)
                exit()
        else:
            send_email(notification.subject,
                       notification.body, [to],
                       sender="config.EMAIL_REPORT_SENDER")
Ejemplo n.º 11
0
def send_real_email(
    subject, sender, sender_name, recipients, text_body, html_body
):
    sendgrid_client = SendGridAPIClient(
        api_key=os.environ.get("SENDGRID_API_KEY")
    )
    from_email = From(sender, sender_name)
    to_email = To(recipients)
    Content("text/plain", text_body)
    html_content = Content("text/html", html_body)
    em = Mail(from_email, to_email, subject, html_content)
    asyncio.run(send_email_sendgrid(em, sendgrid_client))
Ejemplo n.º 12
0
    def _make_sendgrid_mail(self, message):
        mail = Mail()
        if message.sender:
            mail.from_email = Email(message.sender)
        else:
            mail.from_email = Email(self.default_sender)

        if message.mail_options and message.mail_options.get('from_name'):
            mail.from_email.name = message.mail_options.get('from_name')

        template_id = getattr(message, 'template_id', None)
        if template_id:
            mail.template_id = template_id

        if message.subject:
            mail.subject = message.subject

        if message.recipients:
            if type(message.recipients) == list:
                personalization = Personalization()
                for recipient in message.recipients:
                    personalization.add_to(Email(recipient))

                dynamic_template_data = getattr(message,
                                                'dynamic_template_data', None)
                if dynamic_template_data:
                    personalization.dynamic_template_data = dynamic_template_data

                mail.add_personalization(personalization)
            else:
                raise Exception("unsupported type yet")
        if message.body:
            mail.add_content(Content("text/plain", message.body))

        if message.html:
            mail.add_content(Content("text/html", message.html))

        if message.reply_to:
            mail.reply_to = Email(message.reply_to)

        if message.attachments:
            for attachment in message.attachments:
                file_content = base64.b64encode(
                    attachment.data).decode('UTF-8')
                mail.add_attachment(
                    Attachment(
                        file_content=file_content,
                        file_name=attachment.filename,
                        file_type=attachment.content_type,
                        disposition=attachment.disposition,
                    ))

        return mail
Ejemplo n.º 13
0
def send_mail(from_email,
              _to_email,
              subject,
              body,
              html=False,
              from_name="Gitcoin.co",
              cc_emails=None,
              add_bcc=True):

    # make sure this subscriber is saved
    to_email = _to_email
    get_or_save_email_subscriber(to_email, 'internal')

    # setup
    sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)
    from_email = Email(from_email, from_name)
    to_email = Email(to_email)
    contenttype = "text/plain" if not html else "text/html"

    # build content
    content = Content(contenttype, html) if html else Content(
        contenttype, body)
    if settings.DEBUG:
        to_email = Email(
            settings.CONTACT_EMAIL
        )  #just to be double secret sure of what were doing in dev
        subject = "[DEBUG] " + subject
    mail = Mail(from_email, subject, to_email, content)

    # build personalization (BCC + CC)
    if add_bcc:
        p = Personalization()
        p.add_to(to_email)
        if cc_emails:  #only add CCif not in prod
            for cc_addr in set(cc_emails):
                cc_addr = Email(cc_addr)
                if settings.DEBUG:
                    cc_addr = to_email
                if cc_addr._email != to_email._email:
                    p.add_to(cc_addr)
        p.add_bcc(Email(settings.BCC_EMAIL))
        mail.add_personalization(p)

    # debug logs
    print("-- Sending Mail '{}' to {}".format(subject, _to_email))

    # send mails
    response = sg.client.mail.send.post(request_body=mail.get())
    return response
Ejemplo n.º 14
0
 def send_email(self, to_email, subject, content):
     from_email = Email('*****@*****.**')
     to_email = Email(to_email)
     content = Content('text/plain', content)
     email = Mail(from_email, subject, to_email, content)
     response = self.sg.client.mail.send.post(request_body=email.get())
     return response.status_code, response.body, response.headers
    def sendgrid_handler(self, queue_message, to_addrs_to_email_messages_map):
        self.logger.info(
            "Sending account:%s policy:%s %s:%s email:%s to %s" %
            (queue_message.get('account', ''), queue_message['policy']['name'],
             queue_message['policy']['resource'],
             str(len(queue_message['resources'])), queue_message['action'].get(
                 'template', 'default'), to_addrs_to_email_messages_map))

        from_email = Email(self.config['from_address'])
        subject = get_message_subject(queue_message)
        email_format = queue_message['action'].get('template_format', None)
        if not email_format:
            email_format = queue_message['action'].get(
                'template', 'default').endswith('html') and 'html' or 'plain'

        for email_to_addrs, email_content in six.iteritems(
                to_addrs_to_email_messages_map):
            for to_address in email_to_addrs:
                to_email = Email(to_address)
                content = Content("text/" + email_format, email_content)
                mail = Mail(from_email, subject, to_email, content)
                try:
                    self.sendgrid_client.client.mail.send.post(
                        request_body=mail.get())
                except (exceptions.UnauthorizedError,
                        exceptions.BadRequestsError) as e:
                    self.logger.warning(
                        "\n**Error \nPolicy:%s \nAccount:%s \nSending to:%s \n\nRequest body:"
                        "\n%s\n\nRequest headers:\n%s\n\n mailer.yml: %s" %
                        (queue_message['policy'],
                         queue_message.get('account', ''), email_to_addrs,
                         e.body, e.headers, self.config))
                    return False
        return True
Ejemplo n.º 16
0
 def __init__(self,
              movie_name,
              location,
              movie_id,
              keywords,
              emails,
              date_list=None):
     self.email_sender = sendgrid.SendGridAPIClient(
         apikey=os.environ.get('SENDGRID_API_KEY'))
     self.from_email = Email(os.environ.get('FROM_EMAIL'))
     self.base_url = "https://in.bookmyshow.com/buytickets"
     self.subject = "BMS Alert: Booking opened in a theatre"
     self.movie_name_with_location = movie_name + "-" + location
     self.movie_id = movie_id
     self.keywords = keywords
     self.emails = emails
     if not date_list:
         current_day = datetime.datetime.today()
         next_day = current_day + datetime.timedelta(days=1)
         date_list = [
             current_day.strftime("%Y%m%d"),
             next_day.strftime("%Y%m%d")
         ]
     self.date_list = date_list
     self.email_content = Content(type_='text/html',
                                  value=str(
                                      codecs.open("hall_opening_alerter/hall_opening_alerter.html", 'r').read()) \
                                  .replace('{movie}', self.movie_name_with_location) \
                                  .replace('{keywords}', str(self.keywords))
                                  .replace('{status}', 'Booking started'))
Ejemplo n.º 17
0
 def _prepare_message(self, message: EmailSchema) -> Mail:
     from_email = Email(message.from_email
                        or self.settings.DEFAULT_EMAIL_ADDRESS)
     to_email = To(message.to_email)
     subject = message.subject
     content = Content(message.content_type, message.content)
     return Mail(from_email, to_email, subject, content)
def send_email(email, name):
    from_email = Email("*****@*****.**")
    to_email = Email(email)
    subject = SUBJECT
    content = Content("text/plain", BODY.format(name))
    mail = Mail(from_email, subject, to_email, content)
    response = sg.client.mail.send.post(request_body=mail.get())
Ejemplo n.º 19
0
    def _create_email(self, email: dict, email_id: str) -> Mail:
        self.log_debug('converting email %s to sendgrid format', email_id)
        mail = Mail()
        personalization = Personalization()

        for i, to in enumerate(email.get('to', [])):
            personalization.add_to(Email(to))
            self.log_debug('added to %d to email %s', i, email_id)

        for i, cc in enumerate(email.get('cc', [])):
            personalization.add_cc(Email(cc))
            self.log_debug('added cc %d to email %s', i, email_id)

        for i, bcc in enumerate(email.get('bcc', [])):
            personalization.add_bcc(Email(bcc))
            self.log_debug('added bcc %d to email %s', i, email_id)

        mail.add_personalization(personalization)
        self.log_debug('added recipients to email %s', email_id)

        mail.subject = email.get('subject', '(no subject)')
        self.log_debug('added subject to email %s', email_id)

        mail.add_content(Content('text/html', email.get('body')))
        self.log_debug('added content to email %s', email_id)

        mail.from_email = Email(email.get('from'))
        self.log_debug('added from to email %s', email_id)

        for i, attachment in enumerate(email.get('attachments', [])):
            mail.add_attachment(self._create_attachment(attachment))
            self.log_debug('added attachment %d to email %s', i, email_id)

        self.log_debug('converted email %s to sendgrid format', email_id)
        return mail
Ejemplo n.º 20
0
def sendgrid_email(user, recipient, subject, body):
    sg = sendgrid.SendGridAPIClient(apikey=SendGridAPIKey)
    from_email = Email(user)
    to_email = Email(recipient)
    content = Content("text/plain", body)
    mail = Mail(from_email, subject, to_email, content)
    response = sg.client.mail.send.post(request_body=mail.get())
Ejemplo n.º 21
0
def send(to_email, subject, content):
    """
    Send an email.

    :param tuple to_email: email recipient address and name
    :param basestring subject: email subject
    :param basestring content: email content
    """
    if not get_secret('sendgrid_key'):
        # This is a test machine
        return

    try:
        if to_email[0].endswith('@gmail.com'):
            sg = sendgrid.SendGridAPIClient(apikey=get_secret('sendgrid_key'))
            content = Content('text/plain', content)
            mail = Mail(Email(*from_email), subject, Email(to_email[0]),
                        content)
            sg.client.mail.send.post(request_body=mail.get())
        else:
            conn = SMTP('127.0.0.1', 25)
            mail = Envelope(to_addr=to_email[0],
                            from_addr=from_email,
                            subject=subject,
                            text_body=content)
            conn.send(mail)
    except Exception:
        traceback.print_exc()
def sendTests(email, assignment, assignment_type, event_list):
    from_email = Email("*****@*****.**")
    subject = "{} {}s".format(assignment, assignment_type)
    to_email = Email(email)
    content = Content("text/html", "Good Luck!")
    mail = Mail(from_email, subject, to_email, content)
    user = User.query.filter_by(email=email).first()
    mail.personalizations[0].add_substitution(Substitution("-name-", user.firstname.capitalize()))
    mail.personalizations[0].add_substitution(Substitution("-assignment-", assignment))
    mail.personalizations[0].add_substitution(Substitution("-assignment_types-", assignment_type+'s'))
    eventNum = len(event_list)
    for c in range(eventNum):
        mail.personalizations[0].add_substitution(Substitution("-Event{}name-".format(c+1), event_list[c][0]))
        mail.personalizations[0].add_substitution(Substitution("-Event{}Link-".format(c+1), event_list[c][1]))
    if eventNum == 1:
        mail.template_id = "8238dc2b-2da6-4006-90c4-9129416f9bba"
    elif eventNum == 2:
        mail.template_id = "21ad7fc8-3183-4a77-8509-bb06973f763f"
    elif eventNum == 3:
        mail.template_id = "ad7f080f-bffd-4314-a2ed-da86971b0cfb"
    elif eventNum == 4:
        mail.template_id = "19df88b3-25ef-4a16-bf51-519169cf70ab"
    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    print(response.body)
    print(response.headers)
Ejemplo n.º 23
0
    def post(self):
        """Reset user password"""
        email = api.payload["email"]
        user = User.query.filter(User.email == email).first()
        if user is None:
            raise UserDoesNotExist
        if user.blocked:
            raise BlockedUser

        new_pass = generate_random_password(DEFAULT_RESET_PWD_LEN)
        user.password = new_pass
        db.session.merge(user)
        db.session.commit()

        sg = sendgrid.SendGridAPIClient(api_key=config.sendgrid.api_key())

        email = config.reset_pwd_email(default=DEFAULT_RESET_PWD_EMAIL)

        from_email = Email(email)
        to_email = To(user.email)

        subject = "BookBNB - Password Reset"
        content_body = f"Your password has been reset. Your new password is: {new_pass}"
        content = Content("text/plain", content_body)

        mail = Mail(from_email, to_email, subject, content)
        mail_json = mail.get()
        sg.client.mail.send.post(request_body=mail_json)
        return {"status": "success"}, 201
Ejemplo n.º 24
0
def send_email(to_email, subject, body, from_email=FROM_EMAIL, html=True):
    # newlines get wrapped in email, use html
    body = body.replace('\n', '<br>')

    # if local no emails
    if settings.LOCAL:
        print('local env - no email, only print send_email args:')
        print('to_email: {}'.format(to_email))
        print('subject: {}'.format(subject))
        print('body: {}'.format(body))
        print('from_email: {}'.format(from_email))
        print('html: {}'.format(html))
        print()
        return

    from_email = Email(from_email)

    to_email = ADMIN_EMAIL if to_email == ME else to_email
    to_email = Email(to_email)

    type_ = html and "text/html" or "text/plain"

    content = Content(type_, body)

    mail = Mail(from_email, subject, to_email, content)

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

    if str(response.status_code)[0] != '2':
        # TODO logging
        print('ERROR sending message, status_code {}'.format(
            response.status_code))

    return response
Ejemplo n.º 25
0
def sendMail(scheduled_time, url, price, name):
    sg = sendgrid.SendGridAPIClient(
        apikey=
        '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'
    )
    from_email = Email("*****@*****.**")
    subject = "This is a test email."
    to_email = Email("*****@*****.**")
    content = Content('text/html', 'text')
    mail = Mail(from_email, subject, to_email, content)

    dynamic_template_data = {
        'name': name,
        "price": price,
        "date": "Denver",
        "firstName": name,
        'url': url
    }
    unixtime = time.mktime(scheduled_time.timetuple())
    mail.send_at = unixtime
    mail.personalizations[0].dynamic_template_data = dynamic_template_data
    # mail.personalizations[0].add_to(Email("*****@*****.**"))
    # mail.personalizations[0].add_substitution(Substitution('event[i].name', 'eat pray love'))
    # mail.personalizations[0].add_substitution(Substitution('event[i].price', '80'))
    # mail.personalizations[0].add_substitution(Substitution('event[i].date', '2018-Dec-14'))
    # mail.personalizations[0].add_substitution(Substitution('event[i].url', 'https://www.eventbrite.com/e/eat-pray-love-tickets-52187209348'))
    # mail.personalizations[0].add_substitution(Substitution('firstName', 'Bikram'))
    mail.template_id = "d-c9c69c9a4d164310a1c5f3c289b9d93c"
    try:
        sg.client.mail.send.post(request_body=mail.get())
    except urllib.HTTPError as e:
        e.read()
        exit()
Ejemplo n.º 26
0
def send_email(receiver_email, user_lang):
    """Send user account validation."""
    _ = gettext.translation(
        'account_validation',
        '/code/locale',
        languages=[user_lang]
    ).gettext
    sender = os.getenv('SENDER_EMAIL')

    token = jwt.encode(
        {'email': receiver_email},
        os.getenv('JWT_SECRET'),
        algorithm='HS512'
    ).decode('utf-8')

    validate_message = _((
        'Hi! Please, click on this <a href="{url}/{token}">link</a> '
        'to validate your account.'
    )).format(
        url=os.getenv('ACCOUNT_VALIDATION_URL'),
        token=token
    )

    sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
    from_email = Email(sender)
    to_email = Email(receiver_email)
    subject = _("ROAp: account validation")
    content = Content("text/html", validate_message)
    mail = Mail(from_email, subject, to_email, content)
    sg.client.mail.send.post(request_body=mail.get())
Ejemplo n.º 27
0
    def post(self, request):
        email = request.data['username']
        user = User.objects.get(username=email)

        profile_id = user.profile.id
        profile = Profile.objects.get(id=profile_id)
        profile.password_reset_code = Profile.generate_password_reset_code()
        profile.save()
        url = 'https://bquest.ucladevx.com/password'
        if settings.DEBUG:
            url = 'http://*****:*****@bquest.ucladevx.com')
        to_email = Email(email)
        subject = 'BQuest User Password Reset'
        reset_link = "{}?code={}&userid={}".format(url,
                                                   profile.password_reset_code,
                                                   user.id)
        content = Content('text/html', 'N/A')
        mail = Mail(from_email, subject, to_email, content)
        mail.personalizations[0].add_substitution(
            Substitution('password_reset_link', reset_link))
        mail.template_id = PASSWORD_RESET_TEMPLATE

        sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)
        response = sg.client.mail.send.post(request_body=mail.get())
        if not (200 <= response.status_code < 300):
            raise ValidationError(
                {'sendgrid_status_code': response.status_code})
        return HttpResponse(status=200)
Ejemplo n.º 28
0
def create_ticket_message(ticket):
    event = ticket.article.event
    tmpl = loader.get_template('events/email/ticket_message.md')
    subject = 'Entrada para {}'.format(event.name)
    body = tmpl.render({
        'ticket': ticket,
        'article': ticket.article,
        'category': ticket.article.category,
        'event': event,
    })
    mail = Mail(from_email=Email(settings.CONTACT_EMAIL,
                                 settings.ASSOCIATION_NAME),
                subject=subject,
                to_email=Email(ticket.customer_email),
                content=Content('text/html', as_markdown(body)))

    attachment = Attachment()
    pdf_filename = ticket.as_pdf()
    with open(pdf_filename, 'rb') as f:
        data = f.read()
    attachment.content = base64.b64encode(data).decode()
    attachment.type = 'application/pdf'
    attachment.filename = 'ticket.pdf'
    attachment.disposition = 'attachment'
    mail.add_attachment(attachment)
    return mail
Ejemplo n.º 29
0
def send_api_mail(subject, to, body):
    sg = sendgrid.SendGridAPIClient(apikey=os.getenv('SENDGRID_API_KEY'))
    from_email = SGEmail('Grey Li <*****@*****.**>')
    to_email = SGEmail(to)
    content = Content("text/plain", body)
    email = SGMail(from_email, subject, to_email, content)
    sg.client.mail.send.post(request_body=email.get())
Ejemplo n.º 30
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('user.welcome'))
    form = RegisterForm()
    if form.validate_on_submit():
        if not form.validate_username(form.username):
            flash('Username has been registered, please choose another name.')
            return redirect(url_for('user.register'))
        if not form.validate_email(form.email):
            flash('Email has been registered, please choose another one.')
            return redirect(url_for('user.register'))
        register_user = User(name=str(form.username.data),
                             email=str(form.email.data),
                             contact=str(form.contactnumber.data),
                             address=str(form.homeaddress.data),
                             extra_info=str(form.extrainfo.data))
        register_user.set_password(form.password.data)
        db.session.add(register_user)
        db.session.commit()
        flash('Register Successfully!')
        # sending emails from verified email address
        sender = From('*****@*****.**')
        to = To(str(form.email.data))
        subject = "Welcome to Beauty Care!"
        content = Content('text/html', f'<b>Welcome! {form.username.data}</b>. <br> '
                                       f'<p>You have registered successfully in Beauty Health Care.</p>'
                                       f'<p>Looking forward to see you!</p>'
                                       f'<p>------</p>'
                                       f'<p>Best wishes,</p>'
                                       f'<p>Betty</p>')
        mail = Mail(from_email=sender, subject=subject, to_emails=to, html_content=content)
        thr = Thread(target=sg.client.mail.send.post, args=[mail.get()])
        thr.start()
        return redirect(url_for('user.register'))
    return render_template('register.html', form=form)