Giter Site home page Giter Site logo

sendgrid-swift's Introduction

SendGrid-Swift

swift5 macOS iOS Linux*

This library allows you to quickly and easily send emails through SendGrid using Swift.

Important: Version 2.0.0 Breaking Changes

Versions 2.0.0 and higher have been migrated to Swift 5. Some existing classes, properties, and functions have been renamed or removed. Deprecation warnings will populate where appropriate.

Version 2 of this library re-architects how requests are sent. Previously a Request instance housed it's API parameters alongside other properties. Now, Request instances hold all their API-related parameters in a new parameters property. The parameters property is an Encodable instance, which simplifies how a request transforms its properties into the API parameters. In addition, the Session class's callback now utilize's Swift 5's Result enum to provide back either the API response or any errors that arose.

Previous Breaking Changes

  • Versions 1.0.0 and higher have been migrated to Swift 4 and adds Linux support, which contains code-breaking API changes.
  • Versions 0.2.0 and higher uses Swift 3, which introduces breaking changes from previous versions.
  • Versions 0.1.0 and higher have been migrated over to use SendGrid's V3 Mail Send Endpoint, which contains code-breaking changes.

*A Note About Linux

While this library does function on Linux via the Swift Package Manager, it relies upon the open source Foundation library (specifically URLSession). As it stands, URLSession hasn't been fully implemented yet. This library uses what has been implemented to make the HTTP requests, but critical implementations such as invalidating the session are unavailable, which could lead to unexpected behaviors such as memory leaks. That being said, Linux supported in this library should be treated as experimental.

Full Documentation

Full documentation of the library is available here.

Table Of Contents

Installation

Swift Package Manager

Add the SendGrid module to the "dependencies" and "targets" sections of your Package.swift file like so:

// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "MyApp",
    dependencies: [
        .package(
            url: "https://github.com/scottkawai/sendgrid-swift.git",
            from: "2.2.1"
        )
    ],
    targets: [
        .target(
            name: "MyApp",
            dependencies: ["SendGrid"]
        )
    ]
)

Note! Make sure you also list "SendGrid" as a dependency in the "targets" section of your manifest.

With Cocoapods

Add the following to your Podfile:

pod 'SendGrid', :git => 'https://github.com/scottkawai/sendgrid-swift.git'

As A Submodule

Add this repo as a submodule to your project and update:

cd /path/to/your/project
git submodule add https://github.com/scottkawai/sendgrid-swift.git

This will add a sendgrid-swift folder to your directory. Next, you need to add all the Swift files under /sendgrid-swift/Sources/ to your project.

Usage

Authorization

The V3 endpoint supports authorization via API keys (preferred) and basic authentication via your SendGrid username and password (Note: the Mail Send API only allows API keys). Using the Session class, you can configure an instance with your authorization method to be used over and over again to send email requests.

It is also highly recommended that you do not hard-code any credentials in your code. If you're running this on Linux, it's recommended that you use environment variables instead, like so:

///
/// Assuming you set your SendGrid API key as an environment variable
/// named "SG_API_KEY"...
///
let session = Session()
guard let myApiKey = ProcessInfo.processInfo.environment["SG_API_KEY"] else { 
    print("Unable to retrieve API key")
    return
}
session.authentication = Authentication.apiKey(myApiKey)

///
/// Alternatively `Session` has a singleton instance that you can 
/// configure once and reuse throughout your code.
///
///     Session.shared.authentication = Authentication.apiKey(myApiKey)

API Calls

All the available API calls are located in their own folders under the ./Sources/SendGrid/API folder, and each one has its own README explaining how to use it. Below is a list of the currently available API calls:

Development

If you're developing on macOS, you an generate an Xcode project by running the following:

cd /path/to/sendgrid-swift
swift package generate-xcodeproj

This project also contains a Dockerfile and a docker-compose.yml file which runs Swift 5. Running docker-compose up will execute the swift build command in the Linux container. If you want to run other commands, you can run docker-compose run --rm app <command>.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-fancy-new-feature)
  3. Commit your changes (git commit -am 'Added fancy new feature')
  4. Write tests for any changes and ensure existing tests pass
    • Note! Be sure that your changes also work on Linux. You can use the Docker container to quickly test this by running swift test --generate-linuxmain && docker-compose run --rm app swift test
  5. Push to the branch (git push origin my-fancy-new-feature)
  6. Create a new Pull Request

sendgrid-swift's People

Contributors

scottkawai avatar sgkawai 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  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  avatar

sendgrid-swift's Issues

400 bad request trying to use Dynamic Transactional Templates

Sendgrid has a (new-ish?) feature for using handlebar templates for transactional emails via the v3 send API - https://sendgrid.api-docs.io/v3.0/mail-send/v3-mail-send#handlebars

This library already supports a templateId parameter, but the docs here seem to suggest that's for legacy style templates? Links from docs here to Sendgrid's Template Engine suggest this is a deprecated feature.

When I attempt to send an email with a templateId of a dynamic template, i get a 400 response but no error message. These template IDs seem to start with d-.

Perhaps this library just needs to also support sending along a dynamic_template_data dictionary? Happy to try this myself, but figured I'd open an issue in case others have run into this / are working on it / have more context than me / etc.

