コード例 #1
0
ファイル: web_service.py プロジェクト: tate11/oniad
 def __init__(self, company, env):
     self.company = company
     self.custom_env = env
     self.api_key = tools.config.get('sendinblue_api_key')
     configuration = sib_api_v3_sdk.Configuration()
     configuration.api_key['api-key'] = self.api_key
     # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
     # configuration.api_key_prefix['api-key'] = 'Bearer'
     # create an instance of the API class
     self.api_instance_account_api = sib_api_v3_sdk.AccountApi(
         sib_api_v3_sdk.ApiClient(configuration))
     self.api_instance_contacts_api = sib_api_v3_sdk.ContactsApi(
         sib_api_v3_sdk.ApiClient(configuration))
コード例 #2
0
def send_email():

    api_instance = sib_api_v3_sdk.TransactionalEmailsApi(
        sib_api_v3_sdk.ApiClient(configuration))

    email = {
        "to": ['*****@*****.**'],
        "reply_to": '*****@*****.**',
        "sender": {
            "name": 'Testing UWCC',
            "email": '*****@*****.**'
        },
        "html_content":
        'This test was successful, \nthanks for participating!',
        "subject": 'Test'
    }

    send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(**email)

    try:
        api_response = api_instance.send_transac_email(send_smtp_email)
        print(api_response)
    except ApiException as e:
        print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)
        raise e
コード例 #3
0
def send_transactional_email(payload: SendTransactionalEmailRequest) -> bool:
    to = [{"email": email} for email in payload.recipients]
    sender = {"email": settings.SUPPORT_EMAIL_ADDRESS, "name": "pass Culture"}
    template_id = payload.template_id
    params = payload.params
    tags = payload.tags

    configuration = sib_api_v3_sdk.Configuration()
    configuration.api_key["api-key"] = settings.SENDINBLUE_API_KEY
    api_instance = sib_api_v3_sdk.TransactionalEmailsApi(
        sib_api_v3_sdk.ApiClient(configuration))

    send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(to=to,
                                                   sender=sender,
                                                   reply_to=sender,
                                                   template_id=template_id,
                                                   params=params,
                                                   tags=tags)

    try:
        api_instance.send_transac_email(send_smtp_email)
        return True
    except ApiException as e:
        logger.error(
            "Exception when calling SMTPApi->send_transac_email: %s\n", e)
        return False
    except Exception as e:  # pylint: disable=broad-except
        logger.error(
            "Unknown exception occurred when calling SMTPApi->send_transac_email: %s\n",
            e)
        return False
コード例 #4
0
def sendInBlueEmail(params):
    configuration = sib_api_v3_sdk.Configuration()

    configuration.api_key['api-key'] = os.environ.get(
        "SEND_IN_BLUE"
    )  ## Either pass your key directly here or add in the aws console of lambda function
    api_instance = sib_api_v3_sdk.TransactionalEmailsApi(
        sib_api_v3_sdk.ApiClient(configuration))
    subject = "from the Python SDK!"
    sender = {"name": "sample", "email": "*****@*****.**"}
    replyTo = {"name": "sample", "email": "*****@*****.**"}
    html_content = "<html><body><h1>Find Vaccine Availability in navi mumbai </h1></body></html>"
    to = to_addresses
    send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(bcc=cc_addresses,
                                                   to=to_addresses,
                                                   reply_to=replyTo,
                                                   template_id=1,
                                                   sender=sender,
                                                   subject=subject,
                                                   params=params)

    try:
        api_response = api_instance.send_transac_email(send_smtp_email)
        print(api_response)
    except ApiException as e:
        print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)
コード例 #5
0
def initialize_api_instance_transactional(*args, **kwargs):
    # Configure API key authorization: api-key
    configuration = sib_api_v3_sdk.Configuration()
    configuration.api_key['api-key'] = SEND_IN_BLUE_API_KEY

    # create an instance of the API class
    api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
    bcc = kwargs.get('bcc', None)
    if bcc == '':
        bcc = None
    cc = kwargs.get('cc', None)
    if cc == '':
        cc = None
    reply_to = kwargs.get('reply_to', None)
    if reply_to == '':
        reply_to = None
    send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
        attachment=None,
        bcc=bcc,
        cc=cc,
        headers=kwargs.get('headers', None),
        html_content=kwargs.get('body', None),
        message_versions=None,
        params=None,
        reply_to=reply_to,
        sender=kwargs.get('sender', DEFAULT_EMAIL_SENDER),
        subject=kwargs.get('title', None),
        tags=None,
        template_id=None,
        text_content=None,
        to=kwargs.get('to', None)
    )
    return api_instance, send_smtp_email
コード例 #6
0
def create_contact(username, email, name, blacklisted):
    configuration = setup_sendinblue_configuration()

    if configuration:
        api_instance = sib_api_v3_sdk.ContactsApi(
            sib_api_v3_sdk.ApiClient(configuration))
        contact = sib_api_v3_sdk.CreateContact(
            email=email,
            attributes={"FULL_NAME": name},
            email_blacklisted=blacklisted,
            list_ids=[
                settings.EDRAAK_SENDINBLUE_LISTID,
            ],
            update_enabled=True)

        try:
            response = api_instance.create_contact(contact)
            log.info(
                'SendInBlue contact created with response text {text}'.format(
                    text=response))
        except ApiException as e:
            log.exception(
                "Exception when calling SendInBlue for email ({}) ContactsApi->create_contact: {}\n"
                .format(email, e))


