Git Product home page Git Product logo

mailerlite-api-python's Introduction

⚠️⚠️⚠️⚠️⚠️ WARNING ⚠️⚠️⚠️⚠️⚠️ : This REPO is no longer maintained in favor of the official mailerlite python client look here

Mailerlite-api-python

Python Wrapper for Mailerlite API

Deployment pypi mailerlite
Build Status
Metrics codacy mailerlite python
License bsd
Community

Getting Started

Installation

This client is hosted at PyPi under the name mailerlite-api-python, to install it, simply run

pip install mailerlite-api-python

or install dev version:

git clone https://github.com/skoudoro/mailerlite-api-python.git
pip install -e .

Method reference

For the complete reference, visit the official MailerLite API reference.

Notes

This version is handling the V2_BETA API (classic version).

we are currently updating the project to handle the new V2 released last summer 2022.

Examples

Initialization

First, Grab YOUR_API_KEY from your Mailerlite account (Profile > Integrations > Developer Api).

>>> from mailerlite import MailerLiteApi
>>> api = MailerLiteApi('YOUR_API_KEY')

A second option is to define an environment variable named MAILERLITE_PYTHON_API_KEY. Then, you do not need to precise it in your code:

>>> from mailerlite import MailerLiteApi
>>> api = MailerLiteApi()

Campaigns

Get all campaigns or a specific one

>>> all_campaigns = api.campaigns.all()
>>> draft = api.compaings.all(status='draft')

Modify a campaign

>>> one_campaign = all_campaigns[0]
>>> html = '<head></head><body><h1>Title</h1><p>Content</p><p><small><a href=\"{$unsubscribe}\">Unsubscribe</a></small></p></body>'
>>> plain = "Your email client does not support HTML emails. "
>>> plain += "Open newsletter here: {$url}. If you do not want"
>>> plain += " to receive emails from us, click here: {$unsubscribe}"

>>> api.campaigns.update(one_campaign.id, html=html, plain=plain)

Create / Delete a campaign

>>> data = {"subject": "Regular campaign subject",
            "name": "Regular campaign name",
            "groups": [2984475, 3237221],
            "type": "regular"}
>>> api.campaigns.create(data)
>>> api.campaigns.delete(campaign_id=3971635)

Send a campaign

>>> data = {"subject": "Regular campaign subject",
            "name": "Regular campaign name",
            "groups": [2984475, 3237221],
            "type": "regular"}
>>>
>>> _, res = api.campaigns.create(data)
>>> campaign_id = res['id']
>>>
>>> html = '<head></head><body><h1>Your Title</h1><p>Your Content</p><p><small>'
>>> html += '<a href=\"{$unsubscribe}\">Unsubscribe</a></small></p></body>'
>>> plain = "Your email client does not support HTML emails. "
>>> plain += "Open newsletter here: {$url}. If you do not want"
>>> plain += " to receive emails from us, click here: {$unsubscribe}"
>>>
>>> api.campaigns.update(campaign_id, html=html, plain=plain)
>>> api.campaigns.send(campaign_id)

Cancel a scheduled campaign

>>> outbox_campaigns = campaign_obj.all(status='outbox', limit=5)
>>> selected_campaign = outbox_campaigns[0]
>>>
>>> api.campaigns.cancel(selected_campaign.id)

count campaign

>>> api.campaigns.count()
>>> api.campaigns.count(status='draft')

Subscribers

Get all subscribers

>>> api.subscribers.all()
>>> api.subscribers.all(stype='active')
>>> api.subscribers.active()
>>> api.subscribers.unsubscribed()
>>> api.subscribers.bounced()
>>> api.subscribers.junk()
>>> api.subscribers.unconfirmed()

Get one subscriber

>>> api.subscribers.get(email='[email protected]')
>>> api.subscribers.get(id=1343965485)

search

>>> api.subscribers.search(search='[email protected]')

subscribers groups

