Beispiel #1
0
def send_mail(user, video_id_list):
    dist = user.email
    if not dist:
        return
    video_list = [Stream.objects.get(video_id=x) for x in video_id_list]
    tz = timezone.pytz.timezone(user.timezone)

    msg = Mail(
        From(settings.MAIL_ADDR),
        To(dist)
    )
    msg.dynamic_template_data = {
        "video_list": [{
            "video_id": x.video_id, "title": x.title, "thumb_url": x.thumb, "channel_id": x.channel_id,
            "channel_name": x.channel.title, "channel_thumb_url": x.channel.thumb}
            for x in video_list],
        "subject": f"{(video_list[0].start_at - timezone.now()).seconds // 60}分後に生放送が開始されます",
        "start_at": video_list[0].start_at.astimezone(tz).strftime("%m{0}%d{1} %H:%M").format(*"月日"),
        "remain_time_min": (video_list[0].start_at - timezone.now()).total_seconds() // 60,
        # "image": "http://youtube.dplab.biz" + static("images/YoutubeLiveSchedulerHeader.jpg"),
        # "unsubscribe": f"http://giftify.dplab.biz{reverse('account:unsubscribe_page')}?email={dist}&c={_condition_id}"
    }
    msg.template_id = "d-fd0b728c820b424dbe63e4154b47cc4b"
    try:
        sg = sendgrid.SendGridAPIClient(settings.SENDGRID_API)
        response = sg.send(msg.get())
    except Exception as e:
        logger.error(e)
        print(e)
        return None
    logger.debug(f"[NOTIFY] Sent a Mail to {user.email}")
    print(f"[NOTIFY] Sent a Mail to {user.email}")
    return dist
Beispiel #2
0
def send_email(recipients, subject, text_body, html_body, send_admin=False):
    message = Mail()
    msg_to = []
    for r in recipients:
        msg_to.append(To(r))
    message.to = msg_to

    if send_admin:
        admin_list = current_app.config['MAIL_ADMINS'].split(';')
        msg_bcc = []
        for a in admin_list:
            msg_bcc.append(Bcc(a))
        message.bcc = msg_bcc

    message.subject = Subject(subject)
    message.from_email = From(current_app.config['MAIL_FROM'],
                              'Indian Matrimonial')
    message.reply_to = ReplyTo(current_app.config['MAIL_REPLY_TO'],
                               'Indian Matrimonial')
    message.content = [
        Content('text/html', html_body),
        Content('text/txt', text_body)
    ]

    try:
        sg = SendGridAPIClient(current_app.config['SENDGRID_API_KEY'])
        response = sg.send(message)
        print(response.status_code),
        print(response.body)
        print(response.headers)
        return True
    except Exception as e:
        print(e)
        return False
Beispiel #3
0
def _send_password_reset_email(email, token):
    if settings.DEBUG:
        print("""********
Password reset requested for {}.
Here is your token:

\t{}

********""".format(email, token))
        return True

    import sendgrid
    from sendgrid.helpers.mail import Mail, From

    message = Mail(
        from_email=From('*****@*****.**', "SxSuri Messenger"),
        to_emails=email,
        subject="SxSuri Messenger password reset requested",
        html_content=RESET_TEMPLATE.format(email=email, token=token),
    )
    try:
        sg = sendgrid.SendGridAPIClient(settings.SENDGRID_API_KEY)
        ret = sg.send(message)
    except:
        return False
    return 200 <= ret.status_code < 300
