Giter Club home page Giter Club logo

sendwithus_ruby's Introduction

Sendwithus Ruby Client

Ruby bindings for sending email via the Sendwithus API.

sendwithus.com

Build Status

Installation

gem install send_with_us

or with Bundler:

gem 'send_with_us'
bundle install

Usage

Send

NOTE - If a customer does not exist by the specified email (recipient address), the send call will create a customer.

send_email arguments

  • template_id - string - Template ID being sent
  • to - hash - Recipients' email address
  • :data - hash - Email data
  • :from - hash - From name/address/reply_to
  • :cc - array - array of CC addresses
  • :bcc - array - array of BCC addresses
  • :files - array - array of files to attach, as strings or hashes (see below)
  • :esp_account - string - ESP account used to send email
  • :version_name - string - version of template to send
  • :headers - hash - custom email headers NOTE only supported by some ESPs
  • :tags - array - array of strings to attach as tags
  • :locale - string - Localization string

send_with arguments [DEPRECATED]

  • template_id - string - Template ID being sent
  • to - hash - Recipients' email address
  • data - hash - Email data
  • from - hash - From name/address/reply_to
  • cc - array - array of CC addresses
  • bcc - array - array of BCC addresses
  • files - array - array of files to attach, as strings or hashes (see below)
  • esp_account - string - ESP account used to send email
  • version_name - string - version of template to send
  • headers - hash - custom email headers NOTE only supported by some ESPs
  • tags - array - array of strings to attach as tags

For any Ruby project:

require 'rubygems'
require 'send_with_us'

begin
    obj = SendWithUs::Api.new( api_key: 'YOUR API KEY', debug: true )

    # required params
    result = obj.send_email(
        'template_id',
        { address: "[email protected]" })
    puts result

    # required params and locale
    result = obj.send_email(
        'template_id',
        { address: "[email protected]" }),
        locale: 'en-US'
    puts result

    # full cc/bcc support
    result = obj.send_email(
        'template_id',
        { name: 'Matt', address: '[email protected]' },
        data: { company_name: 'TestCo' },
        from: { name: 'Company',
            address: '[email protected]',
            reply_to: '[email protected]' },
        cc: [
            { name: 'CC',
                address: '[email protected]' }
        ],
        bcc: [
            { name: 'BCC',
                address: '[email protected]' },
            { name: 'BCC2',
                address: '[email protected]' }
        ])
    puts result

    # Attachment support
    result = obj.send_email(
        'template_id',
        { name: 'Matt', address: '[email protected]' },
        data: { company_name: 'TestCo' },
        from: { name: 'Company',
            address: '[email protected]',
            reply_to: '[email protected]' },
        cc: [],
        bcc: [],
        files: [
          'path/to/file.txt',
          { filename: 'customfilename.txt', attachment: 'path/to/file.txt' },
          { filename: 'anotherfile.txt', attachment: File.open('path/to/file.txt') },
          { filename: 'unpersistedattachment.txt', attachment: StringIO.new("raw data") },
          { id: "alreadyBase64EncodedFile", data: "aG9sYQ==\n" }
        ]
    )
    puts result

    # Set ESP account
    # See: https://help.sendwithus.com/support/solurtions/articles/1000088976-set-up-and-use-multiple
    result = obj.send_email(
        'template_id',
        { name: 'Matt', address: '[email protected]' },
        data: { company_name: 'TestCo' },
        from: { name: 'Company',
            address: '[email protected]',
            reply_to: '[email protected]' },
        cc: [],
        bcc: [],
        files: [],
        esp_account: 'esp_MYESPACCOUNT')
    puts result

    # all possible arguments
    result = obj.send_email(
        'template_id',
        { name: 'Matt', address: '[email protected]' },
        data: { company_name: 'TestCo' },
        from: {
          name: 'Company',
          address: '[email protected]',
          reply_to: '[email protected]'
        },
        cc: [
            { name: 'CC',
                address: '[email protected]' }
        ],
        bcc: [
            { name: 'BCC',
                address: '[email protected]' },
            { name: 'BCC2',
                address: '[email protected]' }
        ],
        files: ['path/to/attachment.txt'],
        esp_account: 'esp_MYESPACCOUNT',
        version_name: 'v2',
        tags: ['tag1', 'tag2'],
        locale: 'en-US')
    puts result

    # send_with - DEPRECATED!
    result = obj.send_with(
        'template_id',
        { name: 'Matt', address: '[email protected]' },
        { company_name: 'TestCo' },
        {
          name: 'Company',
          address: '[email protected]',
          reply_to: '[email protected]'
        },
        [
            { name: 'CC',
                address: '[email protected]' }
        ],
        [
            { name: 'BCC',
                address: '[email protected]' },
            { name: 'BCC2',
                address: '[email protected]' }
        ],
        ['path/to/attachment.txt'],
		'esp_MYESPACCOUNT',
		'v2',
        ['tag1', 'tag2'],
        'en-US')
    puts result
