|
| 1 | +import requests |
| 2 | +from urllib.parse import quote |
| 3 | + |
| 4 | + |
| 5 | +class SendMail: |
| 6 | + """ |
| 7 | + Simple mail sender against tempmail.plus API. |
| 8 | +
|
| 9 | + Usage: |
| 10 | + from ByMail.send import SendMail |
| 11 | + mail = SendMail( |
| 12 | + from_="utpys@merepost.com", |
| 13 | + to="utpys@fexpost.com", |
| 14 | + subject="WEwetse", |
| 15 | + text="zsgzsdgzse", |
| 16 | + content_type="text/html", # default |
| 17 | + ) |
| 18 | + sent = mail.status() |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__( |
| 22 | + self, |
| 23 | + *, |
| 24 | + from_: str, |
| 25 | + to: str, |
| 26 | + subject: str, |
| 27 | + text: str, |
| 28 | + content_type: str = "text/html", |
| 29 | + api_url: str = "https://tempmail.plus/api/mails/", |
| 30 | + headers_override: dict | None = None, |
| 31 | + ) -> None: |
| 32 | + self.from_ = from_ |
| 33 | + self.to = to |
| 34 | + self.subject = subject |
| 35 | + self.text = text |
| 36 | + self.content_type = content_type or "text/html" |
| 37 | + self.api_url = api_url |
| 38 | + self._response = None |
| 39 | + |
| 40 | + cookies = {"email": quote(self.from_)} |
| 41 | + |
| 42 | + |
| 43 | + headers = { |
| 44 | + "accept": "*/*", |
| 45 | + "origin": "https://tempmail.plus", |
| 46 | + "referer": "https://tempmail.plus/en/", |
| 47 | + "x-requested-with": "XMLHttpRequest", |
| 48 | + "user-agent": "ByMail/1.0 (+requests)", |
| 49 | + } |
| 50 | + if headers_override: |
| 51 | + headers.update(headers_override) |
| 52 | + |
| 53 | + files = { |
| 54 | + "email": (None, self.from_), |
| 55 | + "to": (None, self.to), |
| 56 | + "subject": (None, self.subject), |
| 57 | + "content_type": (None, self.content_type), |
| 58 | + "text": (None, self.text if self.content_type != "text/html" else f"{self.text}"), |
| 59 | + } |
| 60 | + |
| 61 | + try: |
| 62 | + self._response = requests.post( |
| 63 | + self.api_url, |
| 64 | + cookies=cookies, |
| 65 | + headers=headers, |
| 66 | + files=files, |
| 67 | + timeout=20, |
| 68 | + ) |
| 69 | + except Exception as exc: |
| 70 | + class _ErrorResponse: |
| 71 | + def __init__(self, error: Exception) -> None: |
| 72 | + self.status_code = 0 |
| 73 | + self.ok = False |
| 74 | + self.text = str(error) |
| 75 | + |
| 76 | + self._response = _ErrorResponse(exc) |
| 77 | + |
| 78 | + def status(self) -> bool: |
| 79 | + """Return True if the message appears to be sent successfully.""" |
| 80 | + if self._response is None: |
| 81 | + return False |
| 82 | + try: |
| 83 | + return 200 <= int(getattr(self._response, "status_code", 0)) < 300 |
| 84 | + except Exception: |
| 85 | + return False |
| 86 | + |
| 87 | + def response(self): |
| 88 | + """Return the underlying response object (or error-like object).""" |
| 89 | + return self._response |
| 90 | + |
| 91 | + |
0 commit comments