def send_email(receiver_email, text_message, job_number, test=False):
    """Sends an e-mail from `[email protected] over SMTP protocol.
    
    Parameters:
     - `receiver_email` (dict {str:str}): keys are contact names and values are contact
     email addresses. This specifies the recipient(s) of the email.
     - `html_message` (str): text contained in the email.
     - `job_number` (str): user's job number.
     - `test`: if set to `True`, will short-circuits out of function without doing anything.
    
    """
    message = Mail(to_emails=[*receiver_email.values()],
                   subject=f"Upcoming Holdback Release: #{job_number}",
                   html_content=text_message)
    message.from_email = From('*****@*****.**', 'HBR-Bot Notifier')
    message.to_email = To([*receiver_email.values()])
    if test:
        return  # escape early
    try:
        with open(".secret.json") as f:
            api_key = json.load(f)["sendgrid_key"]
        sg = SendGridAPIClient(api_key)
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e.message)
Beispiel #5
0
def build_email(message):
    print("Iniciando envio de email para aviso")
    email_subject = Subject("SmartScale")
    email_address = To("*****@*****.**")
    from_email = From("*****@*****.**")
    email_content = "Olá, esta é uma mensagem automática da sua SmartScale\n\n\n" + message
    send_email(email_address, email_subject, email_content, from_email)
Beispiel #6
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)
Beispiel #7
0
def send_email_task_sendgrid(payload, headers, smtp_config):
    try:
        message = Mail(from_email=From(payload['from'], payload['fromname']),
                       to_emails=payload['to'],
                       subject=payload['subject'],
                       html_content=payload["html"])
        if payload['attachments'] is not None:
            for attachment in payload['attachments']:
                with open(attachment, 'rb') as f:
                    file_data = f.read()
                    f.close()
                encoded = base64.b64encode(file_data).decode()
                attachment = Attachment()
                attachment.file_content = FileContent(encoded)
                attachment.file_type = FileType('application/pdf')
                attachment.file_name = FileName(payload['to'])
                attachment.disposition = Disposition('attachment')
                message.add_attachment(attachment)
        sendgrid_client = SendGridAPIClient(get_settings()['sendgrid_key'])
        logging.info('Sending an email regarding {} on behalf of {}'.format(
            payload["subject"], payload["from"]))
        sendgrid_client.send(message)
        logging.info('Email sent successfully')
    except urllib.error.HTTPError as e:
        if e.code == 429:
            logging.warning("Sendgrid quota has exceeded")
            send_email_task_smtp.delay(payload=payload,
                                       headers=None,
                                       smtp_config=smtp_config)
        elif e.code == 554:
            empty_attachments_send(sendgrid_client, message)
        else:
            logging.exception(
                "The following error has occurred with sendgrid-{}".format(
                    str(e)))
Beispiel #8
0
def send_notification(user_email, day):
    template_id = None
    if day == 1:
        template_id = os.environ.get('SG_MEMBER_TEMPLATE_1_DAY')
    elif day == 7:
        template_id = os.environ.get('SG_MEMBER_TEMPLATE_7_DAY')
    elif day == 15:
        template_id = os.environ.get('SG_MEMBER_TEMPLATE_15_DAY')
    else:
        logging.exception('SendGrid message not found')
        return False
    
    message = Mail(
        from_email=From('*****@*****.**', 'OWASP'),
        to_emails=user_email,
        html_content='<strong>Email Removal</strong>')
    message.template_id = template_id
    
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        sg.send(message)
        return True
    except Exception as ex:
        template = "An exception of type {0} occurred while sending an email. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        logging.exception(message)
        return False
Beispiel #9
0
def send_email(to_email, subject, body, from_email=FROM_EMAIL, html=True):
    from_email = From(email=from_email, name=PYBITES)
    to_email = To(to_email)

    # if local no emails
    if settings.LOCAL:
        body = body.replace('<br>', '\n')
        print('local env - no email, only print send_email args:')
        print(f'to_email: {to_email.email}')
        print(f'subject: {subject}')
        print(f'body: {body}')
        print(f'from_email: {from_email.email}')
        print(f'html: {html}')
        print()
        return

    # newlines get wrapped in email, use html
    body = body.replace('\n', '<br>')
    message = Mail(from_email=from_email,
                   to_emails=to_email,
                   subject=subject,
                   plain_text_content=body if not html else None,
                   html_content=body if html else None)

    response = sg.send(message)

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

    return response
