コード例 #1
0
def send_kitchen_sink():
    # Assumes you set your environment variable:
    # https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key
    message = build_kitchen_sink()
    sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sendgrid_client.send(message=message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
コード例 #2
0
ファイル: messages.py プロジェクト: shlomiLan/tvsort_sl
def send_email(subject, content):
    sendgrid_client = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
    message = Mail(
        from_email='*****@*****.**',
        to_emails='*****@*****.**',
        subject=subject,
        plain_text_content=content,
    )
    sand_box = os.environ.get('SAND_BOX')

    if sand_box == 'true':
        mail_settings = MailSettings()
        mail_settings.sandbox_mode = SandBoxMode(True)
        message.mail_settings = mail_settings

    return sendgrid_client.send(message)
コード例 #3
0
def send_report(to_email_address, file_with_path, file_name, msg_subject,
                msg_content):
    """
    Sends a report/file to an email address

    Parameters
    ----------
    to_email_address : string
        email address to send the file

    file_with_path : string
        entire path including file, used to load report output

    file_name : string
        name of the file, used to name the file as it is attached to the email

    msg_subject : string
        subject fo the message to be sent

    msg_content : string
        content to be included in the message
    """

    message = Mail(from_email=Email(reports_from_email, reports_from_name),
                   to_emails=to_email_address,
                   subject=msg_subject,
                   html_content=msg_content)

    with open(file_with_path, 'rb') as f:
        data = f.read()
        f.close()

    encoded_file = base64.b64encode(data).decode()

    message.attachment = Attachment(FileContent(encoded_file),
                                    FileName(file_name),
                                    FileType('application/pdf'),
                                    Disposition('attachment'))

    sg = SendGridAPIClient(sendgrid_api_key)
    response = sg.send(message)
    if (response.status_code >= 200 and response.status_code < 300):
        print("success sending: " + file_with_path + " to " +
              to_email_address + " ok")
    else:
        print("could not send email")
        print(response.status_code, response.body, response.headers)
コード例 #4
0
def tea_send_email(request):
    """HTTP Cloud Function.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.

    """
    request_json = request.get_json(silent=True)
    request_args = request.args

    try:
        # This is from Google documentation
        # Think this is obsolete because we get the following error:
        # module 'sendgrid' has no attribute 'SendGridClient'; think its call SendGridAPIClient now
        #
        # sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        # message = sendgrid.Mail()
        # message.add_to("*****@*****.**")
        #
        # In addition, got this error: 'Mail' object has no attribute 'set_from'
        #
        # message.set_from("*****@*****.**")
        # message.set_subject("Sending with SendGrid is Fun")
        # message.set_html("and easy to do anywhere, even with Python")
        # sg.send(message)

        # Sample from SendGrid website
        # https://app.sendgrid.com/guide/integrate/langs/python
        message = Mail(
            from_email='*****@*****.**',
            to_emails='*****@*****.**',
            subject='Sending with Twilio SendGrid is Fun',
            html_content=
            '<strong>and easy to do anywhere, even with Python</strong>')

        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)

    except Exception as e:
        logging.error(e)
コード例 #5
0
def emergency(username, therapist):
    """sends email to final emergency contact and therapist"""

    if "username" not in session or username != session["username"]:
        raise Unauthorized()

    user = User.query.get(username)
    therapist = Therapist.query.get(therapist)

    to_emails = [(user.emergency_contact_email, 'Emergency Contact'),
                 (therapist.email, 'Therapist')]

    print("*******EMERGENCY*******")
    message = Mail(
        from_email='*****@*****.**',
        to_emails=to_emails,
        is_multiple=True,
        subject=
        f'Mental Health Net has an Emergency Case: {user.full_name} is having a crisis.',
        html_content=
        f'<strong>Hello,<br> We have been notified by  {user.full_name} that they are having a crisis.<br> Our Team Has been notified and are working on the case'
    )
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e.body)

    #####################################################
    #             Twilio SMS notification               #
    #####################################################

    account_sid = os.getenv('TWILIO_ACCOUNT_SID')

    auth_token = os.getenv('TWILIO_AUTH_TOKEN')

    client = Client(account_sid, auth_token)

    message = client.messages.create(body="Client Crisis.",
                                     from_='+18722505272',
                                     to='+17609043999')

    flash("Emergency SMS and Email Have been sent, Hang in there!")
    return redirect(f"/users/{username}")
