GithubHelp home page GithubHelp logo

xsleonard / pystmark Goto Github PK

View Code? Open in Web Editor NEW
24.0 4.0 15.0 748 KB

Postmark library for python 2 and 3. Built on top of the requests library.

License: MIT License

Python 100.00%
postmark email python postmarkapp

pystmark's Introduction

pystmark

PyPI version Build Status Coverage Status

Postmark API library for python 2.7, 3.6 and pypy. Built on top of the requests library.

Web Framework Integration

Documentation

The full Sphinx-compiled documentation is available here: https://readthedocs.org/docs/pystmark/en/latest/

Example Usage

from pystmark import (
    Message,
    send,
    send_with_template,
    send_batch,
    send_batch_with_templates,
    UnauthorizedError
)

API_KEY = 'my_api_key'
SENDER = '[email protected]'

# Send a single message
message = Message(
    sender=SENDER,
    to='[email protected]',
    subject='Hi',
    text='A message',
    tag='greeting'
)

response = send(message, api_key=API_KEY)

# Send a template message
model = {
    'user_name': 'John Smith',
    'company': {
      'name': 'ACME'
    }

message = Message(
    sender=SENDER,
    to='[email protected]',
    template_id=11111,
    template_model=model,
    tag='welcome',
)

response = send_with_template(message, api_key=API_KEY)

# Send multiple messages
messages = [
    Message(
        sender=SENDER,
        to='[email protected]',
        subject='Hi',
        text='A message',
        tag='greeting',
        message_stream='broadcasts',
    )
]

response = send_batch(messages, api_key=API_KEY)

# Send multiple messages with templates
messages = [
    Message(
        sender=SENDER,
        to='[email protected]',
        template_id=11111,
        template_model=model,
        tag='greeting',
        message_stream='broadcasts',
    )
]

response = send_batch_with_templates(messages, api_key=API_KEY)

# Check API response error
try:
    response.raise_for_status()
except UnauthorizedError:
    print 'Use your real API key'

# Check for errors in each message when sending batch emails:
for m in response.messages:
    if m.error_code > 0:
        print m.message

Contribution

  1. Fork this repo
  2. Make your changes and write a test for them
  3. Add yourself to the AUTHORS.md file and submit a pull request

Please run the tests with ./setup.py test --with-integration, with at least python2.7, before you make a pull request. Requirements for running the tests are in tests/requirements.txt. The other versions will be handled by travis-ci.

The pep8 tests may fail if using pypy due to this bug, so that test is disabled if pypy is detected.

Copyright and License

pystmark is licensed under the MIT license. See the LICENSE file for full details.

pystmark's People

Contributors

jdavisp3 avatar jonathana avatar maxcountryman avatar mbachry avatar ollemento avatar sheeley avatar speedplane avatar xsleonard 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

Watchers

 avatar  avatar  avatar  avatar

pystmark's Issues

Pip can't install?

$ pip install pystmark Downloading/unpacking pystmark Could not find any downloads that satisfy the requirement pystmark

Any idea what's going on?

I then tried to install from the github repo:

pip install git+git://github.com/xsleonard/pystmark.git
Downloading/unpacking git+git://github.com/xsleonard/pystmark.git
  Cloning git://github.com/xsleonard/pystmark.git to /tmp/pip-g9dNc2-build
  Running setup.py egg_info for package from git+git://github.com/xsleonard/pystmark.git

Requirement already satisfied (use --upgrade to upgrade): requests>=1.1.0 in /Library/Python/2.7/site-packages (from pystmark==0.3)
Installing collected packages: pystmark
  Running setup.py install for pystmark

Successfully installed pystmark
Cleaning up...

This seemed to work, however I still can't import it?

import pystmark ImportError: No module named pystmark

Template not found silently fails for `send_batch_with_templates`

To reproduce:

import pystmark

api_key = 12345
fr = "[email protected]"
to = "[email protected]"
m = pystmark.Message(sender=fr, to=to, template_id=1, template_model={})
r = pystmark.send_with_template(m, api_key=api_key)
r.raise_for_status()

# raises
# pystmark.UnprocessableEntityError:
# The 'TemplateId' associated with this request is not valid or was not found.
# [ErrorCode 1101]


r = pystmark.send_batch_with_templates([m], api_key=api_key)
r.raise_for_status()

# silent

unicode error

I'm trying to send email with non-ascii characters in the body. I am using:

  • python 2.7.5
  • requests 1.2.3 (also tried 2.3.0)
  • pystmark 0.3.3

I am getting an error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 120: ordinal not in range(128)

I have tried encoding the body as utf-8 when passing to pystmark, but I think it gets turned back into unicode by the json.dumps call.

I believe the solution would be for pystmark to encode the JSON sent to postmark as utf-8. I'm happy to submit a patch if that would be acceptable.

SSLError: [Errno 2] No such file or directory

I've started getting the following Traceback when sending to Postmark:

Traceback (most recent call last):
  File "../updater\CrossPlatform.py", line 1494, in _send_email_postmark
    resp = pystmark.send(message, api_key = passwords.postmark_apikey)
  File "..\libs\pystmark.py", line 96, in send
    secure=secure, test=test, **request_args)
  File "..\libs\pystmark.py", line 1007, in send
    return self._request(url, data=data, headers=headers, **request_args)
  File "..\libs\pystmark.py", line 891, in _request
    response = requests.request(self.method, url, **kwargs)
  File "..\libs\requests\api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "..\libs\requests\sessions.py", line 456, in request
    resp = self.send(prep, **send_kwargs)
  File "..\libs\requests\sessions.py", line 559, in send
    r = adapter.send(request, **kwargs)
  File "..\libs\requests\adapters.py", line 382, in send
    raise SSLError(e, request=request)