# TODO: update contact attributes upon completion of profile
# TODO: delete a contact and integrate with user retirement
コード例 #7
0
def make_update_request(payload: UpdateSendinblueContactRequest) -> bool:
    if settings.IS_RUNNING_TESTS:
        testing.sendinblue_requests.append({
            "email":
            payload.email,
            "attributes":
            payload.attributes,
            "emailBlacklisted":
            payload.emailBlacklisted
        })
        return True

    if settings.IS_DEV:
        logger.info(
            "A request to Sendinblue Contact API would be sent for user %s with attributes %s emailBlacklisted: %s",
            payload.email,
            payload.attributes,
            payload.emailBlacklisted,
        )
        return True

    configuration = sib_api_v3_sdk.Configuration()
    configuration.api_key["api-key"] = settings.SENDINBLUE_API_KEY
    api_instance = sib_api_v3_sdk.ContactsApi(
        sib_api_v3_sdk.ApiClient(configuration))
    create_contact = sib_api_v3_sdk.CreateContact(
        email=payload.email,
        attributes=payload.attributes,
        list_ids=payload.contact_list_ids,
        update_enabled=True,
        email_blacklisted=payload.emailBlacklisted,
    )

    try:
        api_instance.create_contact(create_contact)
        return True

    except SendinblueApiException as exception:
        if exception.status == 524:
            logger.warning(
                "Timeout when calling ContactsApi->create_contact: %s",
                exception,
                extra={
                    "email": payload.email,
                    "attributes": payload.attributes,
                    "emailBlacklisted": payload.emailBlacklisted,
                },
            )
        else:
            logger.exception(
                "Exception when calling ContactsApi->create_contact: %s",
                exception,
                extra={
                    "email": payload.email,
                    "attributes": payload.attributes,
                    "emailBlacklisted": payload.emailBlacklisted,
                },
            )
        return False
コード例 #8
0
ファイル: app.py プロジェクト: prataplyf/Flask
def booking():
    if request.method == 'POST':
        uname = request.form.get('name')
        email = request.form.get('email')
        contact = request.form.get('contact')
        skypeID = request.form.get('skypeID')
        date = request.form.get('date')
        timeslot = request.form.get('timeslot')
        result = timeslotBooking.find({}).count() + 1
        uid = "B-WSS" + "%07d" % result
        name = uname.split()[0]
        configuration = sib_api_v3_sdk.Configuration()
        configuration.api_key[
            'api-key'] = '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'
        api_instance = sib_api_v3_sdk.SMTPApi(
            sib_api_v3_sdk.ApiClient(configuration))
        send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
            to=[{
                "email": email,
                "name": name
            }],
            template_id=15,
            params={
                "name": name,
                "date": date,
                "time": timeslot
            },
            headers={
                "X-Mailin-custom":
                "custom_header_1:custom_value_1|custom_header_2:custom_value_2|custom_header_3:custom_value_3",
                "charset": "iso-8859-1"
            })  # SendSmtpEmail | Values to send a transactional email
        try:
            # Send a transactional email
            api_response = api_instance.send_transac_email(send_smtp_email)
            timeslotBooking.insert_one({
                "_id": uid,
                "Name": name,
                "Email": email,
                "Contact": contact,
                "SkypeID": skypeID,
                "Date": date,
                "TimeSlot": timeslot
            })
            pprint(api_response)
            return jsonify({
                "Name": name,
                "Email": email,
                "Contact Number": contact,
                "SkypeID": skypeID,
                "Date": date,
                "TimeSlot": timeslot
            })
        except ApiException as e:
            print("Exception when calling SMTPApi->send_transac_email: %s\n" %
                  e)

    return render_template('booking.html')
コード例 #9
0
def send_email(emailid, content):
    api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
    send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(to=emailid, subject="Slot available by Laksh", params={"CONTENT": content},template_id=5, headers={"X-Mailin-custom": "custom_header_1:custom_value_1|custom_header_2:custom_value_2|custom_header_3:custom_value_3", "charset": "iso-8859-1"}) # SendSmtpEmail | Values to send a transactional email
    try:
        api_response = api_instance.send_transac_email(send_smtp_email)
        print(f"Sent email to: {emailid}")
        print(api_response)
        return True
    except ApiException as e:
        print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)
        return False