>>> api.subscribers.groups(id=1343965485)

subscribers activity

>>> api.subscribers.activity(id='1343965485')
>>> api.subscribers.activity(id='1343965485', limit=50, offset=1, atype='clicks')

Create subscriber

>>> data = {'name': 'John',
            'email': '[email protected]',
            'fields': {'company': 'MailerLite'}
            }
>>> api.subscribers.create(data)

Update subscriber

>>> data = {'name': 'John',
            'fields': {'company': 'MailerLite'}
            }
>>> api.subscribers.update(data, id='1343965485')

Count subscribers

Get the total count of all subscribers in a single call.

Please, be aware that this is not a documented feature in the official API.

>>> api.subscribers.count()

Groups

Get all Groups

>>> api.groups.all()
>>> api.groups.all(limit=50)
>>> api.groups.all(offset=10)
>>> api.groups.all(gfilters='My Group')
>>> api.groups.all(group_id=12345)

Create a Group

>>> api.groups.create(group_id=12345, name='My New Group')

Rename a Group

>>> api.groups.update(group_id=12345, name='New Name')

Get a Group

>>> api.groups.get(group_id=12345)

Delete a Group

>>> api.groups.delete()
>>> api.groups.delete(group_id=12345)

Get all subscribers in a Group

>>> api.groups.subscribers(group_id=12345)
>>> api.groups.subscribers(group_id=12345, limit=50, offset=1)
>>> api.groups.subscribers(group_id=12345, stype='active')

Get one subscriber from a Group

>>> api.groups.subscriber(group_id=12345, subscriber_id=54321)

Add list of subscribers to a Group

This method calls the import endpoint https://developers.mailerlite.com/reference#add-many-subscribers

>>> api.groups.add_subscribers(group_id=12345, subscribers_data=[{"email": "[email protected]", "name": "John Wick"}], autoresponders=False, resubscribe=False, as_json=False)

subscriber_data argument accepts a list of dictionaries or just one dictionary containing the subscriber name and email

Add a single subscriber to a Group

This method calls the add single subscriber endpoint https://developers.mailerlite.com/reference#add-single-subscriber

>>> api.groups.add_single_subscriber(group_id=12345, subscribers_data={"email": "[email protected]", "name": "John Wick" ...}, autoresponders=False, resubscribe=False, as_json=False)

Unlike the method above, this adds only one subscriber to a group. The subscriber_data argument accepts all subscriber attributes. Check available attributes on https://developers.mailerlite.com/reference#create-a-subscriber

Delete one subscriber from a Group

>>> api.groups.delete_subscriber(group_id=12345, subscriber_id=54321)

Segments

Get list of Segments

>>> api.segments.all()

Get count of Segments

>>> api.segments.count()

Fields

Get list of Fields

>>> api.fields.all()

Get one Field

>>> api.fields.get(field_id=123456)

Create / update / delete one Field

>>> api.fields.create(title="my custom title")
>>> api.fields.update(field_id=123456, title="my new title 2")
>>> api.fields.delete(field_id=123456)

Webhooks

Get list of Webhooks

>>> api.webhooks.all()

Get one webhook

>>> api.webhooks.get(webhook_id=123456)

Create/update/delete one webhook

>>> api.webhooks.create(url="https://yoursite/script-is-here",
...                     event="subscriber.create")
>>> api.webhooks.update(webhook_id=123456,
...                     url="https://yoursite/script-is-here",
...                     event="subscriber.create")
>>> api.webhooks.delete(webhook_id=123456)

Account

# Get some info or stats
>>> api.account.info()
>>> api.account.stats()
>>> api.account.double_optin()
# Set up the double_optin
>>> api.account.set_double_optin(True)

Batch

>>> batch_requests = {"requests": [{"method":"GET",
...                                 "path": "/api/v2/groups"
...                                 },
...                                 {"method":"POST",
...                                  "path": "/api/v2/groups",
...                                  "body": {"name": "New group"}
...                                 }
...                                 ]
...                    }
>>> api.batch(batch_requests)

