Skip to content

Commit

Permalink
Update the Python API to use the new API
Browse files Browse the repository at this point in the history
This update adds the functionality for custom domains and specific domains.

The library may have some incompatibilities with the old one, so a disclaimer was added to the README file.
  • Loading branch information
AlexanderEpolite committed Apr 13, 2023
1 parent 524a46b commit 8b99820
Show file tree
Hide file tree
Showing 5 changed files with 150 additions and 72 deletions.
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,8 @@ __pychache__/
TempMail/__pycache__/
build/
dist/
*.egg-info/
*.egg-info/

.idea
*.iml
venv
63 changes: 37 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,49 @@

This repository is for the [TempMail.lol](https://tempmail.lol/) Python API.

## Updating form v1
The library is different from version 1.x.x. Please see Usage to learn more about the changes to
the Python library.

## Installation

Use this command in terminal.
You can install the TempMail API using PIP:
```
pip install tempmail-lol
```

## TempMail Plus (optional)

Optionally, you can purchase time on a BananaCrumbs ID to get TempMail Plus. This includes higher rate limits, as well
as some other features. For more info, see this page: https://tempmail.lol/pricing.html

## Usage
```python
from TempMail import TempMail #imports everything from TempMail library
import time #import time module

inbox = TempMail.generateInbox() #returns an Inbox object with Email and Token

print("Email Address: "+ inbox.address) #View output below
print("Authorization Token: "+ inbox.token)

#output:
"""
Email Address: m8h69n52824315@theeyeoftruth.com
Authorization Token: RCfc1og1z1JzuN1mkXL2eFdAc_8uxSRAwcGhUoXuH26e7nnJMdVVtSxxasZLD9D2OHTKIjVEvLhK7S0K5QIanA
"""

while(True): #Infinite Loop
emails = TempMail.getEmails(inbox) #Returns list of Email objects
print(emails) # View output below
time.sleep(30) #wait 30 sec

#output:
"""
[Email (sender=ExampleEmail@gmail.com, recipient=d6inmp52824914@magicaljellyfish.com,
subject=Subject line, body=Text Area, html=<div dir="ltr">Text Area</div>,
date=1652824961713 )]
"""
from TempMail import TempMail

# Create a new TempMail object
tmp = TempMail()

# If you have a BananaCrumbs ID, you can login using the constructor
tmp = TempMail("24 number ID", "32 or 36 character token")

# Generate an inbox
inb = TempMail.generateInbox(tmp)

# Generate an inbox using Community (formerly Rush) domains
inb = TempMail.generateInbox(tmp, rush=True)

# Generate an inbox using a specific normal/community domain
inb = TempMail.generateInbox(tmp, rush=False, domain="cringemonster.com")

# Check for emails
emails = TempMail.getEmails(tmp, inbox=inb)

# Check custom domains (requires TempMail Plus)
custom_domain_emails = TempMail.checkCustomInbox(tmp, "example.com", "token given on website")
```

## Custom Domain Keys
Note that the token for custom inboxes is stored on your domain as a text record with a name of `_tmpml` and a sha512 hash.
The token that you submit is the text pre-sha512. This helps disconnect a user's BananaCrumbs ID and the domain he/she owns.

2 changes: 1 addition & 1 deletion TempMail/Email.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
Email class is used to store the email data which consists of
Email class is used to store the email data which consists of
the sender, recipient, subject, body, html and date
"""

Expand Down
115 changes: 89 additions & 26 deletions TempMail/TempMail.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,67 +3,130 @@
from TempMail.Email import Email
from TempMail.Inbox import Inbox


class TempMail:
global BASE_URL
BASE_URL = "https://api.tempmail.lol"



# class vars
auth_id = None
auth_token = None

# constructor
def __init__(self, auth_id=None, auth_token=None):
TempMail.auth_id = auth_id
TempMail.auth_token = auth_token

"""
Make a request to the tempmail.lol api with a given endpoint
The content of the request is a json string and is returned as a string object
"""
def makeHTTPRequest(endpoint):

def makeHTTPRequest(self, endpoint):
headers = {
"User-Agent": "TempMailPythonAPI/1.0",
"Accept": "application/json"
}
try:
connection = requests.get(BASE_URL + endpoint, headers=headers)
if connection.status_code >= 400:
raise Exception("HTTP Error: " + str(connection.status_code))
except Exception as e:
print(e)
return None

if TempMail.auth_id is not None and TempMail.auth_token is not None:
headers["X-BananaCrumbs-ID"] = TempMail.auth_id
headers["X-BananaCrumbs-MFA"] = TempMail.auth_token

connection = requests.get(BASE_URL + endpoint, headers=headers)

# Check some error codes
# This includes rate limits, auth errors, and server errors
if connection.status_code == 429: # Rate limit
raise Exception("TempMail Rate Limit: " + connection.text)
elif connection.status_code == 402: # No time left on account
raise Exception("BananaCrumbs ID has no time left. See https://tempmail.lol/pricing.html for more info")
elif 400 <= connection.status_code < 500: # Client error
raise Exception("HTTP Error: " + str(connection.status_code))
elif 500 <= connection.status_code < 600: # Server error
raise Exception("TempMail Server returned an error: " + str(
connection.status_code) + " " + connection.text + " please report this.")

response = connection.text

return response

"""
GenerateInbox will generate an inbox with an address and a token
and returns an Inbox object
> rush = False will generate a normal inbox with no rush (https://tempmail.lol/news/2022/08/03/introducing-rush-mode-for-tempmail/)
> domain = None will generate an inbox with a random domain
"""
def generateInbox(rush = False):
try :
s = TempMail.makeHTTPRequest("/generate" + ("/rush" if rush else ""))
except:
print("Website responded with: "+ s)

def generateInbox(self, rush=False, domain=None):
url = "/generate"
# with rush mode: /generate/rush
# with domain: /generate/<domain>
# these two cannot be combined. If both are true, only rush will be used

if rush:
url = url + "/rush"
elif domain is not None:
url = url + "/" + domain

s = TempMail.makeHTTPRequest(self, url)
data = json.loads(s)
return Inbox(data["address"], data["token"])


"""
getEmail gets the emails from an inbox object
and returns a list of Email objects
"""
def getEmails(inbox):
s = TempMail.makeHTTPRequest("/auth/" + inbox.token)

def getEmails(self, inbox):
# if inbox is an instance of Inbox object, get the token, otherwise inbox is a string
if isinstance(inbox, Inbox):
token = inbox.token
else:
token = inbox

s = TempMail.makeHTTPRequest(self, "/auth/" + token)
data = json.loads(s)

#Raise an exception if the token is invalid
# Raise an exception if the token is invalid
if "token" in s and "token" in data:
if data["token"] == "invalid":
raise Exception("Invalid Token")

#if no emails are found, return an empty list
#else return a list of email
if data["email"] == None:
# if no emails are found, return an empty list
# else return a list of email
if data["email"] is None:
return ["None"]
else:
emails = []
for email in data["email"]:
emails.append(Email(email["from"], email["to"], email["subject"], email["body"], email["html"], email["date"]))
# Some emails may not have html, so we will check for that
if "html" in email:
emails.append(
Email(email["from"], email["to"], email["subject"], email["body"], email["html"], email["date"]))
else:
emails.append(
Email(email["from"], email["to"], email["subject"], email["body"], None, email["date"]))
return emails

"""
checkCustomInbox checks if there are any emails in a custom inbox
and returns a list of Email objects
> domain Required
> token Required
"""
def checkCustomInbox(self, domain, token):
url = "/custom/" + token + "/" + domain

s = TempMail.makeHTTPRequest(self, url)
data = json.loads(s)

# There is no way to check if the token is invalid
# so we will just return an empty list if there are no emails
if data["email"] is None:
return []
else:
emails = []
for email in data["email"]:
emails.append(
Email(email["from"], email["to"], email["subject"], email["body"], email["html"], email["date"]))
return emails

36 changes: 18 additions & 18 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,23 @@
here = os.path.abspath(os.path.dirname(__file__))

with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as fh:
long_description = "\n" + fh.read()
long_description = "\n" + fh.read()

setup(name='tempmail-lol',
version='1.1.0',
description='A Python API for TempMail',
author='Alex Torres',
author_email='cloudbotsedc@gmail.com',
url='https://github.com/tempmail-lol/api-python',
packages=find_packages(),
install_requires=['requests'],
keywords=['python', 'video', 'api', 'tempmail'],
classifiers=[
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3",
"Operating System :: Unix",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
]
)
version='2.0.0',
description='A Python API for TempMail',
author='Alex Torres, Alexander Epolite',
author_email='cloudbotsedc@gmail.com',
url='https://github.com/tempmail-lol/api-python',
packages=find_packages(),
install_requires=['requests'],
keywords=['tempmail', 'api', 'lol', 'tempmail-lol', 'tempmail.lol', 'email', 'free'],
classifiers=[
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3",
"Operating System :: Unix",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
]
)

0 comments on commit 8b99820

Please sign in to comment.