コード例 #10
0
ファイル: app.py プロジェクト: prataplyf/Flask
 def check():
     characters = string.ascii_letters + string.digits
     password = "".join(
         choice(characters) for x in range(randint(8, 8)))
     if re.search("[0-9][a-z][A-Z]", password):
         global pd
         pd = password
         configuration = sib_api_v3_sdk.Configuration()
         configuration.api_key[
             'api-key'] = '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'
         api_instance = sib_api_v3_sdk.SMTPApi(
             sib_api_v3_sdk.ApiClient(configuration))
         send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
             to=[{
                 "email": email,
                 "name": name
             }],
             template_id=14,
             params={
                 "name": name,
                 "email": email,
                 "pwd": password
             },
             headers={
                 "X-Mailin-custom":
                 "custom_header_1:custom_value_1|custom_header_2:custom_value_2|custom_header_3:custom_value_3",
                 "charset": "iso-8859-1"
             }
         )  # SendSmtpEmail | Values to send a transactional email
         try:
             # Send a transactional email
             api_response = api_instance.send_transac_email(
                 send_smtp_email)
             user.insert_one({
                 "_id": uid,
                 "Name": name,
                 "Email": email,
                 "Password": pd
             })
             User_delete.remove({"Email": email}, {
                 "Name": 1,
                 "Email": 1,
                 "Password": 1,
                 "_id": 1
             })
             pprint(api_response)
         except ApiException as e:
             print(
                 "Exception when calling SMTPApi->send_transac_email: %s\n"
                 % e)
         #
     else:
         return check()
コード例 #11
0
def upload_to_sib(content, numero_id, title, hours="18:00:00"):
    folder = get_script_path()
    fname = os.path.join(folder, 'sib.keys')
    if not os.path.isfile(fname):
        raise IOError("Please, create configuration file for upload")

    with open(fname, 'r') as f:
        config_data = json.load(f)
    configuration = sib_api_v3_sdk.Configuration()
    configuration.api_key['api-key'] = config_data.get('api-key-v3')

    api_client = sib_api_v3_sdk.ApiClient(configuration)
    api_instance = sib_api_v3_sdk.AccountApi(api_client)

    try:
        # Get your account informations, plans and credits details
        api_response = api_instance.get_account()
        print(api_response)
    except ApiException as e:
        print("Exception when calling AccountApi->get_account: %s\n" % e)

    # now = datetime.now(timezone.utc)
    # scheduled_at = now.strftime("%Y-%m-%dT{}Z".format(hours))
    api_instance = sib_api_v3_sdk.EmailCampaignsApi(api_client)

    # Define the campaign settings\
    email_campaigns = sib_api_v3_sdk.CreateEmailCampaign(
        name="Python Astuces #{}".format(numero_id),
        subject="Python Astuces #{} - {}".format(numero_id, title),
        sender={
            "name": "Python Astuces",
            "email": "*****@*****.**"
        },
        reply_to="*****@*****.**",
        html_content=content,
        # Select the recipients\
        recipients={"listIds": [
            2,
        ]},
        # scheduled_at=scheduled_at,
        # inline_image_activation=True
    )

    # Make the call to the client\
    try:
        api_response = api_instance.create_email_campaign(email_campaigns)
        print(api_response)
    except ApiException as e:
        msg = "Exception when calling"
        msg += " EmailCampaignsApi->create_email_campaign:%s\n" % e
        print(msg)
コード例 #12
0
def create_compaign_user(user_mail):
    configuration = sib_api_v3_sdk.Configuration()
    configuration.api_key['api-key'] = TRANSACTIONAL_MAIL_KEY

    api_instance = sib_api_v3_sdk.ContactsApi(
        sib_api_v3_sdk.ApiClient(configuration))
    create_contact = sib_api_v3_sdk.CreateContact(email=user_mail,
                                                  list_ids=[COMPAIGN_ID])

    try:
        api_response = api_instance.create_contact(create_contact)
    except ApiException as e:
        print("Exception when calling ContactsApi->create_contact: %s\n" % e)
        return False
    return True
コード例 #13
0
def initialize_api_instance_account():
    # Configure API key authorization: api-key
    configuration = sib_api_v3_sdk.Configuration()
    configuration.api_key['api-key'] = SEND_IN_BLUE_API_KEY

    # create an instance of the API class
    api_instance = sib_api_v3_sdk.AccountApi(sib_api_v3_sdk.ApiClient(configuration))

    try:
        # Get your account information, plan and credits details
        response = api_instance.get_account()
    except ApiException as e:
        print("Exception when calling AccountApi->get_account: %s\n" % e)
        return None
    return api_instance, response
コード例 #14
0
def send_transaction_email(user_mail):
    configuration = sib_api_v3_sdk.Configuration()
    configuration.api_key['api-key'] = TRANSACTIONAL_MAIL_KEY

    api_instance = sib_api_v3_sdk.EmailCampaignsApi(
        sib_api_v3_sdk.ApiClient(configuration))
    campaign_id = 1
    email_to = sib_api_v3_sdk.SendTestEmail(email_to=[user_mail])

    try:
        resp = api_instance.send_test_email(campaign_id, email_to)
    except ApiException as e:
        print(
            "Exception when calling EmailCampaignsApi->send_test_email: %s\n" %
            e)
        return False

    return True