Beispiel #10
0
def create_message(today, job, template):
    from_email = From('*****@*****.**', 'junior.guru')
    to_email = To('*****@*****.**', job.company_name)  # TODO job.email
    subject = f'Jak se daří vašemu inzerátu? ({job.title})'

    starts_at = job.effective_approved_at
    ends_at = job.expires_at or (today + timedelta(days=30))
    content = template.render(
        title=job.title,
        company_name=job.company_name,
        url=f'https://junior.guru/jobs/{job.id}/',
        metrics=job.metrics,
        starts_at=starts_at,
        start_days=(today - starts_at).days,
        ends_at=ends_at,
        end_days=(ends_at - today).days,
        newsletter_at=job.newsletter_at,
        newsletter_url=
        'https://us3.campaign-archive.com/home/?u=7d3f89ef9b2ed953ddf4ff5f6&id=e231b1fb75'
    )

    return Mail(from_email=from_email,
                to_emails=to_email,
                subject=subject,
                html_content=content)
Beispiel #11
0
def send_email(request, pk):

    form = get_object_or_404(Form, pk=pk)

    re_captcha_is_valid = re_captcha(request, form.re_captcha)

    if not re_captcha_is_valid:
        return Response(status=status.HTTP_403_FORBIDDEN)

    reply_to = request.POST.get("_replyTo") or form.reply_to
    content = get_form_content(request.POST)

    message = Mail(
        from_email=From(settings.FROM_EMAIL, form.from_name),
        to_emails=To(form.to),
        subject=Subject(form.subject),
        html_content=content,
    )

    message.reply_to = ReplyTo(reply_to)

    if form.cc:
        message.cc = get_emails(form.cc)

    if form.bcc:
        message.bcc = get_emails(form.bcc)

    try:
        sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
        response = sg.send(message)
        return Response(status=status.HTTP_200_OK)
    except Exception as e:
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Beispiel #12
0
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)
Beispiel #13
0
def sendMailWithPdf(email):
    #mailMsg = '{
    #       "subject": "subject",
    #      "to": "*****@*****.**",
    #     "from": "*****@*****.**",
    #    "text": "Text",
    #   "html": "",
    #  "filename": "stats.xlsx",
    # "contentId": "stats"
    #}'
    #mailMsgJson = json.loads(mailMsg)
    message = Mail()
    message.to = To(email.data['to'])
    message.subject = Subject(email.data['subject'], p=0)
    message.from_email = From(email.data['from'], 'My Team Manager')

    message.template_id = TemplateId(email.data['templateId'])
    message.attachment = Attachment(FileContent(email.data['pdf']),
                                    FileName(email.data['filename']),
                                    FileType('application/pdf'),
                                    Disposition('attachment'),
                                    ContentId('Content ID 1'))
    message.content = Content(MimeType.text, email.data['text'])
    message.content = Content(MimeType.html, email.data['html'])
    sg = SendGridAPIClient(mailApiKey)
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
 def send_email(self, user_external_id: str, sender_email: str,
                sender_name: str, to_email: str, subject: str,
                plain_text_content: str,
                html_content: str) -> Tuple[EmailResult, str]:
     # https://github.com/sendgrid/sendgrid-python/blob/master/examples/helpers/mail_example.py#L16
     mail_params = {
         'from_email': From(sender_email, sender_name),
         'to_emails': to_email,
         'subject': Subject(subject),
     }
     if plain_text_content:
         mail_params['plain_text_content'] = PlainTextContent(
             plain_text_content)
     if html_content:
         mail_params['html_content'] = HtmlContent(html_content)
     message = Mail(**mail_params)
     response = self._get_sendgrid_client().send(message)
     if response and (response.status_code in [200, 202, 201]):
         external_id = response.headers['X-Message-Id']
         # External From, Subject etc are not Json Serializable
         mail_params['from_email'] = (sender_email, sender_name)
         mail_params['subject'] = subject
         if plain_text_content:
             mail_params['plain_text_content'] = plain_text_content
         if html_content:
             mail_params['html_content'] = html_content
         BaseEmail.create(mail_params, to_email, self.get_type(),
                          EmailResult.SENT, external_id, user_external_id)
         return EmailResult.SENT, external_id
     return EmailResult.FAILED, None
    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_address = self.config.get('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, message in six.iteritems(to_addrs_to_email_messages_map):
            for to_address in email_to_addrs:
                if email_format == "html":
                    mail = Mail(
                        from_email=From(from_address),
                        to_emails=To(to_address),
                        subject=subject,
                        html_content=message.as_string())
                else:
                    mail = Mail(
                        from_email=From(from_address),
                        to_emails=To(to_address),
                        subject=subject,
                        plain_text_content=message.as_string())
                try:
                    self.sendgrid_client.send(mail)
                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
Beispiel #16
0
def send(recipients: Union[Tuple[Tuple[str, str]], Tuple[str, str]],
         subject: str, body_html: Optional[str], body_text: str) -> bool:
    """Send an email from the configured address.
    `recipients` is a list of tuples like `[(address, name),...]` or just a single
    tuple like `(address, name)`.
    Does not check for address validity.
    If `body_text` is None, it will be derived from `body_html`.
    if `body_html` is None but `body_text` is provided, no HTML part will be sent.
    Returns True on success, false otherwise. Does not throw exception.
    """

    if config.DEMO:
        # Emails to users are disabled to prevent abuse.
        return True

    if not recipients:
        return True

    if isinstance(recipients[0], str):
        # We were passed just `(address, name)`.s
        recipients = [recipients]

    if not body_text and not body_html:
        raise Exception(
            'emailer.send: body_text or body_html must be provided')
    elif body_html and not body_text:
        h2t = html2text.HTML2Text()
        h2t.body_width = 0
        body_text = h2t.handle(body_html)

    sg = SendGridAPIClient(api_key=config.SENDGRID_API_KEY)

    to = []
    for r in recipients:
        to.append(To(r[0], r[1]))

    message = Mail(from_email=From(config.MASTER_EMAIL_SEND_ADDRESS,
                                   name=config.MASTER_EMAIL_SEND_NAME),
                   to_emails=to,
                   subject=Subject(subject),
                   plain_text_content=PlainTextContent(body_text),
                   html_content=HtmlContent(body_html) if body_html else None)

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

    if response.status_code not in (200, 202):
        # The expected response code is actually 202, but not checking for 200 as well feels weird.
        logging.error(
            f"emailer.send fail: {response.status_code} | {response.body} | {response.headers}"
        )
        return False

    # Body is expected to be empty on success, but we'll check it anyway.
    logging.info(
        f"emailer.send success: {response.status_code} | {response.body}")
    return True
Beispiel #17
0
def queue_partner_emails():
    try:
        users = db_session.query(Users).filter(
            Users.wants_emails == True).all()
        for user in users:
            print("Sending email to {}...".format(user.email))
            partner = get_next_partner(user.uuid)
            if not partner:
                print("Reseting prayers for {}!".format(user.email))
                db_session.query(Prayers).filter(
                    Prayers.user_id == str(user.uuid)).filter(
                        Prayers.partner_id != None).delete(
                            synchronize_session=False)
                db_session.commit()
                partner = get_next_partner(user.uuid)
            message = Mail(from_email=From('*****@*****.**',
                                           '3ABC Prayer Reminders'),
                           to_emails=user.email)

            message.dynamic_template_data = {
                'user_name':
                user.name,
                'email':
                partner.email,
                'name':
                partner.name,
                'type':
                partner.type,
                'image':
                partner.image_url if partner.image_url is not None else None,
                'description':
                partner.description
                if partner.description is not None else None,
                'location':
                partner.location if partner.location is not None else None,
            }
            message.template_id = 'd-5f8116bd407849d5a06e66d586354bdb'

            sg = SendGridAPIClient(
                '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'
            )
            response = sg.send(message)
            print(response.status_code)

            new_prayer = Prayers(member_id=None,
                                 partner_id=partner.ccbid,
                                 user_id=user.uuid)
            db_session.add(new_prayer)
            db_session.commit()
        return 200
    except Exception as e:
        print('Failed sending partner emails')
        print(e)
        return 500
    finally:
        db_session.close()
Beispiel #18
0
    def send_email(self):

        # send email using the self.cleaned_data dictionary
        first_name = self.cleaned_data.get("fname")
        last_name = self.cleaned_data.get("lname")
        email = self.cleaned_data.get("email")
        phone = self.cleaned_data.get("phone")
        message = self.cleaned_data.get("message")

        # Issue response to client via sendgrid API
        sendgrid_client = SendGridAPIClient(config('SENDGRID_API_KEY'))
        mail = Mail()
        mail.from_email = From(config('EMAIL_FROM'))
        mail.to_email = To(email)
        mail.subject = "Your Enquiry with Mayan Web Studio"
        mail.template_id = config('SENDGRID_TEMPLATE_ID')
        p = Personalization()
        p.add_to(To(email))
        p.dynamic_template_data = {
            "firstName": first_name,
            "lastName": last_name,
            "phone": phone
        }
        mail.add_personalization(p)

        response = sendgrid_client.client.mail.send.post(
            request_body=mail.get())
        print(response.status_code)
        print(response.body)
        print(response.headers)

        # Send notification email to Mayan
        subject, from_email, to = 'New Enquiry for Mayan Web Studio', config(
            'EMAIL_FROM'), '*****@*****.**'
        text_content = 'This is an important message.'
        html_content = '''
        <h3>New Enquiry from</h3>
        <ul>
        <li>First Name: $(first_name)</li>
        <li>Last Name: $(last_name)</li>
        <li>Email: $(email)</li>
        <li>Phone: $(phone)</li>
        <li>Message: $(message)</li>
        </ul>
        '''

        html_content = html_content.replace("$(first_name)", first_name)
        html_content = html_content.replace("$(last_name)", last_name)
        html_content = html_content.replace("$(email)", email)
        html_content = html_content.replace("$(phone)", phone)
        html_content = html_content.replace("$(message)", message)

        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
Beispiel #19
0
def send_email(logger, subject, msg, to=None):
    if not to:
        to = cfg.email_admin
    from_email = From(cfg.email_from, cfg.email_from_name)
    message = Mail(from_email=from_email, to_emails=to, subject=subject, html_content=msg)
    try:
        import flask_config_secret
        sg = SendGridAPIClient(flask_config_secret.MAIL_SENDGRID_API_KEY)
        response = sg.send(message)
    except Exception as ex:
        logger.error(f"email '{subject}': {ex}")
Beispiel #20
0
def index(request):
    sendgrid_client = SendGridAPIClient(api_key=SENDGRID_API_KEY)
    from_email = From(TICO_CHURCH_EMAIL)
    to_email = To(TICO_DEV_GMAIL)
    subject = 'Check Out This SendGrid Magic!'
    plain_text_content = PlainTextContent('How dope is this?')
    html_content = HtmlContent('<strong>It is SO dope!</strong>')
    message = Mail(from_email, to_email, subject, plain_text_content,
                   html_content)
    response = sendgrid_client.send(message=message)

    return HttpResponse('Email Sent!')
Beispiel #21
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))
    def test_error_is_not_raised_on_to_emails_set_to_a_tuple(self):
        from sendgrid.helpers.mail import (PlainTextContent, HtmlContent)
        self.maxDiff = None
        to_emails = ('*****@*****.**', 'Example To Name 0')

        Mail(from_email=From('*****@*****.**', 'Example From Name'),
             to_emails=to_emails,
             subject=Subject('Sending with SendGrid is Fun'),
             plain_text_content=PlainTextContent(
                 'and easy to do anywhere, even with Python'),
             html_content=HtmlContent(
                 '<strong>and easy to do anywhere, even with Python</strong>'))