rescue => e
    puts "Error - #{e.class.name}: #{e.message}"
end

Render a Template

  • email_id - string - Template ID being rendered
  • version_id - string - Version ID to render (optional)
  • data - hash - Email data to render the template with (optional)
  • data[:locale] - hash value - This option specifies the locale to render (optional)
  • strict - bool - This option enables strict mode and is disabled by default (optional)
require 'rubygems'
require 'send_with_us'

begin
    obj = SendWithUs::Api.new( api_key: 'YOUR API KEY', debug: true )

    result = obj.render(
        'template_id',
        'version_id',
        { company_name: 'TestCo' },
		strict=true)

    puts result
rescue => e
    puts "Error - #{e.class.name}: #{e.message}"
end

Remove Customer from All Drip Campaigns

require 'rubygems'
require 'send_with_us'

begin
    obj = SendWithUs::Api.new( api_key: 'YOUR API KEY', debug: true )

    result = obj.drips_unsubscribe('[email protected]')

    puts result
rescue => e
    puts "Error - #{e.class.name}: #{e.message}"
end

Using Drip Campaigns

require 'rubygems'
require 'send_with_us'

begin
    obj = SendWithUs::Api.new( api_key: 'YOUR API KEY', debug: true )

    # List campaigns
    result = obj.list_drip_campaigns()
    puts result

    # List steps of campaign dc_asdf1234
    result = obj.drip_campaign_details('dc_asdf1234')
    puts result

    # Add [email protected] to campaign dc_asdf1234
    result = obj.start_on_drip_campaign('[email protected]', 'dc_asdf1234')
    puts result

    OR

    # Add [email protected] to campaign dc_asdf1234, with optional: email_data, locale, tags
    result = obj.start_on_drip_campaign('[email protected]', 'dc_asdf1234', {total: '100.00'}, 'en-US', ['tag1', 'tag2'])
    puts result

    # Remove [email protected] from campaign dc_asdf1234
    result = obj.remove_from_drip_campaign('[email protected]', 'dc_asdf1234')
    puts result
    rescue => e
    puts "error - #{e.class.name}: #{e.message}"
end

Customers

Get a Customer

customer = obj.customer_get("[email protected]")

Create/Update a Customer

result = obj.customer_create("[email protected]")

Delete a Customer

result = obj.customer_delete("[email protected]")

Templates

# List Templates
obj.list_templates() # Alternatively, obj.emails()

# Create Template
obj.create_template(name, subject, html, text)

# Delete Template
obj.delete_template(template_id)

# List Template Versions
obj.list_template_versions(template_id)

# Get Template Version
obj.get_template_version(template_id, version_id)

# Update Template Version
obj.update_template_version(template_id, version_id, name, subject, html, text)

# Create Template Version
obj.create_template_version(template_id, name, subject, html, text)

Rails

For a Rails app, create send_with_us.rb in /config/initializers/ with the following:

SendWithUs::Api.configure do |config|
    config.api_key = 'YOUR API KEY'
    config.debug = true
end

In your application code where you want to send an email:

begin
    result = SendWithUs::Api.new.send_with('template_id', { address: '[email protected]' }, { company_name: 'TestCo' })
    puts result
rescue => e
    puts "Error - #{e.class.name}: #{e.message}"
end