SSLError: [Errno 2] No such file or directory

The URL this call is sending to is: https://api.postmarkapp.com/email

The keyword arguments are:

{'data': '{"From": "[email protected]", 
           "To": "mes65@<REDACTED>", 
           "Cc": "michael.sander@<REDACTED>", 
           "HtmlBody": "<p>html_content: test email: function _send_email_postmark at 0x0000000005E8F438.</p>", 
           "Headers": [{"Name": "X-Docket-Alarm", "Value": "Test Email"}], 
           "TrackOpens": true, "Tag": "testing", 
           "TextBody": "text_content: test email: function _send_email_postmark at 0x0000000005E8F438.",
           "Subject": "DA Email Test"}',
 'headers': {'Accept': 'application/json',
             'Content-Type': 'application/json',
           'X-Postmark-Server-Token': '<REDACTED>'}}

I monkey-patched pystmark.py on line 891 adding verify=False to the call to the requests library. That turns off SSL authentication checking, and appears to fix the issue. But ideally, I'd like to be able to use SSL.

Tag in BouncedMessage?

From the looks of the PostMarkApp api a "Tag" field should be provided in the Bounces response, can we get that added to the BouncedMessage object?

Actually same goes with the "Name", although it maybe simple enough to create that mapping.

Add support for MessageStream

From the docs:

MessageStream | string
Set message stream ID that's used for sending.
If not provided, message will default to the "outbound" transactional stream.

Affected endpoints:

  • /email
  • /email/batch
  • /email/withTemplate/
  • /email/batchWithTemplates

Tests Fail on Windows

Attempting to make a pull request here, and trying to run tests, but I'm running into difficulty getting them off the ground. I get the following exception:

> python ./setup.py test --with-integration
running test
Traceback (most recent call last):
  File "./setup.py", line 127, in <module>
    'Topic :: Communications :: Email',
  File "C:\Python27\lib\site-packages\setuptools\__init__.py", line 129, in setup
    return distutils.core.setup(**attrs)
  File "C:\Python27\lib\distutils\core.py", line 151, in setup
    dist.run_commands()
  File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "C:\Python27\lib\distutils\dist.py", line 972, in run_command
    cmd_obj.run()
  File "./setup.py", line 86, in run
    self._no_print_statements()
  File "./setup.py", line 43, in _no_print_statements
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  File "C:\Python27\lib\subprocess.py", line 351, in __init__
    raise ValueError("close_fds is not supported on Windows "
ValueError: close_fds is not supported on Windows platforms if you redirect stdin/stdout/stderr

That was problem 1, but then I made _no_print_statements a do-nothing function, and I still ran into a number of validation failures.


======================================================================
ERROR: test_get_bounce (tests.integration.test_pystmark.BounceLiveTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\integration\test_pystmark.py", line 35, in test_get_bounce
    r = pystmark.get_bounce(777, test=True)
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\pystmark.py", line 185, in get_bounce
    test=test, **request_args)
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\pystmark.py", line 1291, in get
    return self._request(url, headers=headers, **request_args)
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\pystmark.py", line 921, in _request
    return self.response_class(response, sender=self)
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\pystmark.py", line 809, in __init__
    self.bounce = BouncedMessage(self._data, sender=sender)
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\pystmark.py", line 613, in __init__
    self.id = bounce_data['ID']
KeyError: 'ID'
-------------------- >> begin captured logging << --------------------
urllib3.connectionpool: DEBUG: Starting new HTTPS connection (1): api.postmarkapp.com:443
urllib3.connectionpool: DEBUG: https://api.postmarkapp.com:443 "GET /bounces/777 HTTP/1.1" 200 None
--------------------- >> end captured logging << ---------------------

======================================================================
FAIL: test_bounce_activate (tests.integration.test_pystmark.BounceActivateLiveTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\integration\test_pystmark.py", line 57, in test_bounce_activate
    self.assert500(r)
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\test_pystmark.py", line 81, in assert500
    self.assertEqual(r.status_code, 500)
AssertionError: 200 != 500
-------------------- >> begin captured logging << --------------------
urllib3.connectionpool: DEBUG: Starting new HTTPS connection (1): api.postmarkapp.com:443
urllib3.connectionpool: DEBUG: https://api.postmarkapp.com:443 "PUT /bounces/777/activate HTTP/1.1" 200 None
--------------------- >> end captured logging << ---------------------

======================================================================
FAIL: test_get_bounce_dump (tests.integration.test_pystmark.BounceDumpLiveTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\integration\test_pystmark.py", line 43, in test_get_bounce_dump
    self.assert500(r)
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\test_pystmark.py", line 81, in assert500
    self.assertEqual(r.status_code, 500)
AssertionError: 200 != 500
-------------------- >> begin captured logging << --------------------
urllib3.connectionpool: DEBUG: Starting new HTTPS connection (1): api.postmarkapp.com:443
urllib3.connectionpool: DEBUG: https://api.postmarkapp.com:443 "GET /bounces/777/dump HTTP/1.1" 200 None
--------------------- >> end captured logging << ---------------------

======================================================================
FAIL: test_get_bounce_tags (tests.integration.test_pystmark.BounceTagsLiveTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\integration\test_pystmark.py", line 50, in test_get_bounce_tags
    self.assert500(r)
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\test_pystmark.py", line 81, in assert500
    self.assertEqual(r.status_code, 500)
AssertionError: 200 != 500
-------------------- >> begin captured logging << --------------------
urllib3.connectionpool: DEBUG: Starting new HTTPS connection (1): api.postmarkapp.com:443
urllib3.connectionpool: DEBUG: https://api.postmarkapp.com:443 "GET /bounces/tags HTTP/1.1" 200 None
--------------------- >> end captured logging << ---------------------

======================================================================
FAIL: test_get_bounces (tests.integration.test_pystmark.BouncesLiveTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\integration\test_pystmark.py", line 29, in test_get_bounces
    self.assert500(r)
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\test_pystmark.py", line 81, in assert500
    self.assertEqual(r.status_code, 500)
AssertionError: 200 != 500
-------------------- >> begin captured logging << --------------------
urllib3.connectionpool: DEBUG: Starting new HTTPS connection (1): api.postmarkapp.com:443
urllib3.connectionpool: DEBUG: https://api.postmarkapp.com:443 "GET /bounces?count=25&offset=0 HTTP/1.1" 200 None
--------------------- >> end captured logging << ---------------------

======================================================================
FAIL: test_get_delivery_stats (tests.integration.test_pystmark.DeliveryStatsLiveTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\integration\test_pystmark.py", line 64, in test_get_delivery_stats
    self.assert500(r)
  File "C:\Users\mes65\Documents\DAWork\github_libs\pystmark\tests\test_pystmark.py", line 81, in assert500
    self.assertEqual(r.status_code, 500)
AssertionError: 200 != 500
-------------------- >> begin captured logging << --------------------
urllib3.connectionpool: DEBUG: Starting new HTTPS connection (1): api.postmarkapp.com:443
urllib3.connectionpool: DEBUG: https://api.postmarkapp.com:443 "GET /deliverystats HTTP/1.1" 200 None
--------------------- >> end captured logging << ---------------------

Name                Stmts   Miss  Cover
---------------------------------------
_pystmark_meta.py       3      0   100%
pystmark.py           514      0   100%
---------------------------------------
TOTAL                 517      0   100%
----------------------------------------------------------------------
Ran 93 tests in 2.456s

FAILED (errors=1, failures=5)

New version in pip

Was just wondering when there might be a new version available in pip? Was hoping to get an update for the track_opens param, but doesn't seem to actually be in any release yet.

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.