def send_zoominfo_email(member_email, zoom_email):
    hcontent = f"You have been assigned to <strong>{zoom_email}&#64;owasp.org</strong><br>You should receive a separate email with the password for this account. Because this is a shared account, please coordinate with other members on the account, do not change account details, and do not change the account password.<br><br>Thank you,<br>OWASP Foundation"
    message = Mail(from_email=From('*****@*****.**', 'OWASP'),
                   to_emails=member_email,
                   html_content=hcontent,
                   subject="Your Zoom Account")

    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        sg.send(message)
    except Exception as e:
        logging.warn(
            f"Failed to send mail to {member_email}.  Result: {str(e)}")
Beispiel #24
0
def sendmail(request):
    sendgrid_client = SendGridAPIClient(
        api_key=environ.get('SENDGRID_API_KEY'))
    from_email = From(environ.get('ADMIN_EMAIL'))
    to_email = To(environ.get('ADMIN_EMAIL'))
    subject = request.POST['fname'] + ' ' + \
        request.POST['lname'] + ' - phone num: ' + request.POST['phone']
    plain_text_content = PlainTextContent(request.POST['message'])
    message = Mail(from_email, to_email, subject, plain_text_content)
    response = sendgrid_client.send(message=message)
    print(response)

    return render(request, 'pages/contact_form.html', {'email_sent': True})