Tests

  • Step 1: Install pytest
  pip install pytest
  • Step 2: Run the tests
  pytest -svv mailerlite

Contribute

We love contributions!

You've discovered a bug or something else you want to change - excellent! Create an issue!

You've worked out a way to fix it – even better! Submit a Pull Request!

Start with the contributing guide!

License

Project under 3-clause BSD license, more informations here

mailerlite-api-python's People

Contributors

codacy-badger avatar naishy avatar rsoltys avatar santigz avatar skoudoro avatar vitormorales avatar zainrizvi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mailerlite-api-python's Issues

No webform_subscribe_date on subscribers post response

I got this error creating new subscribers.

return Subscriber(**res_json) TypeError: <lambda>() got an unexpected keyword argument 'webform_subscribe_date'

mailerlite/group.py in add_single_subscriber at line 248

I checked the docs right now and nothing about this. I would say they removed the webform_subscribe_date attr

GH actions to publish release

When I find the time, it would be good to have a GitHub action for publishing release after pushing a tag

It should facilitate maintenance.

Update unittest

Need to update unittest for all modules. every module needs its own PR

  • github action windows / linux / mac
  • account module
  • api module
  • campaign module
  • client module
  • field module
  • group module
  • segment module
  • subscriber module
  • webhook module

Do you have any doc about groups?

Hi,

first of all, thank you for your work. It should be useful for my startup.
Do you have any documentation about the group feature? Or maybe you still didn't develop anything regarding the groups?

Let me explain you my needs, you may redirect me to the good solution.

I am developing a saas business.

  1. When users didn't use at all my software, I would like to send them a series of mails. So I should create an automation series of mail for a specific group. Let's call this group "NON INSTALL GROUP".
    And then, when my software will detect a user didn't use it at all, it will add this user in this specific group : "NON INSTALL GROUP"
    If the user used my software, it will check if user is in this group and remove him/her.

  2. When users didn't use since a long time my software, I would like to send them a series of mails. So I should create an automation series of mail for a specific group. Let's call this group "NOT USED SINCE LONG TIME GROUP".
    And then, when my software will detect a user didn't use since a long time, it will add this user in this specific group : "NOT USED SINCE LONG TIME GROUP"
    If the user used my software, it will check if user is in this group and remove him/her.

I think you get the idea of my specific needs. It is important for the retention of my saas. And RETENTION is king in SAAS business. It is very important.

Maybe there is another way to do what I need?

Kind regards

campaign_name is missing in Activity

Recently, Mailerlite API has been changed and I got this exception:

 File "src/mailerlite-api-python/mailerlite/subscriber.py", line 409, in <listcomp>
    all_activities = [Activity(**res) for res in res_json]
TypeError: __new__() got an unexpected keyword argument 'campaign_name'

MailerLite doesn't allow to update the email

Hi, I've tried your example on how to update a subscriber profile, but I realized it's not possible to use the email field.

Reading MailerLite's documentation, they suggest creating a new subscriber when the email changes.

Is that right?

data = {'name': 'John', 'email': '[email protected]', 'fields': {'company': 'MailerLite'} } api.subscribers.update(data, id='1343965485')

Endless 'sending' status

I try to use the script from README, it seems that Mailerlite receives it and starts to build a campaign, but nothing happens. There is a 'sending' status in the admin panel, but still no mail on the inbox. Am I missing something?

from mailerlite import MailerLiteApi
api = MailerLiteApi('mailerlite-api-key')

data = {"subject": "Regular campaign subject",
        "name": "Regular campaign name",
        "groups": [GroupID],
        "type": "regular"}

_, res = api.campaigns.create(data)
campaign_id = res['id']