コード例 #6
0
def email_transaction():
    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute('SELECT email FROM user WHERE id=%s', (session['id'], ))
    em = cursor.fetchone()
    cursor.execute(
        'SELECT ex_id,amount,category,date,description FROM expense_a WHERE id =%s AND monthname(date)=%s ',
        (
            session['id'],
            session['s_m'],
        ))
    result = cursor.fetchall()
    df = pd.DataFrame(result)
    df_update = df.rename(
        columns={
            'ex_id': 'EX_ID',
            'amount': 'Amount',
            'category': 'Category',
            'date': 'Date',
            'description': 'Description'
        })
    #header=['EX_ID','Amount','Category','Date','Description']
    df_update.to_csv(r'transaction.csv', index=False)

    with open('transaction.csv', 'rb') as f:
        data = f.read()
        f.close()
    message = Mail(
        from_email='*****@*****.**',
        to_emails=em['email'],
        subject='Transaction Report For The Month Of' + '-' + session['s_m'],
        html_content=
        'Below you will find attached a detailed copy of your transactions for the month of'
        + ' ' + session['s_m'])

    encoded_file = base64.b64encode(data).decode()

    attachedFile = Attachment(
        FileContent(encoded_file),
        FileName('transaction' + '_' + session['s_m'] + '.csv'),
        FileType('transaction/csv'), Disposition('attachment'))
    message.attachment = attachedFile

    sg = SendGridAPIClient(SENDGRID_API_KEY)
    response = sg.send(message)
    print(response.status_code, response.body, response.headers)
    flash(u"E-mail has been sent", "success")
    return redirect(url_for('dashboard'))
コード例 #7
0
def send_email(name, dest, link):
    email_html = open('templates/email.html')
    email_body = email_html.read().format(name=name, link=link)
    
    message = Mail(
        from_email=credentials.Email,
        to_emails=dest,
        subject='HELP!!! HELP!!! HELP!!!',
        html_content=email_body)
    try:
        sg = SendGridAPIClient(credentials.SENDGRID_API_KEY)
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        pass
コード例 #8
0
ファイル: scrapsec.py プロジェクト: bbhunter/scrapsec
def sendEmail(receiver, code):
	content = "<h1>Change Detected at " + code + "</h1><br><h3><a href=\"https://bugcrowd.com/" +code+ "\">Visit the program</a></h3>"
	message = Mail(
		from_email='*****@*****.**',
		to_emails= receiver,
		subject='Change Detected !',
		html_content=content
	)	   
	try:
		sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
		response = sg.send(message)
		print(response.status_code)
		print(response.body)
		print(response.headers)
	except Exception as e:
		print(e)
		return
コード例 #9
0
def sendmail(sender, to, subject, message_text):
    import os
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail

    message = Mail(from_email=sender,
                   to_emails=to,
                   subject=subject,
                   html_content='<strong>{}</strong>'.format(message_text))
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e.message)
コード例 #10
0
def email_results(apartment_map):
  print('Sending email!')
  from_email = environ.get('SENDGRID_USERNAME')
  api_key = environ.get('SENDGRID_API_KEY')
  html_content, available_apartments = generate_html(apartment_map)

  for email in RECIPIENT_EMAILS:
    message = Mail(
      from_email=from_email,
      to_emails=email,
      subject='Found {} available apartments!'.format(available_apartments),
      html_content=html_content)
    try:
        sg = SendGridAPIClient(api_key)
        response = sg.send(message)
    except Exception as e:
        print(str(e))
コード例 #11
0
def mailSender(emailsList):
    message = Mail(
        from_email='EMAIL ADDRESS',
        to_emails=emailsList,
        subject=
        "[ROS] Invitation to research survey on architecting ROS-based systems",
        html_content=
        "<pre style=\"font-family: sans-serif;\" >Hi,<br /><br />I am a researcher of the Vrije Universiteit Amsterdam and we are doing a study on the architecture of ROS-based systems.<br />I am contacting you because you appear as one of the contributors of this GitHub repo: <a href='https://www.github.com/[-project-]'>https://www.github.com/[-project-]</a><br /><br />Do you have some spare time for filling out the short survey linked below?<br /><br />The on-line survey is available here: <a href='https://goo.gl/forms/xLhtaFIcCzZEwHSG3'>https://goo.gl/forms/xLhtaFIcCzZEwHSG3</a><br /><br />Filling the survey will take no more than 10-15 minutes to complete. This research is carried out jointly by the Vrije Universiteit Amsterdam (The Netherlands), the Carnegie Mellon Software Engineering Institute (USA) and the Institute for Software Research at Carnegie Mellon University (USA) and we are aiming at building a set of guidelines for architecting ROS-based systems. I hope you will find our work useful.<br /><br />Thanks in advance for your help!<br /><br />   Ivano<br /><br />:::<br />Ivano Malavolta | Assistant professor | Vrije Universiteit Amsterdam, The Netherlands | <a href='http://www.ivanomalavolta.com'>http://www.ivanomalavolta.com</a><br />   </pre>",
        is_multiple=True)
    try:
        sg = SendGridAPIClient('ADD HERE YOUR OWN KEY')
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except HTTPError as e:
        print(e.to_dict)