コード例 #15
0
ファイル: subscription.py プロジェクト: betagouv/ma-cantine
    def post(self, request):
        try:
            email = request.data.get("email")
            validate_email(email)

            list_id = settings.NEWSLETTER_SENDINBLUE_LIST_ID
            configuration = sib_api_v3_sdk.Configuration()
            configuration.api_key["api-key"] = settings.ANYMAIL.get(
                "SENDINBLUE_API_KEY")
            api_instance = sib_api_v3_sdk.ContactsApi(
                sib_api_v3_sdk.ApiClient(configuration))
            create_contact = sib_api_v3_sdk.CreateContact(email=email)
            create_contact.list_ids = [int(list_id)]
            create_contact.update_enabled = True
            api_instance.create_contact(create_contact)
            return JsonResponse({}, status=status.HTTP_200_OK)
        except sib_api_v3_sdk.rest.ApiException as e:
            contact_exists = json.loads(
                e.body).get("message") == "Contact already exist"
            if contact_exists:
                logger.error(f"Beta-tester already exists: {email}")
                return JsonResponse({}, status=status.HTTP_200_OK)
            logger.error("SIB API error in beta-tester subsription :")
            logger.exception(e)
            return JsonResponse(
                {"error": "Error calling SendInBlue API"},
                status=status.HTTP_400_BAD_REQUEST,
            )
        except ValidationError as e:
            logger.error(f"Invalid email on beta-tester subscription: {email}")
            logger.exception(e)
            return JsonResponse({"error": "Invalid email"},
                                status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            logger.error("Error on newsletter subscription")
            logger.exception(e)
            return JsonResponse(
                {"error": "An error has ocurred"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            )
コード例 #16
0
def send_email(to_emails,
               title,
               body,
               from_email=None,
               from_name=None,
               receiver_names=None):

    api_instance = sib_api_v3_sdk.TransactionalEmailsApi(
        sib_api_v3_sdk.ApiClient(configuration))

    # Prepare the list of recipients, optionally including names
    if receiver_names is None:
        recipients = [{'email': mail} for mail in to_emails]
    else:
        recipients = [{
            'email': mail,
            'name': name
        } for name, mail in zip(receiver_names, to_emails)]

    email = {
        "to": recipients,
        "reply_to": {
            'email': from_email
        },
        "sender": {
            "name": from_name,
            "email": from_email
        },
        "html_content": body,
        "subject": title
    }

    send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(**email)

    try:
        api_response = api_instance.send_transac_email(send_smtp_email)
        print(api_response)
    except ApiException as e:
        print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)
        raise e
コード例 #17
0
def import_contacts_in_sendinblue(
        sendinblue_users_data: List[SendinblueUserUpdateData],
        email_blacklist: bool = False) -> None:
    configuration = sib_api_v3_sdk.Configuration()
    configuration.api_key["api-key"] = settings.SENDINBLUE_API_KEY
    api_instance = sib_api_v3_sdk.ContactsApi(
        sib_api_v3_sdk.ApiClient(configuration))

    # Split users in sendinblue lists
    pro_users = [
        user_data for user_data in sendinblue_users_data
        if user_data.attributes[SendinblueAttributes.IS_PRO.value]
    ]
    young_users = [
        user_data for user_data in sendinblue_users_data
        if not user_data.attributes[SendinblueAttributes.IS_PRO.value]
    ]

    # send pro users request
    if pro_users:
        pro_users_file_body = build_file_body(pro_users)
        send_import_contacts_request(
            api_instance,
            file_body=pro_users_file_body,
            list_ids=[settings.SENDINBLUE_PRO_CONTACT_LIST_ID],
            email_blacklist=email_blacklist,
        )
    # send young users request
    if young_users:
        young_users_file_body = build_file_body(young_users)
        send_import_contacts_request(
            api_instance,
            file_body=young_users_file_body,
            list_ids=[settings.SENDINBLUE_YOUNG_CONTACT_LIST_ID],
            email_blacklist=email_blacklist,
        )
コード例 #18
0
    def envio_email(self, correo, nombre, apellido, total, productos):

        configuration = sib_api_v3_sdk.Configuration()
        configuration.api_key[
            'api-key'] = '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'
        fecha = datetime.now()
        dia = fecha.day
        mes = fecha.month
        anio = fecha.year
        fecha_compra = str(dia) + "/" + str(mes) + "/" + str(anio)
        # cra un instancia de la Api

        api_instance = sib_api_v3_sdk.TransactionalEmailsApi(
            sib_api_v3_sdk.ApiClient(configuration))
        send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(to=[{
            "email": correo,
            "name": nombre
        }],
                                                       template_id=2,
                                                       params={
                                                           "DATE":
                                                           fecha_compra,
                                                           "NOMBRE": nombre,
                                                           "APELLIDO":
                                                           apellido,
                                                           "TOTAL": total,
                                                           "PRODUCTOS":
                                                           productos
                                                       })

        try:
            # Envio de email transaccional
            api_response = api_instance.send_transac_email(send_smtp_email)
            pprint(api_response)
        except ApiException as e:
            print("Error al envio: %s\n" % e)
コード例 #19
0
 def perform(self, message: Msg, sender: str, lang: str, **kwargs):
     title_html, body_html, attachments = self.render(message, lang)
     api_instance = sib_api_v3_sdk.SMTPApi(sib_api_v3_sdk.ApiClient(self.configuration))
     senderSmtp = sib_api_v3_sdk.SendSmtpEmailSender(
         name=self.sender_name,
         email=self.sender_email,
     )
     sendTo = sib_api_v3_sdk.SendSmtpEmailTo(
         email=message.recipient,
         name="Recipient Name"  # what's the name?
     )
     arrTo = [sendTo]
     sending_kwargs = {
         "sender": senderSmtp,
         "to": arrTo,
         "html_content": body_html,
         "subject": title_html,
     }
     # attachments.append(self.get_logo_attachment())
     if attachments:
         sending_kwargs['attachment'] = attachments
     send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(**sending_kwargs)
     api_response = api_instance.send_transac_email(send_smtp_email)
     return api_response
コード例 #20
0
 def api_sib(self):
     if not self.APISIB:
         self.APISIB = sib_api_v3_sdk.ApiClient(self.conf_sib)
     return self.APISIB
コード例 #21
0
def web_checkout(request):
    DEFAULT_RETIRE_HOUR = 10
    # get or create user
    email = request.POST.get("email")
    random_token = ''.join(
        random.choices(string.ascii_uppercase + string.digits, k=5))
    try:
        user = CustomUser.objects.get(email=email)
        user.phone_number = request.POST.get("phone_number")
        user.save()
    except:
        user = CustomUser.objects.create_user(
            email=request.POST.get("email"),
            password=random_token,
            confirm_password=random_token,
            full_name=request.POST.get("full_name"),
            phone_number=request.POST.get("phone_number"))
    cart_list = json.loads(request.POST.get('cart_list'))
    retire_time = request.POST.get('retire_time')
    retire_hour = DEFAULT_RETIRE_HOUR
    order_comments = request.POST.get('comments') or ''
    order = create_order_for_user(cart_list, retire_time, retire_hour,
                                  order_comments, user, 1)

    email_attrs = {
        'FULL_NAME': order.user.full_name,
        'ORDER_ID': order.id,
        'ORDER_DESCRIPTION': order.description,
        'ORDER_RETIRE_TIME': arrow.get(order.retire_time).format('DD/MM/YYYY')
    }

    api_instance = sib_api_v3_sdk.TransactionalEmailsApi(
        sib_api_v3_sdk.ApiClient(configuration))
    send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
        to=[{
            "email": order.user.email,
            "name": order.user.full_name
        }],
        template_id=1,
        params=email_attrs,
        headers={
            "charset": "iso-8859-1",
            "Content-Type": "text/html;charset=iso-8859-1"
        })  # SendSmtpEmail | Values to send a transactional email

    #m = Mailin("https://api.sendinblue.com/v3", settings.SENDINBLUE_KEY)
    # data = {
    #     "id": 7,
    #     "to": order.user.email,
    #     "bcc": "*****@*****.**",
    #     "replyto": "*****@*****.**",
    #     "attr": email_attrs,
    #     "headers": {"Content-Type": "text/html;charset=iso-8859-1"}
    # }
    #
    # result = m.send_transactional_template(data)
    try:
        # Send a transactional email
        result = api_instance.send_transac_email(send_smtp_email)
    except ApiException as e:
        print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)
    print(result)
    return redirect('post_checkout')
