Coder Social home page Coder Social logo

sendgrid-ruby's Introduction

Special Announcement

We have released a v3 beta branch for this library that supports our new v3 Mail Send endpoint which is in open beta. The v3/mail/send/beta endpoint is not a production endpoint, so you should not integrate with it for your production email sending. However, when we make this an officially released feature it will be available at v3/mail/send.

Please try it out and let us know what you think about the endpoint and the library in the issues area of this repo, all of your feedback will be taken into account to influence the endpoint and this library.

Beginning with v3/mail/send/beta, the new version of our library will only support v3 endpoints.. Once this endpoint is out of beta, we will update the endpoint, removing the “/beta” from the URI. At this point, the v3 beta branch will be merged to master and will be our official library going forward. This means that we will no longer formally support the v2 mail.send.json endpoint in any of our libraries.

So long as you are not automatically pulling new versions of the library into your production code base, your integration will not break regardless of which endpoint you’re using. By the way, don't pull new versions into your production code base, because breaking changes break things.

The /api/mail.send.json endpoint, known as v2 mail send, is NOT going away. It will continue to work as it always has, happily sending your emails along as if nothing happened.

SendGrid::Ruby

This Gem allows you to quickly and easily send emails through SendGrid's Web API using native Ruby.

You can read our official documentation on the Web API's Mail feature here.

BuildStatus

Installation

Add this line to your application's Gemfile:

gem 'sendgrid-ruby'

And then execute:

$ bundle

Or install it yourself using:

$ gem install sendgrid-ruby

Usage

Create a new client with your SendGrid API Key.

require 'sendgrid-ruby'

# As a hash
client = SendGrid::Client.new(api_key: 'YOUR_SENDGRID_APIKEY')

# Or as a block
client = SendGrid::Client.new do |c|
  c.api_key = 'YOUR_SENDGRID_APIKEY'
end

Create a new Mail object and send:

mail = SendGrid::Mail.new do |m|
  m.to = '[email protected]'
  m.from = '[email protected]'
  m.subject = 'Hello world!'
  m.text = 'I heard you like pineapple.'
end

res = client.send(mail)
puts res.code
puts res.body
# 200
# {"message"=>"success"}

You can also create a Mail object with a hash:

res = client.send(SendGrid::Mail.new(to: '[email protected]', from: '[email protected]', subject: 'Hello world!', text: 'Hi there!', html: '<b>Hi there!</b>'))
puts res.code
puts res.body
# 200
# {"message"=>"success"}

Attachments

Attachments can be added to a Mail object with the add_attachment method. The first parameter is the path to the file, the second (optional) parameter is the desired name of the file. If a file name is not provided, it will use the original filename.

mail.add_attachment('/tmp/report.pdf', 'july_report.pdf')

Inline Content

Inline content can be added to a Mail object with the add_content method. The first parameter is the path to the file, the second parameter is the cid to be referenced in the html.

mail = SendGrid::Mail.new do |m|
  m.to = '[email protected]'
  m.from = '[email protected]'
  m.subject = 'Hello world!'
  m.text = 'I heard you like the beach.'
  m.html = 'I heard you like the beach <div><img src="cid:beach"></div>'
end
mail.add_content('/tmp/beach.jpg', 'beach')
result = client.send(mail)

Available Params

params = {
	:to,
	:to_name,
	:from,
	:from_name,
	:subject,
	:text,
	:html,
	:cc,
	:cc_name,
	:bcc,
	:bcc_name,
	:reply_to,
	:date,
	:smtpapi,
	:attachments,
	:template
}

Setting Params

Params can be set in the usual Ruby ways, including a block or a hash.

mail = SendGrid::Mail.new do |m|
  m.to = '[email protected]'
  m.from = '[email protected]'
end

client.send(SendGrid::Mail.new(to: '[email protected]', from: '[email protected]'))

:to

Using the :to param, we can pass a single email address as a string, or an array of email address strings.