コード例 #12
0
ファイル: utilities.py プロジェクト: nasoma/sms_dashboard
def airtime_mail(amount, telephone_number, date, balance):
    message = Mail(
        from_email=app.config['MAIL_SENDER'],
        to_emails='*****@*****.**'
    )

    message.dynamic_template_data = {
        'subject': app.config['EMAIL_SUBJECT'],
        'amount': amount,
        'telephone': telephone_number,
        'date': date,
        'balance': balance
    }
    message.template_id = 'd-2b1a13d647ef4b329acb7e3e63c41f97'

    sg = SendGridAPIClient(app.config['SENDGRID_API_KEY'])
    response = sg.send(message)
コード例 #13
0
def send_application_submission_confirmation(to_email, from_email, subject, template_id):
    """
    send a generic response email to the applicant
    """
    message = Mail(
        from_email=from_email,
        to_emails=to_email,
        subject=subject
    )
    message.template_id = template_id

    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
    except Exception as e:
        print('could not send')
        print(e.message)
コード例 #14
0
def genera_nueva_contraseña(email, host, uuid):
    message = Mail(
        from_email=EMAIL_GLOBAL,
        to_emails=[email, EMAIL_GLOBAL],
    )
    message.dynamic_template_data = {
        'tema':
        'Genera tu nueva contraseña en TANQUEMANIA',
        'mensaje':
        f'Haz solicitado restablecer tu contraseña de echangarro \n- Por favor sigue la siguiente liga para generar una nueva contraseña: http://{host}/perfil/nuevo-pwd/{uuid}/'
    }
    message.template_id = 'd-44160c651dcd4d299cbf2174ade1bd1c'
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
    except Exception as e:
        print(e)
コード例 #15
0
ファイル: utils.py プロジェクト: baahkusi/shop-server
def send_email(to_email, message, template={'id': '', 'data': ''}):

    message = Mail(from_email='*****@*****.**',
                   to_emails=to_email,
                   subject='Africaniz',
                   html_content=message)

    if TESTING == 'false':
        message.dynamic_template_data = template['data']
        message.template_id = template['id']

    try:
        sg = SendGridAPIClient(SENDGRID_API_KEY)
        response = sg.send(message)
        return response
    except Exception as e:
        pass
コード例 #16
0
ファイル: views.py プロジェクト: jayronx512/nextagram_final
def create_purchase(img_id):
    nonce = request.form.get("nonce")
    amount = request.form.get("dollar")
    message = request.form.get("message")
    result = gateway.transaction.sale({
        "amount": amount,
        "payment_method_nonce": nonce,
        "options": {
            "submit_for_settlement": True
        }
    })
    if result.is_success:
        payment = Payment(payment=amount,
                          donator_id=current_user.id,
                          image_id=img_id,
                          message=message)
        if payment.save():
            image = Image.get_or_none(id=img_id)
            image_owner = User.get_or_none(id=image.user_id)
            message = Mail(
                from_email="*****@*****.**",
                to_emails=image_owner.email,
                subject=f"Donation from {current_user.username}",
                html_content=
                f'<strong>A donation of RM{amount} is made on your image{img_id} from {current_user.username}</strong>'
            )

            try:
                sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
                response = sg.send(message)
                print(response.status_code)
                print(response.body)
                print(response.headers)
            except Exception as e:
                print(str(e))

            flash(
                f"Transaction successful! Thanks on the behalf of Nextagram and {image_owner.username}!",
                'success')
            return redirect(url_for('home'))
        else:
            return render_template('payment/new.html')

    else:
        flash('Transaction failed', 'danger')
        return render_template('payment/new.html')