html = '<head></head><body><h1>Your Title</h1><p>Your Content</p><p><small>'
html += '<a href=\"{$unsubscribe}\">Unsubscribe</a></small></p></body>'
plain = "Your email client does not support HTML emails. "
plain += "Open newsletter here: {$url}. If you do not want"
plain += " to receive emails from us, click here: {$unsubscribe}"

api.campaigns.update(campaign_id, html=html, plain=plain)
api.campaigns.send(campaign_id)

2022-01-31_14-57-40

Undefined "MailerLiteApi"

Hello team,

I just install mailerlite-api with pip3 on python version 3.8.6. But I got undefined "MailerLiteApi" as the screenshot.

thanks.
Screenshot (289)

Adding to a group throws an exception

When trying to add a subscriber to a group, if you don't use as_json=True then it throws an exception because it tries and convert the full response to a Subscriber when the response returned by MailerLite is different dict (imported, updated, unchanged, errors

Here is the code that fails:

data = {
            'email': request.user.email,
}
result = api.groups.add_subscribers(group_id, [data])

And the exception I get

  File ".../.venv/lib/python3.8/site-packages/mailerlite/group.py", line 206, in add_subscribers
    return Subscriber(**res_json)

Performance suggestion

Thanks for making this library!

FWIW, I think it's good Python practice to not execute remote calls upon instantiating a new object. In this case, creating an API object will run 7 identical calls to /api/v2/stats via client.check_headers().

Ability to fetch a subscribers status in a group?

Hi,

Love this package, its very useful so thanks for your hard work.

I was looking thru the API this package provides, but cannot see a way to fetch a subscribers status in a group (eg: active, unsubscribed, unconfirmed, bounced, junk). Just wondering if you know of how to do this, looking at both V1 & V2 API docs, its very unclear if this is even possible from mailerlite's API.

Cheers

Mailerlite does not send mail with "sending..."

Code for creating campaigns and sending mail by running campaigns.

from mailerlite import MailerLiteApi
from pprint import pprint
import time

api = MailerLiteApi('******************')

data = {"subject": "Regular campaign subject",
            "name": "Regular campaign name",
            "groups": [111509512],
            "type": "regular"}
_, res = api.campaigns.create(data)
campaign_id = res['id']

html = '<head></head><body><h1>Your Title</h1><p>Your Content</p><p><small>'
html += '<a href=\"{$unsubscribe}\">Unsubscribe</a></small></p></body>'
plain = "Your email client does not support HTML emails. "
plain += "Open newsletter here: {$url}. If you do not want"
plain += " to receive emails from us, click here: {$unsubscribe}"

api.campaigns.update(campaign_id, html=html, plain=plain)
api.campaigns.send(campaign_id)

Running this code creates a campaign and moves the campaign to the mailerlite outbox. After 1 minute, it says it has been sent and goes to Sent. However, the mail is not actually sent, and when I click on the campaign in Sent, it says Sending...

Am I the only one like this? I would appreciate it if you could tell me the solution.

This is a screenshot.
화면 캡처 2022-09-02 110920

Can get and search subscriber by email

Can get and search subscriber by email, but via postman it works.

In [25]: mailerLiteApi.subscribers.get(email='[email protected]')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-ba3f407787d0> in <module>
----> 1 mailerLiteApi.subscribers.get(email='[email protected]')

~/.local/lib/python3.8/site-packages/mailerlite/subscriber.py in get(self, as_json, **identifier)
    262         res_json['fields'] = [Field(**res) for res in res_json['fields']]
    263 
--> 264         return Subscriber(**res_json)
    265 
    266     def delete(self, subscriber_id):

TypeError: __new__() got an unexpected keyword argument 'groups'
In [28]: mailerLiteApi.subscribers.search(search='[email protected]')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-753a59c1d509> in <module>
----> 1 mailerLiteApi.subscribers.search(search='[email protected]')