コード例 #22
0

import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException


from __future__ import print_function
import time
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from pprint import pprint

configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = 'YOUR API KEY'

api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
subject = "My Subject"
html_content = "<html><body><h1>This is my first transactional email </h1></body></html>"
sender = {"name":"John Doe","email":"*****@*****.**"}
to = [{"email":"*****@*****.**","name":"Jane Doe"}]
cc = [{"email":"*****@*****.**","name":"Janice Doe"}]
bcc = [{"name":"John Doe","email":"*****@*****.**"}]
reply_to = {"email":"*****@*****.**","name":"John Doe"}
headers = {"Some-Custom-Name":"unique-id-1234"}
params = {"parameter":"My param value","subject":"New Subject"}
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(to=to, bcc=bcc, cc=cc, reply_to=reply_to, headers=headers, html_content=html_content, sender=sender, subject=subject)

try:
    api_response = api_instance.send_transac_email(send_smtp_email)
    pprint(api_response)
except ApiException as e:
コード例 #23
0
ファイル: deps.py プロジェクト: studio-rubik/WebAudition
import boto3
import sib_api_v3_sdk

from .app import app
from .models import db

s3 = boto3.resource("s3", endpoint_url=app.config["AWS_S3_ENDPOINT_URL"])
configuration = sib_api_v3_sdk.Configuration()
smtp = sib_api_v3_sdk.SMTPApi(sib_api_v3_sdk.ApiClient(configuration))


@app.before_request
def before_request():
    db.connect()


@app.after_request
def after_request(response):
    db.close()
    return response