コード例 #17
0
ファイル: main.py プロジェクト: Curiouspaul1/SpamBot
def sendMail():
    message = Mail(
        from_email=os.getenv('hostemail'),  # set sender email as envvar
        to_emails=emails,
        subject="EMERGENCY!!",  # You can edit this
        plain_text_content=open('message.txt', 'r').read())
    try:
        sg = SendGridAPIClient(
            os.environ.get('API_KEY'))  # add your sendgrid api-key
        resp = sg.send(message)
        return True
    except HTTPError as e:
        print(e.to_dict)
        return False
    else:
        print(e.to_dict)
        return False
コード例 #18
0
ファイル: mail_helpers.py プロジェクト: dixondj/Nextagram
def endorsement_email(receiver, amount):
    print(receiver.email)
    message = Mail(
        from_email='*****@*****.**',
        to_emails='*****@*****.**',
        subject='Thanks for your Endorsement',
        html_content=
        f"<h1>Dear {receiver.username},</h1><br/>Thank you very much for your recent donation of {amount} USD.<br/><br/><h1>NEXTAGRAM</h1>"
    )
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(str(e))
コード例 #19
0
def confirma_usuario_con(email, host, uuid):
    message = Mail(
        from_email=EMAIL_GLOBAL,
        to_emails=[email, EMAIL_GLOBAL],
    )
    message.dynamic_template_data = {
        'tema':
        f'Bienvenido {email} a {host}, La Bodega del Hobby',
        'mensaje':
        f"¡Gracias por registrate en TANQUEMANIA la Bodega del Hobby! <br/> Por favor confirma tu correo, <a href='https://{host}/perfil/confirma-correo/{uuid}'>sigue esta liga &raquo;<a/>"
    }
    message.template_id = 'd-44160c651dcd4d299cbf2174ade1bd1c'
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
    except Exception as e:
        print(e)
コード例 #20
0
 def send_simple_email(self, *args, **kwargs):
     if isinstance(kwargs.get('to_email'), str):
         to_addresses = []
         to_addresses.append(kwargs.get('to_email'))
     else:
         to_addresses = kwargs.get('to_email')
     for address in to_addresses:
         message = Mail(
             from_email=kwargs.get('from_email'),
             to_emails=address,
             subject=kwargs.get('subject'),
             html_content=kwargs.get('body'))
         try:
             sg = SendGridAPIClient(self.api_key)
             response = sg.send(message)
         except Exception as e:
             print(e)
コード例 #21
0
def sendmail():
    message = Mail(
        from_email='*****@*****.**',
        to_emails='*****@*****.**',
        subject='Sending with Twilio SendGrid is Fun',
        html_content=
        '<strong>and easy to do anywhere, even with Python</strong>')
    try:
        sg = SendGridAPIClient(
            "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"
        )
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print()
コード例 #22
0
def send_email(subject="[Daily Briefing] This is a test", html="<p>Hello World</p>"):
    # > <class 'sendgrid.sendgrid.SendGridAPIClient>
    client = SendGridAPIClient(SENDGRID_API_KEY)
    print("CLIENT:", type(client))
    print("SUBJECT:", subject)
    #print("HTML:", html)
    message = Mail(from_email=MY_EMAIL, to_emails=MY_EMAIL,
                   subject=subject, html_content=html)
    try:
        response = client.send(message)
        # > <class 'python_http_client.client.Response'>
        print("RESPONSE:", type(response))
        print(response.status_code)  # > 202 indicates SUCCESS
        return response
    except Exception as e:
        print("OOPS", e.message)
        return None
コード例 #23
0
ファイル: emailer.py プロジェクト: GitDietz/sweb
def send_email_old(body, destination, subject):

    try:
        sg = SendGridAPIClient(getattr(settings, "EMAIL_KEY", None))
        sender = getattr(settings, "EMAIL_FROM", None)
        message = Mail(from_email=sender,
                       to_emails=destination,
                       subject=subject,
                       html_content=body)
        response = sg.send(message)
        # print(response.status_code)
        # print(response.body)
        # print(response.headers)
        return 0, ''
    except Exception as e:
        logging.getLogger("info_logger").info(f"Error: {e}")
        return 1, sender