I'm also a little unsure about Content for dynamic templates. Sendgrid docs suggest its not required when using dynamic templates. That would make sense to me - the template itself provides most of the "content", while the dynamic aspects for personalization come in the dynamic_template_data payload.

It does look like there was a PR for this that was opened and closed same day https://github.com/scottkawai/sendgrid-swift/pull/15/files

Support for Linux

Does anyone have a fork of this library that supports Linux?

It doesn't seem like massive changes are needed for it to work.

Getting error like Bad username/ password

Hi,
While im using Sendgrid - swift, i'm getting error on Ip Pool, so i commented that code, and i try to test app on simulator and iphone, then i'm getting Bad username/password.

Same credentials i used for Android app, those are working, where as come to Sendgrid- Swift, im getting these errors, so please give an assist on sendgrid-swift, it would be more help for me.

sendAt Error

I am getting the below error when trying to use sendAt:

APIResponse(errors: [SendGrid.Exception.APIMessage(message: "Invalid type. Expected: integer, given: number.", field: Optional("send_at"), help: Optional("http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.send_at"))], _httpResponse: Optional(<NSHTTPURLResponse: 0x283415c20> { URL: https://api.sendgrid.com/v3/mail/send } { Status Code: 400, Headers {
    "Access-Control-Allow-Headers" =     (
        "Authorization, Content-Type, On-behalf-of, x-sg-elas-acl"
    );
    "Access-Control-Allow-Methods" =     (
        POST
    );
    "Access-Control-Allow-Origin" =     (
        "https://sendgrid.api-docs.io"
    );
    "Access-Control-Max-Age" =     (
        600
    );
    Connection =     (
        "keep-alive"
    );
    "Content-Length" =     (
        184
    );
    "Content-Type" =     (
        "application/json"
    );
    Date =     (
        "Tue, 14 Jan 2020 20:43:30 GMT"
    );
    Server =     (
        nginx
    );
    "X-No-CORS-Reason" =     (
        "https://sendgrid.com/docs/Classroom/Basics/API/cors.html"
    );
} }))

The code I am using is as follows:

let personalization = Personalization(recipients: recipientEmail)
        let plainText = Content(contentType: .plainText, value: "Test Email")
        let htmlText = Content(contentType: .htmlText, value: "<h1>Test Email</h1>")
        let email = Email(personalizations: [personalization],
                          from: fromEmail,
                          content: [plainText, htmlText],
                          subject: "Test Email"
        )

        email.parameters!.sendAt = Date(timeIntervalSinceNow: 24 * 60 * 60)
        
        do {
            try Session.shared.send(request: email) { (result) in
                switch result {
                    case .success(let response):
                        print("Success: ", response.statusCode)
                    case .failure(let err):
                        print("Error: ", err)
                    }
            }
        } catch {
            print(error)
        }

Linux Ubuntu 16 Compile Error

Got an error compiling on official swift docker container via Ubuntu 16 and Swift 4.0.3:

Compile Swift Module 'SendGrid' (81 sources)
/root/DavisRealEstate/.build/checkouts/sendgrid-swift.git--6696960893670408330/Sources/SendGrid/Structs/EncodingStrategy.swift:47:36: error: type 'JSONEncoder.DataEncodingStrategy' has no member 'base64Encode'
public static let base64 = JSONEncoder.DataEncodingStrategy.base64Encode
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~
/root/DavisRealEstate/.build/checkouts/sendgrid-swift.git--6696960893670408330/Sources/SendGrid/Structs/DecodingStrategy.swift:48:36: error: type 'JSONDecoder.DataDecodingStrategy' has no member 'base64Decode'
public static let base64 = JSONDecoder.DataDecodingStrategy.base64Decode

Maybe related to this issue: swagger-api/swagger-codegen#6483

Use of older version of AFnetworking

I saw that you are using an older version of AFNetworking. Is there any particular reason for that? It will not allow us to update it for our purposes because you are using an older version.

Xcode 8 GM Swift 2.3 Compilation errors

When use Xcode 8 GM Swift 2.3, I am getting below 3 errors but I can correct 2 error myself. I request your advise on this.

pod entry
pod 'SendGrid', :git => 'https://github.com/scottkawai/sendgrid-swift.git'

Error
.../Pods/SendGrid/Sources/Classes/APIV3.swift:73:49: Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

.../Pods/SendGrid/Sources/Classes/APIV3.swift:45:99: '.dynamicType' is deprecated. Use 'type(of: ...)' instead

.../Pods/SendGrid/Sources/Classes/APIV3.swift:73:17: Expected 'let' in conditional

Plain text

I am using setTextBody to send plain text message. All line breaks are being converted to spaces. I am getting my text from a UITextView.

Authentication error

Could not make an HTTP request as there was no Authentication configured on Session. Please set the authentication property before calling send on Session.

in ViewDidLoad

Session.shared.authentication = Authentication.apiKey("API")

let personalization = Personalization(recipients: "[email protected]") let plainText = Content(contentType: ContentType.plainText, value: "Hello World") let htmlText = Content(contentType: ContentType.htmlText, value: "<h1>Hello World</h1>") let email = Email( personalizations: [personalization], from: "[email protected]", content: [plainText, htmlText], subject: "Hello World" ) do { try Session.shared.send(request: email) } catch { print(error) }

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.