mail = SendGrid::Mail.new
mail.to = '[email protected]'
# or
mail.to = ['Example Dude <[email protected]>', '[email protected]']
# or
mail.to = ['[email protected]', '[email protected]']

:from

mail = SendGrid::Mail.new
mail.from = '[email protected]'

:cc

As with :to, :cc can take a single string or an array of strings.

mail = SendGrid::Mail.new
mail.cc = ['[email protected]', '[email protected]']

:bcc

As with :to and :cc, :bcc can take a single string or an array of strings.

mail = SendGrid::Mail.new
mail.bcc = ['[email protected]', '[email protected]']

:subject

mail = SendGrid::Mail.new
mail.subject = 'This is a subject string'

Email Bodies:

:text

Using the :text param allows us to add plain text to our email body.

mail = SendGrid::Mail.new
mail.text = 'WHATTUP KITTY CAT!?'

:html

Using the :html param allows us to add html content to our email body.

mail = SendGrid::Mail.new
mail.html = '<html><body>Stuff in here, yo!</body></html>'

:template

The :template param allows us to specify a template object for this email to use. The initialized Template will automatically be included in the smtpapi header and passed to SendGrid.

template = SendGrid::Template.new('MY_TEMPLATE_ID')
mail.template = template

Working with Templates

Another easy way to use the SendGrid Templating system is with the Recipient, Mail, Template, and TemplateMailer objects.

Create some Recipients

users = User.where(email: ['[email protected]', '[email protected]'])

recipients = []

users.each do |user|
  recipient = SendGrid::Recipient.new(user.email)
  recipient.add_substitution('first_name', user.first_name)
  recipient.add_substitution('city', user.city)

  recipients << recipient
end

Create a Template

template = SendGrid::Template.new('MY_TEMPLATE_ID')

Create a Client

client = SendGrid::Client.new(api_user: my_user, api_key: my_key)

Initialize mail defaults and create the TemplateMailer

mail_defaults = {
  from: '[email protected]',
  html: '<h1>I like email</h1>',
  text: 'I like email',
  subject: 'Email is great'
}

mailer = SendGrid::TemplateMailer.new(client, template, recipients)

Mail it!

mailer.mail(mail_defaults)

Using SendGrid's X-SMTPAPI Header

To utilize the X-SMTPAPI header, we have directly integrated the SendGridJP/smtpapi-ruby gem. For more information, view our SMTPAPI docs page.
header = Smtpapi::Header.new
header.add_to(['[email protected]', '[email protected]'])
header.add_substitution('keep', ['secret'])        # sub = {keep: ['secret']}
header.add_substitution('other', ['one', 'two'])   # sub = {keep: ['secret'], other: ['one', 'two']}
header.add_unique_arg("unique_code", "8675309")
header.add_category("Newsletter")
header.add_filter('templates', 'enable', 1)	   # necessary for each time the template engine is used
header.add_filter('templates', 'template_id', '1234-5678-9100-abcd')
header.set_ip_pool("marketing_ip_pool")
mail.smtpapi = header

Testing

bundle exec rake test

Deploying

  1. Confirm tests pass bundle exec rake test
  2. Bump the version in lib/sendgrid/version.rb and spec/lib/sendgrid_spec.rb
  3. Update CHANGELOG.md
  4. Commit Version bump vX.X.X
  5. rake release
  6. Push changes to GitHub
  7. Release tag on GitHub vX.X.X

Contributing

  1. Fork it ( https://github.com/[my-github-username]/sendgrid-ruby/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Hit up @rbin or @sendgrid on Twitter with any issues.

sendgrid-ruby's People

Contributors

dylangriffith avatar eddiezane avatar kaixiang avatar kawahara avatar mikedebock avatar nquinlan avatar ohhdear avatar rbin avatar thinkingserious avatar vasspilka avatar

Watchers

 avatar  avatar

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.