コード例 #24
0
 def send_message(**kwargs):
     api_key = kwargs.get("api_key", "")
     to_emails = kwargs.get("to_emails", [])
     from_email = kwargs.get("from_email",
                             "*****@*****.**")
     message = kwargs.get("message", "")
     subject = kwargs.get("subject", "Error Alert from cloudalerts")
     message = Mail(from_email=from_email,
                    to_emails=to_emails,
                    subject=subject,
                    html_content=message)
     try:
         sg = SendGridAPIClient(api_key)
         response = sg.send(message)
         logging.info(response)
     except Exception as e:
         logging.warning(e.message)
コード例 #25
0
ファイル: messaging.py プロジェクト: agrc/forklift
def _send_email_with_sendgrid(email_server, to, subject, body, attachments=[]):
    '''
    email_server: dict
    to: string | string[]
    subject: string
    body: string | MIMEMultipart
    attachments: string[] - paths to text files to attach to the email

    Send an email.
    '''
    from_address = email_server['fromAddress']
    api_key = email_server['apiKey']

    if None in [from_address, api_key]:
        log.warning('Required environment variables for sending emails do not exist. No emails sent. See README.md for more details.')

        return

    message = Mail(
        from_email=from_address,
        to_emails=to,
        subject=subject,
        html_content=body)

    for location in attachments:
        path = Path(location)

        encoded_log = _gzip(path)

        if encoded_log is None:
            continue

        content = b64encode(encoded_log).decode()

        message.attachment = Attachment(
            FileContent(content), FileName(f'{path.name}.gz'), FileType('x-gzip'), Disposition('attachment')
        )

    try:
        client = SendGridAPIClient(api_key)

        return client.send(message)
    except Exception as e:
        log.error(f'Error sending email with SendGrid: {e}')

        return e
コード例 #26
0
ファイル: email.py プロジェクト: guru-aot/ccpractice
    def send(to_email: str, title: str, message: str):
        """Send Watch notification using SendGrid"""
        message = Mail(from_email='*****@*****.**',
                       to_emails=to_email,
                       subject='Notification:',
                       html_content='<strong>' + message + ' <i>Topic:' +
                       title + '</i></strong>')

        print(os.getenv('SENDGRID_API_KEY'))
        sg_client = SendGridAPIClient(
            api_key=
            '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'
        )
        response = sg_client.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