コード例 #24
0
    def send_campaign(self, request, campaign, contacts, test_send=False):

        sib_api_key = getattr(settings, "SENDINBLUE_API_KEY", None)
        config = None
        if sib_api_key:
            config = sib_api_v3_sdk.Configuration()
            config.api_key['api-key'] = sib_api_key
        else:
            logging.info("No SIB mailing list")

        if test_send and config:
            for contact in contacts:
                content = render_to_string(
                    campaign.get_template(request),
                    campaign.get_context(request, contact),
                )
                # create an instance of the API class
                api_instance = sib_api_v3_sdk.TransactionalEmailsApi(
                    sib_api_v3_sdk.ApiClient(config))
                send_smtp_email_sender = sib_api_v3_sdk.SendSmtpEmailSender(
                    email=self.from_email)
                send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
                    sender=send_smtp_email_sender,
                    to=[{
                        'email': contact.email
                    }],
                    html_content=content,
                    subject=campaign.subject,
                    headers={
                        "X-Mailin-custom":
                        "custom_header_1:custom_value_1|custom_header_2:custom_value_2|custom_header_3:custom_value_3",
                        "charset": "iso-8859-1"
                    })

                try:
                    # Send a transactional email
                    api_response = api_instance.send_transac_email(
                        send_smtp_email)
                except ApiException as e:
                    messages.error(request, f"Test email failed: {e}")
                    print(
                        "Exception when calling SMTPApi->send_transac_email: %s\n"
                        % e)

        elif sib_api_key:
            # To satisfy module internals we need a dummy email address as the contact in the content
            api_instance = sib_api_v3_sdk.ContactsApi(
                sib_api_v3_sdk.ApiClient(config))
            lists = api_instance.get_lists(limit=50).lists
            lists = list(
                filter(lambda l: campaign.mailing_lists in l['name'], lists))
            contact = re.sub('\s+', '',
                             campaign.mailing_lists) + "@climate.esa.int"

            content = render_to_string(campaign.get_template(request),
                                       campaign.get_context(request, contact))

            sendTime = datetime.utcnow() + timedelta(minutes=5)
            sendTimeStr = sendTime.strftime("%Y-%m-%dT%H:%M:%S.000Z")

            selected_lists = [l['id'] for l in lists]
            url = "https://api.sendinblue.com/v3/emailCampaigns"

            payload = {
                "sender": {
                    "email": self.from_email
                },
                "recipients": {
                    "listIds": selected_lists
                },
                "inlineImageActivation": False,
                "sendAtBestTime": False,
                "abTesting": False,
                "ipWarmupEnable": False,
                "name": campaign.name,
                "htmlContent": content,
                "subject": campaign.subject,
                "scheduledAt": sendTimeStr
            }
            headers = {
                "Accept": "application/json",
                "Content-Type": "application/json",
                "api-key": sib_api_key
            }

            the_campaign = SendCampaign(request, campaign.pk, url, payload,
                                        headers)
            the_campaign.run()