def send_zoompw_email(leader_emails, zoom_pw):
    hcontent = f"To access your shared zoom account, use <strong>{zoom_pw}</strong><br>You should receive a separate email with the account login for this account. Because this is a shared account, please coordinate with other members on the account, do not change account details, and do not change the account username.<br><br>Thank you,<br>OWASP Foundation"

    message = Mail(from_email=From('*****@*****.**', 'OWASP'),
                   to_emails=leader_emails,
                   html_content=hcontent,
                   subject="Your Zoom Account")

    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        sg.send(message)
    except Exception as e:
        logging.warn(
            f"Failed to send mail to {leader_emails}.  Result: {str(e)}")
    def test_send_a_single_email_to_multiple_recipients(self):
        from sendgrid.helpers.mail import (Mail, From, To, Subject,
                                           PlainTextContent, HtmlContent)
        self.maxDiff = None
        to_emails = [
            To('*****@*****.**', 'Example To Name 0'),
            To('*****@*****.**', 'Example To Name 1')
        ]
        message = Mail(
            from_email=From('*****@*****.**', 'Example From Name'),
            to_emails=to_emails,
            subject=Subject('Sending with SendGrid is Fun'),
            plain_text_content=PlainTextContent(
                'and easy to do anywhere, even with Python'),
            html_content=HtmlContent(
                '<strong>and easy to do anywhere, even with Python</strong>'))

        self.assertEqual(
            message.get(),
            json.loads(r'''{
                "content": [
                    {
                        "type": "text/plain",
                        "value": "and easy to do anywhere, even with Python"
                    },
                    {
                        "type": "text/html",
                        "value": "<strong>and easy to do anywhere, even with Python</strong>"
                    }
                ],
                "from": {
                    "email": "*****@*****.**",
                    "name": "Example From Name"
                },
                "personalizations": [
                    {
                        "to": [
                            {
                                "email": "*****@*****.**",
                                "name": "Example To Name 0"
                            },
                            {
                                "email": "*****@*****.**",
                                "name": "Example To Name 1"
                            }
                        ]
                    }
                ],
                "subject": "Sending with SendGrid is Fun"
            }'''))
    def send_sendgrid_email(self, dotenv_path, email, selected_cluster,
                            ca_cert, server_ip):
        """
        If the admin has sendgrid API credentials, then they can use this function to send email
        :param dotenv_path: path of sendgrid.env file
        :param email: email of the receiver
        :param selected_cluster: the name of cluster that we want to send the info of
        :param ca_cert: ca_cert of the cluster
        :param server_ip: ip of the cluster
        :return:
        """

        self.log.info("Sending email using sendgrid!")
        try:
            from dotenv import load_dotenv
            from sendgrid import SendGridAPIClient, SendGridException
            from sendgrid.helpers.mail import Mail, To, From

            # Load Sendgrid API key
            load_dotenv(dotenv_path)

            # Create an email message.
            # The 'from_email' is currently hardcoded. It will have to be changed later.
            message = Mail(
                from_email=From('*****@*****.**'),
                to_emails=To(email),
                subject='Credentials for cluster: ' + selected_cluster,
                html_content='<strong>Cluster name: </strong>' +
                selected_cluster + '<br><br><strong>CA Cert: </strong>' +
                ca_cert + '<br><br><strong>Server IP: </strong>' + server_ip)

            # Send the email to the user.
            sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
            response = sg.send(message)
            self.log.info("Successfully sent email using sendgrid!")
        except ImportError as e:
            # Handle import exceptions
            error = 'Cannot send email.'
            self.log.info(str(e))
            self.send({'msgtype': 'added-user-unsuccessfully', 'error': error})
        except SendGridException as e:
            # Handle sendgrid exceptions
            error = 'Cannot send email.'
            self.log.info(str(e))
            self.send({'msgtype': 'added-user-unsuccessfully', 'error': error})
        except Exception as e:
            error = 'Cannot send email.'
            self.log.info(str(e))
            self.send({'msgtype': 'added-user-unsuccessfully', 'error': error})
