Exemplo n.º 1
0
def suscripcion(request):
    if request.method == "POST":
        email = request.POST['email']

        mailchimp = Client()
        mailchimp.set_config({
            "api_key": api_key,
            "server": server,
        })

        member_info = {
            "email_address": email,
            "status": "subscribed",
        }

        try:
            response = mailchimp.lists.add_list_member(list_id, member_info)
            messages.success(request, "Email recibido. ¡Gracias! ")
            asunto = "Suscripción"
            mensaje = "Gracias por suscribirte a nuestro boletin"
            remitente = "*****@*****.**"
            destinatario = email
            send_mail(asunto, mensaje, remitente, [destinatario])
        except ApiClientError as error:
            print(error.text)
            messages.success(request, "Hubo un problema. Intentelo más tarde")
    
    return render(request, "marketing/email_sus.html")
Exemplo n.º 2
0
    def __init__(self):
        self.audience_id = 'c6e22b46fd'
        self.interest_category_id = 'interests-9872b92779'
        self.segement_field_id = 'interests-ddaa47f9ce'
        self.trello_token = os.environ['TRELLO_TOKEN']
        self.trello_key = os.environ['TRELLO_API_KEY']
        self.mailchimp_key = os.environ['MAILCHIMP_API_KEY']
        self.never_bouce_apy_key = os.environ['NB_APY_KEY']
        self.mailchimp_client = Client()
        self.mailchimp_client.set_config({"api_key": self.mailchimp_key})
        self.trello = TrelloApi(self.trello_key, self.trello_token)
        self.trello.set_token(self.trello_token)
        self.markdown2html = Markdown()

        self.segments = {
            'ruby':
            '55eaa52f81',
            'python':
            'febbd795e0',
            'javascript (backend/node/meteor)':
            'dd8317b5bb',
            'php':
            '804ccb1e24',
            'mobile':
            'c71d0c8111',
            'javascript (frontend/angular/react/vue)':
            '9d6ae89058',
            'interaction design (web design/mobile design/ui/ux)':
            'b7205a2deb',
            'graphic design (branding/logos/animations/illustrations)':
            'b00fcf9a76'
        }
Exemplo n.º 3
0
def test():
    from snapflow_mailchimp import module as snapflow_mailchimp

    api_key = ensure_api_key()
    server = api_key.split("-")[
        -1]  # Hack? appears to be true for new api keys
    mailchimp = Client()
    mailchimp.set_config({
        "api_key": api_key,
        "server": server,
    })
    # delete_list(mailchimp, "9311ebcf06")
    list_id = create_test_list(mailchimp)

    try:
        g = graph()
        members_df = pd.DataFrame.from_records([
            dict(
                email_address="*****@*****.**",
                status="subscribed",
                merge_fields={"f1": "v1"},
            ),
            dict(
                email_address="*****@*****.**",
                status="subscribed",
                merge_fields={"f1": "v2"},
            ),
            dict(
                email_address="*****@*****.**",
                status="subscribed",
                merge_fields={"f1": "v3"},
            ),
        ])

        # Initial graph
        import_df = g.create_node(
            "core.import_dataframe",
            params={
                "dataframe": members_df,
                "schema": "MailchimpMember"
            },
        )
        export_aud = g.create_node(
            snapflow_mailchimp.functions.export_audience,
            input=import_df,
            params={
                "api_key": api_key,
                "list_id": list_id,
                "server": server
            },
        )
        # logger.enable("snapflow")
        produce(export_aud,
                execution_timelimit_seconds=5,
                modules=[snapflow_mailchimp])
        response = mailchimp.lists.get_list_members_info(list_id)
        assert len(response["members"]) == len(members_df)
    finally:
        delete_list(mailchimp, list_id)
Exemplo n.º 4
0
 def __init__(self):
     client = Client()
     client.set_config({
         'api_key': self.api_key,
         # https://us19.admin.mailchimp.com/...
         'server': get_mail_chimp_server_key()
     })
     self.client = client
Exemplo n.º 5
0
def get_mailchimp_client():
    key = get_mail_chimp_api_key()
    server = get_mail_chimp_server_key()

    client = Client()
    client.set_config({
        'api_key': key,
        # https://us19.admin.mailchimp.com/...
        'server': server
    })
    return client