コード例 #25
0
    def send_reset_email(cls, user, url):
        configuration = sib_api_v3_sdk.Configuration()
        configuration.api_key['api-key'] = os.getenv('API_KEY')

        api_instance = sib_api_v3_sdk.TransactionalEmailsApi(
            sib_api_v3_sdk.ApiClient(configuration))
        subject = "Password Reset Request for LISA"

        html_content = """
        <!DOCTYPE html>
        <html>

        <head>
            <!-- Remote style sheet -->
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">

        </head>

        <body style="background-color:#f9f9f9;">
            <div class= "container" style="background-color:#f9f9f9;width:500px;border-collapse:collapse;border-spacing:0;position:absolute;margin-left:auto;margin-right:auto;left:0;right:0;">
                <img src="https://firebasestorage.googleapis.com/v0/b/projectdoc-5af7b.appspot.com/o/template%2Fwp2570965.jpg?alt=media&token=678c9c38-92da-4ba1-ad89-32a461871e9e" style="height:auto;display:block;display: block;margin-left: auto;margin-right: auto;width: 100%;" </img>
                <table role="presentation" style="background-color:#ffffff;border: 1px solid #c5cad9;">
                    <tr>
                        <td style="text-align:center;vertical-align:top;direction:ltr;font-size:0px;padding:40px 50px">
                            <div aria-labelledby="mj-column-per-100" class="m_6964446768198031751mj-column-per-100"
                                style="vertical-align:top;display:inline-block;direction:ltr;font-size:13px;text-align:left;width:100%">
                                <table role="presentation" cellpadding="0" cellspacing="0" width="100%" border="0">
                                    <tbody>
                                        <tr>
                                            <td style="word-break:break-word;font-size:0px;padding:0px" align="left">
                                                <div
                                                    style="color:#737f8d;font-family:Whitney,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;font-size:16px;line-height:24px;text-align:left">

                                                    <h2
                                                        style="font-family:Whitney,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;font-weight:500;font-size:20px;color:#4f545c;letter-spacing:0.27px">
                                                        Hey {},</h2>
                                                    <p>Your LISA password can be <span class="il">reset</span> by clicking
                                                        the button below. If you did not request a new password, please ignore
                                                        this email.</p>

                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="word-break:break-word;font-size:0px;padding:10px 25px;padding-top:20px"
                                                align="center">
                                                <table role="presentation" cellpadding="0" cellspacing="0"
                                                    style="border-collapse:separate" align="center" border="0">
                                                    <tbody>
                                                        <tr>
                                                            <td style="border:none;border-radius:3px;color:white;padding:15px 19px"
                                                                align="center" valign="middle" bgcolor="#7289DA"><a
                                                                    href={}
                                                                    style="text-decoration:none;line-height:100%;background:#7289da;color:white;font-family:Ubuntu,Helvetica,Arial,sans-serif;font-size:15px;font-weight:normal;text-transform:none;margin:0px"
                                                                    <span class="il">Reset</span> Password
                                                                </a></td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="word-break:break-word;font-size:0px;padding:30px 0px">
                                                <p
                                                    style="font-size:1px;margin:0px auto;border-top:1px solid #dcddde;width:100%">
                                                </p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="word-break:break-word;font-size:0px;padding:0px" align="left">
                                                <!-- <div
                                                    style="color:#747f8d;font-family:Whitney,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;font-size:13px;line-height:16px;text-align:left">
                                                    <p>Need help? <a
                                                            href="https://url9624.discordapp.com/ls/click?upn=qDOo8cnwIoKzt0aLL1cBeNlOcN7VC1Mue2BSa5oqYEdKm-2BPBEvWHLEUfi61TfqfxuvBipSaAkPtkAVPOEnBIzw-3D-3DioHW_av9jLgVz1hP-2FL23lkyqaU7Iw5z8d9cjUxeAc64zG-2BCrkrwGzXJ0UvMvbPbh0CuPQR4XvzIFXgeoDwXnAKuYf1dtVLmy9bjZvmioy7CiEqaaUw0gzmeeN8hENSyy-2BFnnQe-2Bt0mXQLXh3CpZv7j24L7dUFCGxoOSGlsSi-2B4h5FzeuZMsnKz6Jpe5b264knMhKDgyD4eh8tObF3gzgwNSZy4OPjH7x6In-2B1V3zD3HFxLZI-3D"
                                                            style="font-family:Whitney,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;color:#7289da"
                                                            target="_blank"
                                                            data-saferedirecturl="https://www.google.com/url?q=https://url9624.discordapp.com/ls/click?upn%3DqDOo8cnwIoKzt0aLL1cBeNlOcN7VC1Mue2BSa5oqYEdKm-2BPBEvWHLEUfi61TfqfxuvBipSaAkPtkAVPOEnBIzw-3D-3DioHW_av9jLgVz1hP-2FL23lkyqaU7Iw5z8d9cjUxeAc64zG-2BCrkrwGzXJ0UvMvbPbh0CuPQR4XvzIFXgeoDwXnAKuYf1dtVLmy9bjZvmioy7CiEqaaUw0gzmeeN8hENSyy-2BFnnQe-2Bt0mXQLXh3CpZv7j24L7dUFCGxoOSGlsSi-2B4h5FzeuZMsnKz6Jpe5b264knMhKDgyD4eh8tObF3gzgwNSZy4OPjH7x6In-2B1V3zD3HFxLZI-3D&amp;source=gmail&amp;ust=1623380898827000&amp;usg=AFQjCNGTsQC5Fqab-gw8xvqCTjY7INY4eA">Contact
                                                            our support team</a> or hit us up on Twitter <a
                                                            href="https://url9624.discordapp.com/ls/click?upn=qDOo8cnwIoKzt0aLL1cBeHLasbud5D3vi74o1Q-2B2VLcLLCDOodJpEqop-2Fc-2F5Wr6ZjdI4_av9jLgVz1hP-2FL23lkyqaU7Iw5z8d9cjUxeAc64zG-2BCrkrwGzXJ0UvMvbPbh0CuPQmfNZNY-2FILyobSO4P9h1dKzHEtVSzIVSf2C6VBGN9DjSQYjtAdAKazZ96BSDYTVd3xqazrmIvyMKeCNzgcESsWdgmr0II3ec6aUMcbe0EHYlcExYTWEjv-2Fm-2FHt1jtoP5r0dgiLOP-2BxY5cgnjSI0L2QbvlT3yhOgAtnVJhqAcw8a4-3D"
                                                            style="font-family:Whitney,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;color:#7289da"
                                                            target="_blank"
                                                            data-saferedirecturl="https://www.google.com/url?q=https://url9624.discordapp.com/ls/click?upn%3DqDOo8cnwIoKzt0aLL1cBeHLasbud5D3vi74o1Q-2B2VLcLLCDOodJpEqop-2Fc-2F5Wr6ZjdI4_av9jLgVz1hP-2FL23lkyqaU7Iw5z8d9cjUxeAc64zG-2BCrkrwGzXJ0UvMvbPbh0CuPQmfNZNY-2FILyobSO4P9h1dKzHEtVSzIVSf2C6VBGN9DjSQYjtAdAKazZ96BSDYTVd3xqazrmIvyMKeCNzgcESsWdgmr0II3ec6aUMcbe0EHYlcExYTWEjv-2Fm-2FHt1jtoP5r0dgiLOP-2BxY5cgnjSI0L2QbvlT3yhOgAtnVJhqAcw8a4-3D&amp;source=gmail&amp;ust=1623380898827000&amp;usg=AFQjCNGqElMrsFM6MXSTUB1UeAxFcDL82A">@discord</a>.<br>
                                                        Want to give us feedback? Let us know what you think on our <a
                                                            href="https://url9624.discordapp.com/ls/click?upn=qDOo8cnwIoKzt0aLL1cBeGtifxhyb-2FEeTgeN31uAkBS2ZTvlNepPcLUnXgSC4-2BGKDJZ5_av9jLgVz1hP-2FL23lkyqaU7Iw5z8d9cjUxeAc64zG-2BCrkrwGzXJ0UvMvbPbh0CuPQ6TPLy9Qw8RLDdQqa-2FGwL6WJ8SBN1HwsACYgJU0ZE50Kkvc-2FIGtT3tspc5SN4pHdHBIV8MtzgM-2BrnV3KjlcRIWn4vrC8B-2B9ksewMuGYtz4X6GydIKgiWPWq5422hkh0NSDjiMtG6Oeczuo8aO2aeOHslFx7hJ8Xw-2FoHl-2Bo9RvsZ0-3D"
                                                            style="font-family:Whitney,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;color:#7289da"
                                                            target="_blank"
                                                            data-saferedirecturl="https://www.google.com/url?q=https://url9624.discordapp.com/ls/click?upn%3DqDOo8cnwIoKzt0aLL1cBeGtifxhyb-2FEeTgeN31uAkBS2ZTvlNepPcLUnXgSC4-2BGKDJZ5_av9jLgVz1hP-2FL23lkyqaU7Iw5z8d9cjUxeAc64zG-2BCrkrwGzXJ0UvMvbPbh0CuPQ6TPLy9Qw8RLDdQqa-2FGwL6WJ8SBN1HwsACYgJU0ZE50Kkvc-2FIGtT3tspc5SN4pHdHBIV8MtzgM-2BrnV3KjlcRIWn4vrC8B-2B9ksewMuGYtz4X6GydIKgiWPWq5422hkh0NSDjiMtG6Oeczuo8aO2aeOHslFx7hJ8Xw-2FoHl-2Bo9RvsZ0-3D&amp;source=gmail&amp;ust=1623380898827000&amp;usg=AFQjCNGGgA4WPpC4yOpWcZL5KCJP9Tw_3w">feedback
                                                            site</a>.</p>

                                                </div> -->
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        </body>

        </html>
        """.format(user.username, url)

        sender = {"name": "ADMIN_LISA", "email": '*****@*****.**'}
        to = [{"email": user.email, "name": user.username}]
        #reply_to = {"email":'*****@*****.**',"name":'ADMIN_LISA'}#{"email":"*****@*****.**","name":"John Doe"}
        headers = {"Some-Custom-Name": "unique-id-1234"}
        params = {"parameter": "My param value", "subject": "New Subject"}
        send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
            to=to,
            headers=headers,
            html_content=html_content,
            sender=sender,
            subject=subject)

        try:
            api_response = api_instance.send_transac_email(send_smtp_email)
            pprint(api_response)
        except ApiException as e:
            print("Exception when calling SMTPApi->send_transac_email: %s\n" %
                  e)
