Git Product home page Git Product logo

mailtmswift's Introduction

MailTMSwift


MailTMSwift is a Lightweight Swift Wrapper for https://mail.tm API (A Temp Mail Service).

Used by

Tempbox - An opensource disposable email client for MacOS powered by Mail.tm

Tempbox

Documentation

  • Documentation is generated from Apple's DocC and is hosted on here
  • The mail.tm api is documented here

Installation

Swift Package Manager

  • File > Swift Packages > Add Package Dependency
  • Add https://github.com/devwaseem/MailTMSwift.git
  • Select "Up to Next Major" with "1.1.1"

Requirements

Swift: 5.0

Platform Minimum required version
iOS 11.0
macOS 10.12
watchOS 4.0
tvOS 11.0

Highlights

๐Ÿ•น Simple interface

๐Ÿšฅ Combine support

๐Ÿ“ก Live updates using SSE

๐Ÿšง Cancel ongoing request

Getting started

Introduction

All the methods in this package support Combine. Retaining AnyCancellables will take care of canceling the ongoing API request when the retaining class is deinitialized. However, to cancel ongoing API requests when using completion handler supported methods, use MTAPIServiceTask.

The Helper classes MTAccountService, MTMessageService and MTDomainService are Stateless classes, so you are free to create multiple instances of it, without creating any side effects. If you use a dependency container, store the instance of the class and store it as Application or Singleton scope.

Cancel ongoing API Request

Any non-combine methods of MTAccountService, MTMessageService and MTDomainService return MTAPIServiceTask. You can call cancel() method to cancel the ongoing API request.

let task = messageService.deleteMessage(id: id, token: token) { ... }

// cancel request
task.cancel()

Creating an account

import MailTMSwift

let auth = MTAuth(address: "[email protected]", password: "12345678")
let accountService = MTAccountService()
accountService.createAccount(using: auth) { (accountResult: Result<MTAccount, MTError>) in
  switch accountResult {
    case .success(let account):
      print("Created an account \(account)")
    case .failure(let error):
      print("Error occurred \(error)")
  }
}

Login with existing Account

createAccount(using:) returns account document but not JWT token. You need JWT token to authorize protected endpoints.

To fetch the JWT token:

import MailTMSwift

let auth = MTAuth(address: "[email protected]", password: "12345678")
let accountService = MTAccountService()
accountService.login(using: auth) { (result: Result<String, MTError>) in
  switch result {
    case .success(let token):
      print("got JWT: \(token)")
    case .failure(let error):
      print("Error occurred \(error)")
  }
}

Deleting an account

import MailTMSwift

let id = // Account ID
let token = // Account JWT token
let accountService = MTAccountService()
accountService.deleteAccount(id: id, token: token) { (result: Result<MTEmptyResult, MTError>) in
    if case let .failure(error) = result {
        print("Error Occurred: \(error)")
        return
    }
    
    // Account deleted
    doSomethingAfterDelete()
}

Fetching available domains

import MailTMSwift

let domainService = MTDomainService()
domainService.getAllDomains { (result: Result<[MTDomain], MTError>) in
    switch result {
      case .success(let domains):
        print("Available domains: \(domains)")
      case .failure(let error):
        print("Error occurred \(error)")
    }
}

To get details of a specific domain:

import MailTMSwift

let id = // domain ID
domainService.getDomain(id: id) { (result: Result<MTDomain, MTError>) in
    switch result {
      case .success(let domain):
        print("Domain: \(domain)")
      case .failure(let error):
        print("Error occurred \(error)")
    }
}

Get all messages

import MailTMSwift

let messageService = MTMessageService()
let token = // Account JWT token
messageService.getAllMessages(token: token) { (result: Result<[MTMessage], MTError>) in
    switch result {
      case .success(let messages):
            for message in messages {
                print("Message: \(message)")
            }
      case .failure(let error):
        print("Error occurred \(error)")
    }
}

The messages returned by getAllMessages(token:) does not contain complete information, because it is intended to list the messages as list. To fetch the complete message with the complete information, use getMessage(id:token:).