Exemplo n.º 6
0
def mailchimp_add_user(request, user, **kwargs):
    """Adds user email to MailChimp"""
    mailchimp = Client()
    mailchimp.set_config({
        'api_key': keys.MAILCHIMP_KEY,
        'server': MAILCHIMP_SERVER
    })

    try:
        member_info = {'email_address': user.email, 'status': 'subscribed'}
        mailchimp.lists.add_list_member(MAILCHIMP_LIST_ID, member_info)
    except Exception as error:
        sentry.log_error(error, message=error.text)
Exemplo n.º 7
0
def get_client(mailchimp_api_key, mailchimp_server):
    """Creates a MailChimp client instance.
    
    Args:
    mailchimp_api_key: Mailchimp api key, you can set this up in your mailchimp account.
    mailchimp_server: Mailchimp server, found in your account url.
    
    Returns:
    client: Mailchimp client"""
    client = Client()
    client.set_config(
        {"api_key": mailchimp_api_key, "server": mailchimp_server}
    )
    return client
Exemplo n.º 8
0
def unsubscribe(email):
    mailchimp = Client()
    mailchimp.set_config({
    "api_key":  api_key,
    "server": server
    })
    member_info = {
        "email_address": email,
        "status": "subscribed",
    }
    try:
        response = mailchimp.lists.delete_list_member(list_id,email)
        print("response: {}".format(response))
    except ApiClientError as error:
        print("An exception occurred: {}".format(error.text))
Exemplo n.º 9
0
 def subscribe_email(email):
     """
     This function will communicate with mailchimp api
     to create a member in an audience list
     """
     mailchimp = Client()
     mailchimp.set_config({
         "api_key": MAILCHIMP_API_KEY,
         "server": MAILCHIMP_DATA_CENTER
     })
     member_info = {
         "email_address": email,
         "status": "subscribed",
     }
     try:
         mailchimp.lists.add_list_member(MAILCHIMP_LIST_ID, member_info)
     except ApiClientError as error:
         print(error.text)
Exemplo n.º 10
0
def export_audience(
    members: DataBlock[MailchimpMember], api_key: str, server: str, list_id: str,
):
    mailchimp = Client()
    mailchimp.set_config(
        {"api_key": api_key, "server": server,}
    )
    member_records = members.as_records()
    for record in member_records:
        member = {
            k: record.get(k)
            for k in ["email_address", "status", "merge_field"]
            if record.get(k) is not None
        }
        if "status" not in member:
            member["status"] = "subscribed"
        try:
            response = mailchimp.lists.add_list_member(list_id, member)
        except ApiClientError as e:
            # TODO: emit bad row? Error? ctx.emit("error", row) or collect and at end ctx.emit("error", error_records)
            logger.error(f"Mailchimp error: {e.text} ({e.status_code})")
Exemplo n.º 11
0
def subscribe(email):
    """
    Contains code handling the communication to the mailchimp api
    to create a contact/member in an audience/list.
    """

    mailchimp = Client()
    mailchimp.set_config({
        "api_key": api_key,
        "server": server,
    })

    member_info = {
        "email_address": email,
        "status": "subscribed",
    }

    try:
        response = mailchimp.lists.add_list_member(list_id, member_info)
        print("response: {}".format(response))
    except ApiClientError as error:
        print("An exception occurred: {}".format(error.text))
Exemplo n.º 12
0
    def __init__(self, bot, api_key, list_id, logger):
        """Init cog and connect to Mailchimp.

        Args:
            bot: Bot object that registered this cog.
            api_key: String representing Mailchimp API key.
            list_id: String representing Mailchimp list ID.
            logger: Logger for this cog.
        """
        self.bot = bot
        self.client = client = Client({"api_key": api_key})
        self.list_id = list_id
        self.logger = logger
def submit_to_mailchimp(email):
    """
    Adds email as contact on MailChimp audience/list via MailChimp API
    """
    mailchimp = Client()
    mailchimp.set_config({
        "api_key": API_KEY,
        "server": API_DATACENTER,
    })

    member_info = {
        "email_address": email,
        "status": "subscribed",
    }

    try:
        response = mailchimp.lists.add_list_member(API_LIST_ID, member_info)
        print("response: {}".format(response))
    except ApiClientError as error:
        response = {"status": error.text}
        print("An exception occurred: {}".format(error.text))

    return response