~/.local/lib/python3.8/site-packages/mailerlite/subscriber.py in search(self, search, limit, offset, minimized, as_json)
    320                 res['fields'] = [Field(**field) for field in res['fields']]
    321 
--> 322         all_subscribers = [Subscriber(**res) for res in res_json]
    323         return all_subscribers
    324 

~/.local/lib/python3.8/site-packages/mailerlite/subscriber.py in <listcomp>(.0)
    320                 res['fields'] = [Field(**field) for field in res['fields']]
    321 
--> 322         all_subscribers = [Subscriber(**res) for res in res_json]
    323         return all_subscribers
    324 

TypeError: __new__() got an unexpected keyword argument 'groups'

via postman is ok https://connect.mailerlite.com/api/subscribers/[email protected]

API https://developers.mailerlite.com/docs/subscribers.html#fetch-a-subscriber

Add new attributes to campaign

Need to add campaign sent attributes in a Campaign object

response example of the campaign sent:

{'id': 42706640, 'total_recipients': 0, 'type': 'regular', 'extra_type': None, 'name': 'Regular campaign name', 'status': 'draft', 'step': 3, 'send_rule': None, 'opened': {'count': None, 'rate': None}, 'clicked': {'count': None, 'rate': None}, 'followup_info': {'send_type': 'regular', 'followup_send_type': None}, 'ab_info': {'send_type': 'regular', 'ab_win_type': None}, 'date_created': '2021-10-18 14:08:49', 'date_send': '2021-10-18 14:08:00', 'date_end': None, 'mail': {'id': 45258518, 'date': '2021-10-18 14:08:49', 'subject': 'Regular campaign subject', 'code': 'v4u1v8', 'from': '[email protected]', 'from_name': 'Demo API v2', 'url': 'regular-campaign-subject-45258518', 'send_date': '2021-10-18 14:08:00', 'host': 'mailerlite.com', 'type': 'template', 'screenshot': 'https://static.mailerlite.com/images/newsletter_screenshot2.png', 'screenshot_big': 'https://static.mailerlite.com/images/newsletter_screenshot2.png', 'updated': '2021-10-18 11:08:51', 'language': {'code': 'en', 'title': 'English'}, 'groups': [{'id': 2984475, 'name': 'Asmeniniai', 'total': 6, 'active': 6, 'unsubscribed': 0, 'bounced': 0, 'unconfirmed': 0, 'junk': 0, 'sent': 241, 'opened': 74, 'clicked': 40, 'ordering': 34, 'updating': 0, 'user_id': 0, 'date': '2015-12-16 15:43:46', 'updated': '2020-07-07 16:44:57'}, {'id': 3237221, 'name': 'Gumroad', 'total': 0, 'active': 0, 'unsubscribed': 0, 'bounced': 0, 'unconfirmed': 0, 'junk': 0, 'sent': 83, 'opened': 52, 'clicked': 24, 'ordering': 30, 'updating': 0, 'user_id': 0, 'date': '2016-02-03 10:33:01', 'updated': '2020-07-07 16:44:57'}]}, 'mails': [{'id': 45258518, 'date': '2021-10-18 14:08:49', 'subject': 'Regular campaign subject', 'code': 'v4u1v8', 'from': '[email protected]', 'from_name': 'Demo API v2', 'url': 'regular-campaign-subject-45258518', 'send_date': '2021-10-18 14:08:00', 'host': 'mailerlite.com', 'type': 'template', 'screenshot': 'https://static.mailerlite.com/images/newsletter_screenshot2.png', 'screenshot_big': 'https://static.mailerlite.com/images/newsletter_screenshot2.png', 'updated': '2021-10-18 11:08:53'}], 'includes_survey': False, 'has_ecommerce': False, 'report_date': None}

add_single_subscriber updated?

Hello~
Thanks so much for the library I'm looking at the mailer docs and I think the endpoint might have updated to add a single subscriber. It looks like we pass in the group_id and subscriber_id instead of the subscriber data. Where would be a good place to update in the mailerlite-api-python lib files?