Get complete message

import MailTMSwift

let messageService = MTMessageService()
let id = // Message ID
let token = // Account JWT token
messageService.getMessage(id: id, token: token) { (result: Result<MTMessage, MTError>) in
    switch result {
      case .success(let message):
        print("Complete message: \(message)")
      case .failure(let error):
        print("Error occurred \(error)")
    }
}

Please see Get all messages before proceeding with this method.

Mark message as seen

import MailTMSwift

let messageService = MTMessageService()
let id = // Message ID
let token = // Account JWT token
messageService.markMessageAs(id: id, seen: true, token: token) { (result: Result<MTMessage, MTError>) in
    switch result {
      case .success(let message):
        print("Updated message: \(message)")
      case .failure(let error):
        print("Error occurred \(error)")
    }
}

Get the source of a message

import MailTMSwift

let messageService = MTMessageService()
let id = // Message ID
let token = // Account JWT token
messageService.getSource(id: id, token: token) { (result: Result<MTMessageSource, MTError>) in
    switch result {
      case .success(let messageSource):
        print("Message source: \(messageSource)")
      case .failure(let error):
        print("Error occurred \(error)")
    }
}

If the size of message is big and you wish to use a downloadTask from URLSession, you can do so manually by using the URLRequest object returned by:

import MailTMSwift

let messageService = MTMessageService()
let id = // Message ID
let token = // Account JWT token
let urlRequest = messageService.getSourceRequest(id: id, token: token)
let task = URLSession.shared.downloadTask(with: request)
// handle download task

Deleting a message

import MailTMSwift

let messageService = MTMessageService()
let id = // Message ID
let token = // Account JWT token
messageService.deleteMessage(id: id, token: token) { (result: Result<MTEmptyResult, MTError>) in
    if case let .failure(error) = result {
        print("Error Occurred: \(error)")
        return
    }
    
    // Message deleted
    doSomethingAfterDelete()
}

๐Ÿšฅ Live Events

MTLiveMailService uses Apple's Combine framework to listen for live events. Make sure you use the required minimum version of the platform you're using this package.

Requirements

Platform Minimum required version
iOS 13.0+
macOS 10.15+
watchOS 6.0+
tvOS 13.0+

Setup

import MailTMSwift
import Combine

let subscriptions = Set<AnyCancellable>()
let token = // Account JWT token
let id = // Account id
let liveMailService = MTLiveMailService(token: token, accountId: id)

Listen for New / Updated messages

liveMailService.messagePublisher.sink { message in
    print("Received message event: \(message)")
}
.store(in: &subscriptions)

Listen for account updates

liveMailService.accountPublisher.sink { account in
    print("Received account event: \(account)")
}
.store(in: &subscriptions)

Listen for connection changes

liveMailService.statePublisher.sink { state in
  if state == .opened {
      print("Connected to server")
  } else {
      print("Disconnected to server")
  }
}
.store(in: &subscriptions)

Start the listener

liveMailService.start()

Stop the listener

liveMailService.stop()

Restart the listener

liveMailService.restart()

Enable autoRetry property to automatically restart the connection if the connection is lost in between.

liveMailService.autoRetry = true

Contribute ๐Ÿค

If you want to contribute to this library, you're always welcome! You can contribute by filing issues, bugs and PRs.

Contributing guidelines:

  • Open issue regarding proposed change.
  • Repo owner will contact you there.
  • If your proposed change is approved, Fork this repo and do changes.
  • Open PR against latest development branch. Add nice description in PR.
  • You're done!

โ˜•๏ธ Donation

If this project helped you in any way, you can give me a cup of coffee :).

paypal

๐Ÿ“ฑ Contact

Have an project? DM us at ๐Ÿ‘‡

Drop a mail to:- [email protected]

License

MailTMSwift is released under the MIT license. See LICENSE for details.

Copyright (c) 2021 Waseem akram

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

mailtmswift's People

Contributors

devwaseem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

mailtmswift's Issues

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.