Exemplo n.º 14
0
        print(f'This update: {current_datetime}')
        print(f'Updated "{last_update_filename}"')

    if len(new_members) < 1:
        print('No new members to update!')
        exit()

    # Extract only emails
    new_emails = [member['email'] for member in new_members]

    # Make the correct body for Mailchimp
    member_body = [{
        "email_address": email,
        "status": "subscribed"
    } for email in new_emails]

    print('Updating members:')
    pprint(new_emails)

    try:
        mailchimp = Client()
        mailchimp.set_config(mc_cred_data)

        list_id = "dd02c68798"
        body_params = {"members": member_body, "update_existing": False}

        response = mailchimp.lists.batch_list_members(list_id, body_params)
        pprint(response)
    except ApiClientError as error:
        print(f"Error: {error.text}")
Exemplo n.º 15
0
from mailchimp_marketing import Client
from mailchimp_marketing.api_client import ApiClientError
import os
from datetime import datetime, timedelta

api_key = os.environ.get('MAILCHIMP_API_KEY')

mailchimp = Client()
mailchimp.set_config({
  "api_key": api_key,
  "server": "us2"
})
list_id = os.environ.get('MAILCHIMP_LIST_ID')


def subscribe_or_unsubscribe(email_list):
    members_data = []

    for email in email_list:
        member_email = email["email"]
        members_status = "subscribed" if email["is_subscribed"] else "unsubscribed"
        members_data.append({"email_address" : member_email, "status" : members_status})

    try:
        mailchimp.lists.batch_list_members(list_id, {"members": members_data, "update_existing" : True})
    except ApiClientError as error:
        print(f"Error: {error.text}")



def create_email_template(jobs_data):
Exemplo n.º 16
0
from pathlib import Path
from mailchimp_marketing import Client

# print(Path('mailchimp.apikey').read_text())

mailchimp = Client()
mailchimp.set_config({
  "api_key": Path('mailchimp.apikey').read_text().replace('\n',''),
  "server": "us5"
})

response = mailchimp.ping.get()
print(response)

except ApiClientError as error:
  print(error)
def sendNewsletter(items, newsletter_type):
    subject = datetime.now().strftime("MuMaNews - CW %V")
    title = "%s %s" % (datetime.now().strftime("%Y-%V"), newsletter_type)
    try:
        client = Client()
        client.set_config({
            "api_key": config.mailchimp_api_key,
            "server": config.mailchimp_server
        })

        response = client.campaigns.create({
            "type": "regular",
            "recipients": {
                "list_id": config.mailchimp_list_id
            },
            "settings": {
                "template_id": config.mailchimp_template_id,
                "subject_line": subject,
                "title": title,
                "from_name": config.MAIL_FROM_NAME,
                "reply_to": config.MAIL_FROM
            }
        })
        # print(response)
        campaign_id = response["id"]
        debug_out("Mailchimp Campaign: %s / %s" %
                  (campaign_id, response["web_id"]))

        response = client.campaigns.get_content(campaign_id)
        soup = BeautifulSoup(response["html"], "html.parser")

        template_elem_src = soup.find(string="%TITLE%").find_parent(
            class_="mcnTextBlock")

        template_txt = str(template_elem_src)
        output = []
        for item in items:
            txt = template_txt.replace("%TITLE%", item.name)
            txt = txt.replace(
                "%CONTENT%",
                markdown.markdown(
                    item.description,
                    extensions=[GithubFlavoredMarkdownExtension()]))
            output.append(txt)
        new_elem = BeautifulSoup("".join(output), "html.parser")

        template_elem_src.replace_with(new_elem)

        response = client.campaigns.set_content(campaign_id,
                                                {"html": str(soup)})

        if newsletter_type == "preview":
            response = client.campaigns.send_test_email(
                campaign_id, {
                    "test_emails": [config.MAIL_TO_PREVIEW],
                    "send_type": "html"
                })
            debug_out(str(response))
        else:
            response = client.campaigns.send(campaign_id)
            debug_out(str(response))

    except ApiClientError as error:
        print("Error: {}".format(error.text))