コード例 #26
0
from __future__ import print_function
import time
import datetime
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from pprint import pprint

configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = 1

# create an instance of the API class
api_instance = sib_api_v3_sdk.ContactsApi(
    sib_api_v3_sdk.ApiClient(configuration))
create_contact = sib_api_v3_sdk.CreateContact(
    email='*****@*****.**',
    list_ids=[3])  # CreateContact | Values to create a contact

try:
    # Create a contact
    api_response = api_instance.create_contact(create_contact)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling ContactsApi->create_contact: %s\n" % e)

configuration = sib_api_v3_sdk.Configuration()
configuration.api_key[
    'api-key'] = "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"

api_instance = sib_api_v3_sdk.EmailCampaignsApi(
    sib_api_v3_sdk.ApiClient(configuration))
campaign_id = 1
コード例 #27
0
 def __init__(self, email):
     self.email = email
     self.cfg = sib.Configuration()
     self.cfg.api_key['api-key'] = mykey.SIB_API_KEY
     self.instance = (sib.ContactsApi(sib.ApiClient(self.cfg)))
     self._get_contact()
コード例 #28
0
 def connect(self, api_key):
     """Create client"""
     configuration = sib_api_v3_sdk.Configuration()
     configuration.api_key["api-key"] = api_key
     client = sib_api_v3_sdk.ApiClient(configuration)
     return client
コード例 #29
0
 def __init__(self):
     configuration = sib_api_v3_sdk.Configuration()
     configuration.api_key["api-key"] = settings.SENDINBLUE_API_KEY
     self.api_instance = sib_api_v3_sdk.TransactionalSMSApi(
         sib_api_v3_sdk.ApiClient(configuration))