No module named 'mailerlite'

Installed 0.10.0 via pip [venv], still receiving:

from mailerlite import MailerLiteApi

ModuleNotFoundError: No module named 'mailerlite'

py3.8

Unable to get Subscriber group_id

I'm using the API to fetch subscribers from Mailerlite via Python. Specifically, I'm using below call:

api.subscribers.all(limit=2000, as_json=True)

This results in a list of subscribers with below JSON details per subscriber

{'id': 1261159647788771324, 'name': '', 'email': '[email protected]', 'sent': 0, 'opened': 0, 'opened_rate': 0, 'clicked': 0, 'clicked_rate': 0, 'type': 'active', 'country_id': 49, 'signup_ip': '88.23.20.209', 'signup_timestamp': '2022-04-05 22:39:05', 'confirmation_ip': '88.23.20.209', 'confirmation_timestamp': '2022-04-05 22:39:05', 'fields': [{'key': 'email', 'value': '[email protected]', 'type': 'TEXT'}, {'key': 'name', 'value': '', 'type': 'TEXT'}, {'key': 'last_name', 'value': '', 'type': 'TEXT'}, {'key': 'company', 'value': '', 'type': 'TEXT'}, {'key': 'country', 'value': '', 'type': 'TEXT'}, {'key': 'city', 'value': '', 'type': 'TEXT'}, {'key': 'phone', 'value': '', 'type': 'TEXT'}, {'key': 'state', 'value': '', 'type': 'TEXT'}, {'key': 'zip', 'value': '', 'type': 'TEXT'}], 'webform_subscribe_date': None, 'date_subscribe': None, 'date_unsubscribe': None, 'date_created': '2022-04-05 22:39:05', 'date_updated': '2022-04-05 22:39:05', 'user_agent': None}

I would like to identify the group_id of the subscribers and I would have expected this to be part of the subscriber JSON - but that does not seem to be the case. Any idea what might be missing in my call to get this - or what would be the best way to extract it?

TypeError: __new__() got an unexpected keyword argument 'webform_subscribe_date'

Description
I am trying to extract all subscribers from my mailerlite account through

  1. api.subscribers.all(stype='active')
  2. api.subscribers.active()
  3. api.subscribers.groups(id=group_id)

Platform Ubuntu 20.10
Python 3.8.10

Observed behavior:
The python script failed with webform_subscribe_date missing.
This : TypeError: new() got an unexpected keyword argument 'webform_subscribe_date'

Expected behavior:
The python layer returns all registered and active user accounts .

implement limit and offset for subscribers activity

I found out that the activity endpoint of the subscribers API from mailerlite has as well a limit and offset parameter.
This is not specified in the mailerlite API documentation.
https://developers.mailerlite.com/reference/activity-of-single-subscriber

Just calling the activity of the subscriber endpoint (with this library) doesn't return the full activity history of the subscriber.

When I call the API directly without this mailerlite-api-python wrapper library, and add limit and offset, I'm able to get the full history.

import requests

url = "https://api.mailerlite.com/api/v2/subscribers/987654321/activity?offset=0&limit=1000"

headers = {
    "Accept": "application/json",
    "X-MailerLite-ApiDocs": "true",
    "X-MailerLite-ApiKey": "....mykey..."
}


response = requests.request("GET", url, headers=headers)

print(response.text)

How to extract more than 100 subscribers in a call?

Hi,

I'm trying to pull out my subscribers as follows:

from mailerlite import MailerLiteApi

def mailerlite_loader(api_key):
    api = MailerLiteApi(api_key)
    subs = api.subscribers.all()
    email_subs = []

    for i in range(len(subs)):
        email_subs.append(subs[i].email)

    return email_subs

The above, however, only returns 100 subscribers (there are many more). Is there a way to get all the subscribers, either via one call or via some form of looping?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.