コード例 #27
0
    def send(self):
        if self.send_mail == 0:
            return

        if len(self.to_emails) > 1:
            is_multiple = True
        else:
            is_multiple = False
      
        message = Mail(
            from_email=self.from_email,
            to_emails=self.to_emails,
            subject=self.subject,
            html_content=self.html_content,
            is_multiple=is_multiple)

        with open(self.filename, 'rb') as f:
            data = f.read()
            f.close()

        encoded_file = base64.b64encode(data).decode()
        
        if platform.system() == "Windows":
            divider = "\\"
        else:
            divider = "/"
        parts = self.filename.split(divider)
        actual_filename = parts[len(parts) - 1]
        print(actual_filename)

        attachedFile = Attachment(
            FileContent(encoded_file),
            FileName(actual_filename),
            FileType(
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
            Disposition('attachment')
        )
        message.attachment = attachedFile

        try:
            SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
            sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
            response = sg.send(message)

        except Exception as e:
            print(e.message)
コード例 #28
0
def send_mail():
    global message, sended_time, sended

    message = Mail(from_email='〇〇@yahoo.co.jp',
                   to_emails='〇〇@gmail.com',
                   subject='MyBotからのお知らせ 変動率: ' + str(percent),
                   html_content='本文なし')
    try:
        sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
        sended_time = str(now_time.minute)
        sended = sended + 1
    except Exception as e:
        print(e.message)
コード例 #29
0
ファイル: app.py プロジェクト: onaclovtech/product-checker
def send_email(message):
    # using SendGrid's Python Library
    # https://github.com/sendgrid/sendgrid-python
    import os
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail
    print("Sending Email")
    message = Mail(from_email='*****@*****.**',
                   to_emails='*****@*****.**',
                   subject='In Stock',
                   html_content=message)
    try:
        sg = SendGridAPIClient(key)
        response = sg.send(message)
    except Exception as e:
        print("Error Sending Message ")
        print(e)
コード例 #30
0
def doEmail(emailAddressToC,newsAboutSales):
    message = Mail(
        from_email='*****@*****.**',
        to_emails=emailAddressToC,
        subject='New games on sale!',
        html_content=newsAboutSales)

    try:
        print(os.environ.get('SENDGRID_API_KEY'))
        sg = SendGridAPIClient('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')
        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print("Error!")
        print(e.message)
コード例 #31
0
ファイル: views.py プロジェクト: kenesovb/Tours
    def post(self, request):
        user = get_object_or_404(User, username=self.request.user)
        bookings = get_object_or_404(Booking, pk=request.data['id'])
        tour = get_object_or_404(Tour, pk=bookings.tour_detail.tour.id)
        image = TourImage.objects.filter(tour=bookings.tour_detail.tour.id)[0]
        tour.tour_rating = tour.tour_rating + int(
            bookings.booking_number_of_persons)
        message = Mail(
            from_email='*****@*****.**',
            to_emails=user.email,
            subject='Information about your ' +
            bookings.tour_detail.tour.title + ' tour',
            html_content=
            '<h2>Hello, dear Traveller! </h2> <br> <h3>Below some information about your tour </h3> <br>'
            + '<strong>' + bookings.tour_detail.tour.title + '</strong>' +
            '<p> Star date: <strong>' +
            str(bookings.tour_detail.tour_start_date) + '</strong> </p>' +
            '<p> End date: <strong>' +
            str(bookings.tour_detail.tour_end_date) + '</strong> </p>' +
            '<p> Starting city: <strong>' +
            str(bookings.tour_detail.tour.city.city_name) + '</strong> </p>' +
            '<p> Ending city: <strong>' +
            str(bookings.tour_detail.tour.tour_end_city) + '</strong> </p>' +
            '<p> Price: <strong>' + str(bookings.tour_detail.tour.price) +
            ' ' + str(bookings.tour_detail.tour.currency) + '</strong> </p>' +
            '<p> Status: <strong>' + str(bookings.booking_status) +
            '</strong> </p>' +
            '<p>you can download your ticket <a href="https://tourismera.herokuapp.com/api/v1/fornow/users/me/'
            + str(bookings.id) +
            '/pdf/download"> here </a> </p> <br><br><br><br>' + '<img src="' +
            image.file.url + '" width="450px" height="450px">' +
            '<h3>Have fun, hope you will enjoy your vacation across Kazakhstan</h3>'
            + '<h3>best regards from travel-kazakhstan team.</h3>')
        try:
            sg = SendGridAPIClient(os.environ.get('SendGridAPIClient'))
            response = sg.send(message)
        except Exception as e:
            print(e)
        tour.save()
        bookings.tour_detail.cur_person_number = bookings.tour_detail.cur_person_number + \
                                                 int(bookings.booking_number_of_persons)
        bookings.booking_status = 'Approved'
        bookings.tour_detail.save()
        bookings.save()

        return Response(status=status.HTTP_201_CREATED)
コード例 #32
0
def _send_mail(to, data, template_id, html_content=''):
    message = Mail(
        from_email='GoToken <*****@*****.**>',
        to_emails=to,
        html_content='<strong>and easy to do anywhere, even with Python</strong>')

    message.dynamic_template_data = data
    message.template_id = template_id

    try:
        sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
        response = sendgrid_client.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e.message)
コード例 #33
0
class SendGridMailer:
    def __init__(self, *args, **kwargs):
        self.client = SendGridAPIClient(settings.SENDGRID_API_KEY)

    def send(self, from_email, to_emails, subject, message, message_type="html"):
        # if type(to_emails) == list:
        #     to_emails = ",".join(to_emails)
        context = {"from_email":from_email, "to_emails":to_emails,"subject":subject}
        if message_type=="html":
            context["html_content"] = message
        elif message_type=="text":
            context["plain_text_content"] = message
        message = Mail(**context)
        response=self.client.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
コード例 #34
0
ファイル: live_test.py プロジェクト: sendgrid/sendgrid-python
## Send a Single Email to a Single Recipient
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException

message = Mail(from_email=From('*****@*****.**', 'DX'),
               to_emails=To('*****@*****.**', 'Elmer Thomas'),
               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>'))

try:
    print(json.dumps(message.get(), sort_keys=True, indent=4))
    sendgrid_client = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
    response = sendgrid_client.send(message=message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except SendGridException as e:
    print(e.message)

# Send a Single Email to Multiple Recipients
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException

to_emails = [
    To('*****@*****.**', 'Elmer SendGrid'),
    To('*****@*****.**', 'Elmer Thomas')