Take a look at our Mailer that you can use similarly to ActionMailer

sendwithus_ruby_action_mailer

Logs

Get single log

Used to get the details for a single log. The log ID can be obtained by recording the receipt_id value returned from the send call.

obj.log('log_sld7xWJ3isc23-3')

Get logs for customer

This will retrieve email logs for a customer.

Optional Arguments:

  • count – The number of logs to return. Max: 100, Default: 100.
  • created_gt – Return logs created strictly after the given UTC timestamp.
  • created_lt – Return logs created strictly before the given UTC timestamp.
obj.customer_email_log('[email protected]', count: 1)

Get events for a single log

This will retrieve the events and associated data for a specified log.

obj.log_events('log_sld7xWJ3isc23-3')

Errors

The following errors may be generated:

SendWithUs::ApiInvalidEndpoint - the target URI is probably incorrect or template_id is invalid
SendWithUs::ApiInvalidKey - the sendwithus API key is invalid
SendWithUs::ApiBadRequest - the API request is invalid
SendWithUs::ApiConnectionRefused - the target URI is probably incorrect
SendWithUs::ApiUnknownError - an unhandled HTTP error occurred

Running tests

Use rake to run the tests:

$: rake

Troubleshooting

General Troubleshooting

  • Enable debug mode
  • Make sure you're using the latest Ruby client
  • Capture the response data and check your logs — often this will have the exact error

Enable Debug Mode

Debug mode prints out the underlying request information as well as the data payload that gets sent to sendwithus. You will most likely find this information in your logs. To enable it, simply put debug: true as a parameter when instantiating the API object. Use the debug mode to compare the data payload getting sent to sendwithus' API docs.

obj = SendWithUs::Api.new( api_key: 'YOUR API KEY', debug: true )

Response Ranges

Sendwithus' API typically sends responses back in these ranges:

  • 2xx – Successful Request
  • 4xx – Failed Request (Client error)
  • 5xx – Failed Request (Server error)

If you're receiving an error in the 400 response range follow these steps:

  • Double check the data and ID's getting passed to Sendwithus
  • Ensure your API key is correct
  • Log and check the body of the response

sendwithus_ruby's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 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

sendwithus_ruby's Issues

UTF-8 payloads that raise a 400 BadRequest cause a nested error due to incomptible encoding coercion

Client version

4.0.1 but the offending code is in 4.1.0+ as well

Here is the line number: https://github.com/sendwithus/sendwithus_ruby/blob/v4.1.0/lib/send_with_us/api_request.rb#L61

Expected behaviour

I should receive a SendWithUs::ApiBadRequest exception

Actual behaviour

I receive Encoding::CompatibilityError: incompatible character encodings: ASCII-8BIT and UTF-8

Steps to reproduce

The easiest way to reproduce this is to attempt to send an email to an invalid email address with UTF-8 encoded characters that cannot be coerced to ASCII. For example, just send an email to Ö.

UTF-8 in email address causes an error: "incompatible character encodings..."

I have a user in my database with non-ASCII characters in their email address. According to http://stackoverflow.com/a/37320735/1067145 this is valid per RFC 6531.

However, I'm encountering an error when attempting to push this user to sendwithus as a customer:

irb(main):035:0> SendWithUsClient.get.customer_create(User.find(id).email, { foo: 'bar' })
Encoding::CompatibilityError: incompatible character encodings: ASCII-8BIT and UTF-8
    from /app/vendor/bundle/ruby/2.3.0/gems/send_with_us-1.12.0/lib/send_with_us/api_request.rb:61:in `request'
    from /app/vendor/bundle/ruby/2.3.0/gems/send_with_us-1.12.0/lib/send_with_us/api_request.rb:18:in `post'
    from /app/vendor/bundle/ruby/2.3.0/gems/send_with_us-1.12.0/lib/send_with_us/api.rb:260:in `customer_create'
    from (irb):35
    from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.5.1/lib/rails/commands/console.rb:110:in `start'
    from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.5.1/lib/rails/commands/console.rb:9:in `start'
    from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /app/vendor/bundle/ruby/2.3.0/gems/railties-4.2.5.1/lib/rails/commands.rb:17:in `<top (required)>'
    from /app/bin/rails:9:in `require'
    from /app/bin/rails:9:in `<main>'