Beispiel #28
0
def queue_emails():
    try:
        users = db_session.query(Users).filter(
            Users.wants_emails == True).all()
        for user in users:
            print("Sending email to {}...".format(user.email))
            member = get_next_member(user.uuid)
            if not member:
                print("Reseting prayers for {}!".format(user.email))
                db_session.query(Prayers).filter(
                    Prayers.user_id == str(user.uuid)).filter(
                        Prayers.member_id != None).delete(
                            synchronize_session=False)
                db_session.commit()
                member = get_next_member(user.uuid)
            message = Mail(from_email=From('*****@*****.**',
                                           '3ABC Prayer Reminders'),
                           to_emails=user.email)

            member_since = member.member_since.strftime('%B %Y')
            message.dynamic_template_data = {
                'email': member.email,
                'name': member.name,
                'member_since': member_since,
                'image':
                member.image_url if member.image_url is not None else None,
                'username':
                user.name if user.name is not None else user.username
            }
            message.template_id = 'd-0a35a380ad214eb0b6152ddaa961f420'

            sg = SendGridAPIClient(
                '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'
            )
            response = sg.send(message)
            print(response.status_code)

            new_prayer = Prayers(member_id=member.ccbid,
                                 partner_id=None,
                                 user_id=user.uuid)
            db_session.add(new_prayer)
            db_session.commit()
        return 200
    except Exception as e:
        print('Failed sending all emails')
        print(e)
        return 500
    finally:
        db_session.close()
Beispiel #29
0
def send_mail(from_mail: str, to_mail: str, subject: str, content: str, cc: List[str] = None) -> object:
    sg = sendgrid.SendGridAPIClient(config.SENDGRID_KEY)

    mail = Mail()
    mail.from_email = From(from_mail, "UCC Netsoc")
    mail. subject = subject
    mail.content = Content("text/plain", content)

    p = sendgrid.Personalization()
    p.add_to(To(to_mail))
    if cc:
        for email in cc:
            p.add_cc(Email(email))
    mail.add_personalization(p)
    return sg.send(mail)
def send_subscription_management_email(member_email, customer_token):
    params = {'token': customer_token}
    message_link = 'https://owasp.org/manage-membership?' + urllib.parse.urlencode(
        params)

    message = Mail(from_email=From('*****@*****.**', 'OWASP'),
                   to_emails=member_email,
                   html_content='<strong>Manage Billing</strong>')
    message.dynamic_template_data = {'manage_link': message_link}
    message.template_id = 'd-8d6003cb7bae478492ec9626b9e31199'
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        sg.send(message)
    except Exception as e:
        logging.info(str(e))