Exemplo n.º 18
0
class MailChimpCampaignCreator(object):
    def __init__(self):
        self.audience_id = 'c6e22b46fd'
        self.interest_category_id = 'interests-9872b92779'
        self.segement_field_id = 'interests-ddaa47f9ce'
        self.trello_token = os.environ['TRELLO_TOKEN']
        self.trello_key = os.environ['TRELLO_API_KEY']
        self.mailchimp_key = os.environ['MAILCHIMP_API_KEY']
        self.never_bouce_apy_key = os.environ['NB_APY_KEY']
        self.mailchimp_client = Client()
        self.mailchimp_client.set_config({"api_key": self.mailchimp_key})
        self.trello = TrelloApi(self.trello_key, self.trello_token)
        self.trello.set_token(self.trello_token)
        self.markdown2html = Markdown()

        self.segments = {
            'ruby':
            '55eaa52f81',
            'python':
            'febbd795e0',
            'javascript (backend/node/meteor)':
            'dd8317b5bb',
            'php':
            '804ccb1e24',
            'mobile':
            'c71d0c8111',
            'javascript (frontend/angular/react/vue)':
            '9d6ae89058',
            'interaction design (web design/mobile design/ui/ux)':
            'b7205a2deb',
            'graphic design (branding/logos/animations/illustrations)':
            'b00fcf9a76'
        }

    def get_cards_to_send(self):
        return self.trello.lists.get_card('5bb1e965e5336c5390e7e505')

    def create_campaigns(self, trello_cards, in_flask=False):
        for card in trello_cards:
            if self.validate_links(card) and self.validate_email(card):
                segments = self.get_list_segments(card)
                data_dict = {}
                data_dict['type'] = 'regular'
                data_dict['content_type'] = 'multichannel'
                data_dict["recipients"] = {
                    'list_id': self.audience_id,
                    'segment_opts': {
                        'match': 'any'
                    }
                }
                # Here is a stack overflow link explaining how to
                # create dynamic segments because the mailchimp api docs
                # doesn't explain how to do it
                # #https://stackoverflow.com/questions/35785278/create-campaign-with-dynamic-segment-using-mailchimp-api-v3-0

                data_dict["recipients"]['segment_opts']['conditions'] = [{
                    "condition_type":
                    "Interests",
                    'op':
                    'interestcontains',
                    'field':
                    self.interest_category_id,
                    'value':
                    segments
                }]

                data_dict['settings'] = {
                    "title": card['name'],
                    "subject_line": card['name'],
                    "from_name": "FeastFlow",
                    "reply_to": '*****@*****.**'
                }
                screenshot_url = self.get_screenshot(card, in_flask)

                if screenshot_url:
                    html = premium_w_screenshot
                else:
                    html = premium_no_screenshot

                html.encode('utf-8')
                html = html.replace("%IMAGE%", screenshot_url)
                html = html.replace("%TITLE%", card['name'])
                html = html.replace("%CONTENT%", self.get_card_content(card))

                # campaign = self.mailchimp_client.campaigns
                campaign = self.mailchimp_client.campaigns.create(data_dict)
                # campaign.content.get(campaign.campaign_id)
                self.mailchimp_client.campaigns.set_content(
                    campaign['id'], {'html': html})
                # campaign.content.update(
                #     campaign.campaign_id, {'html': html})

                # Old code that would schedule a campaign for the free list
                # if card['badges']['checkItemsChecked'] == 1:
                #     checkedItems = self.trello.checklists.get_checkItem(
                #         card['idChecklists'][0])

                #     # get date to send
                #     time_str = checkedItems[0]['name'].lower().strip('send on ')
                #     mdy = time_str.split('/')

                #     # set for 6pm est on date given
                #     schedule_time = datetime(
                #         int(mdy[2]), int(mdy[0]), int(mdy[1]), 17)

                #     local = pytz.timezone ("America/Atikokan")
                #     local_dt = local.localize(schedule_time, is_dst=None)
                #     utc_schedule_time = local_dt.astimezone(pytz.utc)

                #     free_campaign = self.mailchimp_client.campaigns
                #     data_dict['type'] = 'regular'
                #     data_dict['recipients'] = {'list_id': self.free_list_id}
                #     free_campaign.create(data_dict)
                #     free_campaign.content.get(campaign.campaign_id)
                #     free_campaign.content.update(
                #         free_campaign.campaign_id, {'html': html})

                #     free_campaign.actions.schedule(
                #         free_campaign.campaign_id,
                #         {'schedule_time': utc_schedule_time})

    def get_list_segments(self, trello_card):

        segments = []
        for label in trello_card['labels']:
            segments.append(self.segments[label['name'].lower()])

        return segments

    def get_screenshot(self, trello_card, in_flask=False):
        attachment = self.trello.cards.get_attachment(trello_card['id'])

        try:
            # if an attachment exists and its an image
            # do not get a screenshot
            if attachment[0]["url"][-3] == 'png':
                return attachment[0]["url"]
            else:
                # if its not an image then raise a key error so
                # we can hit the exception below and get a screenshot
                raise KeyError
        except (KeyError, IndexError):
            try:
                url_regex = r'URL: <https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)>'
                url = re.search(
                    url_regex,
                    str(trello_card['desc'].encode('utf-8'))).group()
                url = url.strip('URL: <')
                url = url.strip('>')
                if in_flask:
                    chrome_options = Options()
                    chrome_options.binary_location = \
                        os.environ['GOOGLE_CHROME_BIN']
                    chrome_options.add_argument('--disable-gpu')
                    chrome_options.add_argument('--no-sandbox')
                    chrome_options.add_argument('--headless')
                    chrome_options.add_argument('--disable-dev-shm-usage')
                    driver = webdriver.Chrome(executable_path=str(
                        os.environ.get('CHROMEDRIVER_PATH')),
                                              chrome_options=chrome_options)
                else:
                    driver = webdriver.Chrome(chrome_driver_path)
                driver.get(url)
                time.sleep(3)  # wait for page to load
                driver.save_screenshot('lead_screenshot.png')
                driver.quit()

                # resize image
                with open('lead_screenshot.png', 'r+b') as f:
                    with Image.open(f) as image:
                        img = resizeimage.resize_width(image, 600)
                        img.save('lead_screenshot.png', image.format)

                ss_path = os.path.abspath('lead_screenshot.png')
                self.upload_file_to_trello_card(trello_card['id'], ss_path)
                os.remove(ss_path)

                return self.trello.cards.get_attachment(
                    trello_card['id'])[0]["url"]

            except AttributeError:
                card_name = trello_card['name'].encode('utf-8')
                print(f'Failed to get screenshot for {card_name}')
                return ''

    def get_card_content(self, trello_card):
        return self.markdown2html.convert(trello_card['desc'])

    def upload_file_to_trello_card(self, card_id, file_path):
        """
            Upload a local file to a Trello card as an attachment.
            File must be less than 10MB (Trello API limit).
            :param card_id: The relevant card id
            :param file_path: path to the file to upload
            Returns a request Response object. It's up to you to check the
                status code.
            """
        ATTACHMENTS_URL = 'https://api.trello.com/1/cards/%s/attachments'

        params = {'key': self.trello_key, 'token': self.trello_token}
        files = {'file': open(file_path, 'rb')}
        url = ATTACHMENTS_URL % card_id
        requests.post(url, params=params, files=files)

    def validate_links(self, trello_card):
        url_regex = r'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)'
        links = re.finditer(url_regex,
                            str(trello_card['desc'].encode('utf-8')))
        for link in links:
            try:
                request = requests.get(link.group(0))
            except ConnectionError:
                self.__move_card_to_broken_link_column(trello_card)
                return False

            if request.status_code in [200, 403, 999, 406]:
                continue
            else:
                self.__move_card_to_broken_link_column(trello_card)
                card_name = trello_card['name'].encode('utf-8')
                print(
                    f"Broken Link in {card_name} with status code {request.status_code}: {link.group(0)}"
                )
                return False
        return True

    def validate_email(self, trello_card):
        zb.initialize(os.environ.get('ZB_API_KEY'))

        # client = neverbounce_sdk.client(api_key=self.never_bouce_apy_key)
        email_regex = r'[\w\.-]+@[\w\.-]+'
        emails = re.findall(email_regex,
                            str(trello_card['desc'].encode('utf-8')))
        for address in emails:
            if not address[-1].isalpha():
                address = address[:-1]
            resp = zb.validate(address)
            # resp = client.single_check(address)

            if resp.status not in [ZBValidateStatus.valid]:
                self.__move_card_to_broken_link_column(trello_card)
                card_name = trello_card['name']
                print(
                    f"Email Bounced in {card_name}: {address} with return code '{resp.status}"
                )
                return False

        return True

    def __move_card_to_broken_link_column(self, trello_card):
        # move card to broken link column
        self.trello.cards.update_idList(trello_card['id'],
                                        "5c55ae09f1d4eb1efb039019")
import hashlib
from mailchimp_marketing import Client

mailchimp = Client()
mailchimp.set_config({
    "api_key": "YOUR_API_KEY",
    "server": "YOUR_SERVER_PREFIX"
})

list_id = 'YOUR_LIST_ID'

subscriber_email = "*****@*****.**"
subscriber_hash = hashlib.md5(subscriber_email.lower().encode()).hexdigest()

response = mailchimp.lists.get_list_member_events(list_id, subscriber_hash)
total_items = response['total_items']
print(f'We have created {total_items} events for this user.')