Here's some more detail about the address:

irb(main):039:0> email.valid_encoding?
=> true
irb(main):040:0> email.encoding
=> #<Encoding:UTF-8>

The only non-ASCII character it contains is http://unicode.scarfboy.com/?s=2006.

Allow developers to configure timeout

Client version

Latest

Expected behaviour

Client allows the developer to conveniently set open_timeout for network calls, at least when configuring a client if not per call.

Actual behaviour

Client does not allow the developer to set open_timeout.

A recent SWU outage led our email sends to time out after the default Net::HTTP timeout of 60s (which for us resulted in a backup in our job queues). We would like to be able to configure this timeout to have more control to do what's best for our system.

Steps to reproduce

N/A

Add get drip deactivate method

function remove_from_all_drip_campaigns missing

In the Ruby version, the query is missing from the drip_campaigns deactivate POST.
In the PHP Version exists.

can you implement that?

Batch requests?

Hey, I'd love to use batch endpoint with this gem, is that supported?

letter opener for development

It would be cool if you guys could hook into letter opener for development. Like if there is a call to the api with a test key, you send back the html, and the email is rendered in a new tab.

How to do parallel requests?

This is a question, not a feature-request.

I'm just curious the expected way to send multiple requests to SendWithUs at once with this gem. It takes like 0.5 second to send a single email (if waiting on the http request response) so sending large amounts of emails in a blocking sync way is not ideal.

Thanks!

License missing from gemspec

RubyGems.org doesn't report a license for your gem. This is because it is not specified in the gemspec of your last release.

via e.g.

  spec.license = 'MIT'
  # or
  spec.licenses = ['MIT', 'GPL-2']

Including a license in your gemspec is an easy way for rubygems.org and other tools to check how your gem is licensed. As you can imagine, scanning your repository for a LICENSE file or parsing the README, and then attempting to identify the license or licenses is much more difficult and more error prone. So, even for projects that already specify a license, including a license in your gemspec is a good practice. See, for example, how rubygems.org uses the gemspec to display the rails gem license.

There is even a License Finder gem to help companies/individuals ensure all gems they use meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough issue that even Bundler now generates gems with a default 'MIT' license.

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue with a nice message. In either case, I'll follow up. Thanks for your time!

Appendix:

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), GitHub has created a license picker tool. Code without a license specified defaults to 'All rights reserved'-- denying others all rights to use of the code.
Here's a list of the license names I've found and their frequencies

p.s. In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :). See the previous link or my blog post about this project for more information.

This error is local or in the server?

In the companypage the smtp configured fine. Now I'm trying to use the Ruby example, but I got this?

Conn close because of connect error SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
Error - OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

I would like to know if this is a Firewall issue or the problem is on the server.

function get_events missing

In the Ruby version, the query is missing from the log events.

PHP Version:
public function get_events($log_id) { $endpoint = "logs/" . $log_id . "/events"; return $this->api_request($endpoint, self::HTTP_GET); }

can you implement that?

Is it possible to remove Gemfile.lock?

Hi there!

If you are working on a gem, you should not add your Gemfile.lock file into the repo, do you think you can remove it? We are having some issues with it.

Thanks!

Remove customer from group method signature

It looks like this method is missing the arguments in its definition:

def customer_remove_from_group()
  endpoint = "customers/#{email_address})/groups/#{group_id}"
  SendWithUs::ApiRequest.new(@configuration).delete(endpoint)
end

There is also an extra ')' right after the email_address interpolation

configuration for send attachments

Hello,
i am having some trouble on including attachments.

I used these configurations:

attachment = {:filename => 'myfile.txt', :attachment => '/Users/dev/myfile.txt'}
# attachments = { filename: "myfile.txt", attachment: File.open('/Users/dev/myfile.txt') }

      opts_to_send = {
         ...
         ...
        :data => {
          :subject => subject
        },
        :files =>  [attachments]
        ...
      }

What am I missing?

Lmk

Thank you!

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.