Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check the credentials provided in the constructor #3

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion pymailgun/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@

"""

from client import Client
from __future__ import absolute_import
from .client import Client
from .client import MailgunCredentialsError
22 changes: 17 additions & 5 deletions pymailgun/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
import requests


class MailgunCredentialsError(Exception):
"""
Exception to be raised in case the provided credentials are invalid.
"""
pass


class Client(object):
""" The client for mailgun's API

Expand All @@ -14,13 +21,17 @@ class Client(object):
def __init__(self, key, domain):
self.api_key = key
self.domain = domain
self.check_credentials()

def __request(self, method, path, resource, data=None, files=None):

url = 'https://api.mailgun.net/v2/%s/%s' % (path, resource)
def check_credentials(self):
""" Check the provided credentials """
resp = self.__request('get', 'domains')
if resp.status_code == 401:
raise MailgunCredentialsError('Invalid credentials')

def __request(self, method, path, data=None, files=None):
url = 'https://api.mailgun.net/v2/{}'.format(path)
auth = ('api', self.api_key)

return requests.request(method, url, data=data, auth=auth, files=files)

def send_mail(self, sender, to, subject, text, html=None, cc=None, bcc=None,
Expand Down Expand Up @@ -53,4 +64,5 @@ def send_mail(self, sender, to, subject, text, html=None, cc=None, bcc=None,
return self.__request('post', self.domain, 'messages', data=data,
files=attached_files)

return self.__request('post', self.domain, 'messages', data=data)
return self.__request('post', '{}/{}'.format(self.domain, 'messages'),
data=data)