Coder Social home page Coder Social logo

sendgrid / sendgrid-ruby Goto Github PK

View Code? Open in Web Editor NEW
617.0 211.0 321.0 1.01 MB

The Official Twilio SendGrid Led, Community Driven Ruby API Library

Home Page: https://sendgrid.com

License: MIT License

Ruby 99.42% HTML 0.22% Dockerfile 0.16% Makefile 0.19%
ruby sendgrid email transactional-emails

sendgrid-ruby's Introduction

Twilio SendGrid Logo

Travis Badge Gem Version MIT licensed Twitter Follow GitHub contributors Open Source Helpers

This library allows you to quickly and easily use the Twilio SendGrid Web API v3 via Ruby.

Version 3.X.X+ of this library provides full support for all Twilio SendGrid Web API v3 endpoints, including the new v3 /mail/send.

This library represents the beginning of a new path for Twilio SendGrid. We want this library to be community driven and Twilio SendGrid led. We need your help to realize this goal. To help make sure we are building the right things in the right order, we ask that you create issues and pull requests or simply upvote or comment on existing issues or pull requests.

If you need help using SendGrid, please check the Twilio SendGrid Support Help Center.

Table of Contents

Installation

Prerequisites

  • Ruby version >= 2.4 (except version 2.6.0)
  • The Twilio SendGrid service, starting at the free level

Setup Environment Variables

Update the development environment with your SENDGRID_API_KEY, for example:

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

Install Package

Add this line to your application's Gemfile:

gem 'sendgrid-ruby'

And then execute:

bundle

Or install it yourself using:

gem install sendgrid-ruby

Dependencies

Quick Start

Hello Email

The following is the minimum needed code to send an email with the /mail/send Helper (here is a full example):

With Mail Helper Class

require 'sendgrid-ruby'
include SendGrid

from = SendGrid::Email.new(email: '[email protected]')
to = SendGrid::Email.new(email: '[email protected]')
subject = 'Sending with Twilio SendGrid is Fun'
content = SendGrid::Content.new(type: 'text/plain', value: 'and easy to do anywhere, even with Ruby')
mail = SendGrid::Mail.new(from, subject, to, content)

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.mail._('send').post(request_body: mail.to_json)
puts response.status_code
puts response.body
puts response.parsed_body
puts response.headers

For more complex scenarios, please do not use the above constructor and instead build your own personalization object as demonstrated here.

Without Mail Helper Class

The following is the minimum needed code to send an email without the /mail/send Helper (here is a full example):

require 'sendgrid-ruby'
include SendGrid

data = JSON.parse('{
  "personalizations": [
    {
      "to": [
        {
          "email": "[email protected]"
        }
      ],
      "subject": "Sending with Twilio SendGrid is Fun"
    }
  ],
  "from": {
    "email": "[email protected]"
  },
  "content": [
    {
      "type": "text/plain",
      "value": "and easy to do anywhere, even with Ruby"
    }
  ]
}')
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.mail._("send").post(request_body: data)
puts response.status_code
puts response.body
puts response.parsed_body
puts response.headers

General v3 Web API Usage (With Fluent Interface)

require 'sendgrid-ruby'
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.suppression.bounces.get()
puts response.status_code
puts response.body
puts response.parsed_body
puts response.headers

General v3 Web API Usage (Without Fluent Interface)

require 'sendgrid-ruby'
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client._("suppression/bounces").get()
puts response.status_code
puts response.body
puts response.parsed_body
puts response.headers

Processing Inbound Email

Please see our helper for utilizing our Inbound Parse webhook.

Usage

Use Cases

Examples of common API use cases, such as how to send an email with a transactional template.

Announcements

All updates to this library are documented in our CHANGELOG and releases.

How to Contribute

We encourage contribution to our libraries (you might even score some nifty swag), please see our CONTRIBUTING guide for details.

Troubleshooting

Please see our troubleshooting guide for common library issues.

About

sendgrid-ruby is maintained and funded by Twilio SendGrid, Inc. The names and logos for sendgrid-ruby are trademarks of Twilio SendGrid, Inc.

If you need help using SendGrid, please check the Twilio SendGrid Support Help Center.

License

The MIT License (MIT)

sendgrid-ruby's People

Contributors

af4ro avatar alanunruh avatar awwa avatar brokenthumbs avatar ciceropablo avatar colto avatar cristianossd avatar crweiner avatar dylangriffith avatar eddiezane avatar eshanholtz avatar gustavocaso avatar kernkw avatar kylearoberts avatar mikedebock avatar mptap avatar pushkyn avatar rahul26goyal avatar rakvium avatar rbin avatar rogerpodacter avatar rohan-techfreak avatar shwetha-manvinkurke avatar skalee avatar thepriefy avatar thinkingserious avatar tricknotes avatar twilio-ci avatar twilio-dx avatar wattsinabox 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  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  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  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

sendgrid-ruby's Issues

There Doesn't Appear to be Enough Information in the Docs to Run the Tests Locally

Issue Summary

I followed the directions in setting up the repo for running the tests. For sure there's not enough information b/c I ran into a number of issues in just basic setup. Most of the stuff is typical and I'm smart enough to figure it out. However, I get rake, minitest and everything else working and then I run into this:

Errno::ECONNREFUSED: Connection refused - connect(2) for "localhost" port 4010

And looking through the codebase, I can't find anything that would start a service on 4010: no Procfile, no sinatra config file, nothing.

Steps to Reproduce

  1. Install rake, bundler, etc.
  2. Type rake or rake test

I expect that I should be able to type rake test or at least be able to type ruby test_mail_host.rb in another tab and then have rake test just work.

Technical details:

  • sendgrid-ruby Version: master (latest commit: [commit number])
  • Ruby Version: 2.2 (and 2.1, I'm trying to see if I can get your gem to work on an older version of ruby so that we can use it without having to upgrade our entire codebase).

How to set a default from?

I created a method called

def default_from
  'A name <[email protected]>'
end

But when an email is sent, in the mailbox, the sender name is email but I want to show A name.
Do I do that in the application or I have to configure in sendgrid itself?

Unexpected Mail instance `categories`, `categories=` behavior

Issue Summary

SendGrid::Mail categories behavior makes it too easy to set empty values.

Steps to Reproduce

Instantiate a new instance

sg_mail = SendGrid::Mail.new

I know it will end up being an Arrary, so try to add something to it...

sg_mail.categories << 'foo'
# NoMethodError: undefined method `<<' for nil:NilClass

Oh, categories starts nil. I guess we need to instantiate it?

sg_mail.categories = []
sg_mail.categories
=> [nil]

An Array with nil in it. ???

More misleading is that if someone expects it to accept the String category, it will not complain, it will just add nil

sg_mail.categories = 'foo'
=> "foo"

sg_mail.categories
=> [nil, nil]

Despite its own awareness that it is an Array and its delegation of methods, it doesn't actually let me treat it like an array, so I don't have a clear way of fixing this.

sg_mail.categories.compact
=> []

sg_mail.categories
=> [nil, nil]

You could improve this by doing two things:

  • New instances of Sendgrid::Mail should set categories to an empty Array. If nothing else, that would let callers know to treat it like an array and avoid categories= in the first place.
    def categories
      @categories ||= []
    end

https://github.com/sendgrid/sendgrid-ruby/blob/master/lib/sendgrid/helpers/mail/mail.rb#L908

  • Fix categories=. I don't think that what you have defined works at all. When you call [string] on a String, you just select that pattern from the string. So if someone did do this:
# I guess this was what you had in mind?
sg_mail.categories = { categories: 'foo' }

# It would become this:
{ category: 'foo' }.to_json
=> "{\"category\":\"foo\"}"

# And then you're just pulling the word `category` out of it and storing it in your array
"{\"category\":\"foo\"}"['category']
=> "category"

This is also why calling categories= results in nil entries: it converts everything to a String with to_json and then whatever_your_string_is['categories'] always returns nil.

Technical details:

  • sendgrid-ruby Version: 4.0.2
  • Ruby Version: 2.2.3

Substitutions in a template

Question:

To substitute parameters, like -first_name-, -last_name-, etc, the only option is to use SMTP API as specified here(using-sendgrids-x-smtpapi-header). Is that correct?

I did not see any option to set substitutions directly on the Sendgrid::Mail object.

mail = SendGrid::Mail.new
mail.subs = 'IS_IT_POSSIBLE_TO_SECIFY_SUBSTITUTIONS_HERE'

SendGrid fails when a name contains comma character

Issue Summary

When names include a comma character "," the email is dropped by SendGrid due to reason "Invalid", because it interprets the wrong email address. In the Activity view, SendGrid appears to have tried to send to part of the name field instead of the email field, indicating the the "comma" was used even though it is in part of a string.

Steps to Reproduce

Here is the repro call to SendGrid::API:

    params = {
      "template_id" => "88dd23ff-f322-40a4-b646-1144c43340a8",
      "subject" => "Forgot your password?",
      "personalizations" =>
        [
          {
            "to" =>
              [
                {
                  "email" => "[email protected]",
                  "name" => "Figma, Inc."
                }
              ],
            "substitutions" =>
              {
                "{{URL_ESCAPED_VALIDATION_TOKEN}}" => "***REDACTED***",
                "{{URL}}" => "https://www.figma.com",
                "{{SUPPORT_EMAIL}}" => "[email protected]",
                "{{UNSUBSCRIBE_TOKEN}}" => "***REDACTED***"
              }
          }
        ],
      "tracking_settings" => {
        "click_tracking" => {"enable" => false},
        "open_tracking" => {"enable" => false}
      },
      "content" =>
        [
          {"type" => "text/html", "value" => " "}
        ],
      "from" =>
        {
          "email" => "[email protected]",
          "name" => "Figma"
        }
    }

    response = sendgrid.client.mail._('send').post(request_body: params)
    puts response.to_json

The result is a 202, but the email does not get sent because it is rejected due to "Invalid", and the reported email address it tried sending to is "Figma" instead of "[email protected]".

Here is the result from sendgrid.client.suppression.invalid_emails.get

[{\"created\":1468461165,\"email\":\"figma\",\"reason\":\"Invalid address\"}]

Are there undocumented rules for names? Are we supposed to encode them in some way or strip special characters? Why doesn't your platform do this for us? Why doesn't your platform reject the request?

Technical details:

  • sendgrid-ruby Version: sendgrid-ruby 3.0.4
  • Ruby Version: 2.3.1

Multiple substitutions in one method call?

Hi there,

Ive noted from the readme that the current way to handle multiple substitutions is to make multiple calls to add_substitution. Would there be any interest in supporting an add_substitutions method, which could take a hash and reduce the need to call this multiple times?

How Can I Create The Attachement Content Base64 Encoded?

Issue Summary

attaching a pdf or a zip file.
Used code:
Base64.encode64(File.binread(file_path))
If Base64.encode64 cannot create a proper attachment content, then which library/method I should use to get a proper content which will be accepted by Sendgrid web api v3?

Steps to Reproduce

I get this error:
{"errors":[{"message":"The attachment content must be base64 encoded.","field":"attachments.0.content","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.attachments.content"}]}

Technical details:

  • sendgrid-ruby Version: 4.0.2
  • Ruby Version: 2.2.3

Mail parameter aliases or examples

Just spent the longest time trying to get the "fromname" param to work because I was referencing the Web API docs and, since most params are identical, just assumed it'd be set using "fromname". It needed to be set using "from_name".

I think aliasing the names or adding examples of every transformed param to the readme would help others have a smoother time using the gem.

cannot actually assign an array to mail.to

Readme.md states this:

mail.to = ['Example Dude <[email protected]>', '[email protected]']

That exact example throws an error on send: invalid email address. Even using pure email addresses.

mail_client = SendGrid::Client.new do |c|
      c.api_user = ENV['SENDGRID_USERNAME']
      c.api_key = ENV['SENDGRID_PASSWORD']
end
outbound.each do |o|
        mail = SendGrid::Mail.new do |m|
          mailstr = o.email_to
          m.to = ['Example Dude <[email protected]>', '[email protected]']
          m.from = o.email_from
          m.subject = o.email_subject
          m.html = o.email_content
        end
        send_result = mail_client.send(mail)
end```

#SendGrid::Exception: {"message": "error", "errors": ["Invalid email address Example Dude <[email protected]>"]}

Template caches recipient list

This did not do what I expected it to do, and caused a lot of trouble:

client    = SendGrid::Client.new(api_key: 'SG.abcdefg-AB.L0r3m1p5unaaaaaa')
template  = SendGrid::Template.new('88888888-8888-4000-8000-888888888888')

users.each do |user|

    recipient = SendGrid::Recipient.new user.email

    mailer = SendGrid::TemplateMailer.new(client, template, [recipient])

    mailer.mail({
        from:    "[email protected]",
        subject: "Confidential information about your account",
        html:    "<h1>Some info</h1> ..."
    })

end

Spoiler alert: You'll end up sending A's email to A, B's email to B and A, C's email to C, B & A, etc, etc.

TemplateMailer adds recipient to a recipient list that is cached in template, and it is never cleared out. Recipients keep getting added to the recipient list stored in template.

Perhaps this is by design, but I think it is a counter-intuitive and dangerous design.

Add support for Non-X-SMTPAPI Headers

From API docs, there is support for headers.

My scenario required me to have both X-SMTPAPI's unique_args header, and Non-X-SMTPAPI custom header.

I could not find any way to add Non-X-SMTPAPI headers from either README.md nor from the source code, because there is no attr_accessor :headers

From what I understand, this will entail merging both Sendgrid::Mail @smtpapi and @headers in the source code.

Using TemplateMailer to send email without a body

{"errors":["Missing email body"],"message":"error"}

My goal is to use the sendgrid-ruby gem to send a template without using an email body (the template should be the body). I receive the above error when using TemplateMailer.

I tried duplicating the code internal to the gem to see if I could work around it, but am still receiving the same error. Here's my code:

mail_defaults = { from: '[email protected]', from_name: 'Admin', subject: 'Email is great' }
mail = SendGrid::Mail.new(mail_defaults)
mail.template = SendGrid::Template.new('my_template_id')

client = SendGrid::Client.new(api_user: ENV['SENDGRID_USERNAME'], api_key: ENV['SENDGRID_PASSWORD'])
client.send(mail.to_h)

Is there a best practice for this that I am missing? Or could this be a bug?

cc and bcc is not working

I am trying to send emails using template api

client = SendGrid::Client.new(api_user: ENV['SENDGRID_USERNAME'], api_key: ENV['SENDGRID_PASSWORD'])
@user_emails = ['[email protected]', '[email protected]']

@header = Smtpapi::Header.new
@header.add_to(@user_emails)
@header.add_filter('templates', 'enable', 1)    # necessary for each time the template engine is used
@header.add_filter('templates', 'template_id', template_id)
mail = SendGrid::Mail.new do |m|
      m.to = @user_emails
      m.from = from
      m.from_name = fromname
      m.bcc = bcc
      m.subject = ' '
      m.smtpapi = @header
      m.html = '<img alt="" height="1" src="" style="display:none;" width="1" />'
    end
client.send(mail)

The to is working fine , but bcc is not working . Is it some kind of bug

Getting started

Issue Summary

I'm struggling to understand the documentation for how to get started using WebAPI v3.

The authentication section of the getting started section says " To use keys, you must set a plain text header named “Authorization” with the contents of the header being “Bearer XXX” where XXX is your API Secret Key." https://sendgrid.com/docs/API_Reference/Web_API_v3/How_To_Use_The_Web_API_v3/authentication.html

Q1: Where & how do I set this text header?

The transactional templates overview says "Including the template ID in the templates parameter of the Web API v3 Mail Send endpoint" This page has a link to Ruby libraries, which in turn links to this gem.

Q2: Where and how do I include a template ID in the endpoint?

The sendgrid-ruby gem documentation has an example for various ways to use the gem. The examples for General v3 Web API Usage distinguish between cases where fluent influence is or is not used. Googling fluent influence doesnt lead me to any enlightenment.

Q3: What is fluent influence? How do I determine whether or not I should be using it?

If I do pick a General v3 Web API Usage option,

where in my app do I write these lines?

 require 'sendgrid-ruby'
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client._("suppression/bounces").get()
puts response.status_code
puts response.body
puts response.headers

Once I've figured out how and where to write the above lines, how do I ask my app to send a template email that I have made in Sendgrid's transactional templates section?

Thank you very much for your help in getting started.

Technical details:

gem 'sendgrid-ruby'
gem 'sendgrid-rails', '~> 2.0'
gem 'mail'
ruby "2.3.0"

bundle install fails due to listen gem

Installing listen 3.1.5

Gem::InstallError: listen requires Ruby version >= 2.2.3, ~> 2.2.
...
An error occurred while installing listen (3.1.5), and Bundler cannot continue.
Make sure that `gem install listen -v '3.1.5'` succeeds before bundling.

Readme.md block example throws error

# Or as a block
client = SendGrid::Client.new do |c|
  c.api_user = 'SENDGRID_USERNAME'
  c.api_key = 'SENDGRID_PASSWORD'
end
``
# SendGrid::Exception: api_user and api_key are required

sending email with multiple content types (text+html) fails

Issue Summary

sending email with multiple content types (text+html) fails. Error received is "expected object but received string for content.0" .. not sure how to properly specify the email as there is no documentation anywhere to do it properly with v3 api.

Steps to Reproduce

    mail = Mail.new()
    mail.from = Email.new(email: "[email protected]")
    mail.subject = "Hello World from the SendGrid Ruby Library"
    personalization = Personalization.new()
    personalization.to = Email.new(email: "[email protected]")
    mail.personalizations = personalization
    mail.contents = Content.new(type: "text/plain", value: "some text here")
    mail.contents = Content.new(type: "text/html", value: "<html><body>some text here</body></html>")

Technical details:

  • sendgrid-ruby Version: master
  • Ruby Version: 2.2

Can't use smtpapi to send emails with templates

I'm trying to use sendgrid-ruby to send multiple messages with the same template. At frist I tried to just use mail.smtpapi API:

require "bundler/setup"
require "sendgrid-ruby"

client = SendGrid::Client.new(api_user: 'xxx', api_key: 'xxx')
mail = SendGrid::Mail.new

mail.from = "[email protected]"

mail.smtpapi.add_to('[email protected]')
mail.smtpapi.add_to('[email protected]')
mail.smtpapi.add_filter 'templates', 'enabled', 1
mail.smtpapi.add_filter 'templates', 'template_id', '49ba095b-f291-47a9-84e8-e82e473efa6c'
mail.smtpapi.add_substitution '-name-', [ 'Yay first user :)' , 'Ho last user']
mail.smtpapi.add_substitution 'subject', ['Yay Guilherme :)']

But I got a missing subject error:

fuelzee_api (sendgrid-mailer) > ruby sendgrit_test.rb
/Users/guiocavalcanti/.rvm/gems/ruby-2.0.0-p481/gems/sendgrid-ruby-0.0.3/lib/sendgrid-ruby.rb:29:in `block in send': {"message": "error", "errors": ["Missing subject"]} (SendGrid::Exception)

Then I tried to set some Sendgrid::Mail attributes manually:

client = SendGrid::Client.new(api_user: 'xxx', api_key: 'xxx')
mail = SendGrid::Mail.new

mail.from = "[email protected]"
mail.subject = "Welcome"
mail.text = "Body"

mail.smtpapi.add_to('[email protected]')
mail.smtpapi.add_to('[email protected]')
mail.smtpapi.add_filter 'templates', 'enabled', 1
mail.smtpapi.add_filter 'templates', 'template_id', '49ba095b-f291-47a9-84e8-e82e473efa6c'
mail.smtpapi.add_substitution '-name-', [ 'Yay first user :)' , 'Ho last user']
mail.smtpapi.add_substitution 'subject', ['Yay Guilherme :)']

client.send(mail)

This time the message was sent but without the substitutions. You can see the template I defined here:

Does not support the majority of SendGrid v3 API

Hello SendGrid friends,

After using SendGrid for a few years as a simple SMTP endpoint with a little bit of analytics baked in, I was excited to finally have the opportunity to dive deep into more advanced features, such as Advanced Suppression Management, Marketing Campaigns, and Threads.

Looking at this library, however, the majority of SendGrid's Web API v3 appears to be unsupported:

  • Bounces
  • Suppression Management
  • Marketing Campaigns
  • Categories
  • Users/Subusers
  • Stats

Are there any plans to support any of these through the sendgrid-ruby gem and/or will pull requests be accepted on those items?

My company really likes SendGrid and wish to know where it is best to apply our efforts:

  1. Toward our own Ruby implementation of our needed features (particularly Suppression Management, Categories and Bounces).
  2. Toward a merge into this project using similar code style and strategies (which might not even be advisable, given details of the v3 API and the current implementation of SendGrid::Client).

Trouble using substitutions in templates

I have an email template set up that looks like:

I have an email template set up:

<%body%>
Welcome to the Highlight Summary
Heading
-cl1-
-cl2-
-cl3-
-cl4-
-cl5-

As I understand it, that should allow for me to use -clX- as substitution values when sending email using the ruby library. I've tried many permutations of this, but nothing works.

I would like to substitute values in for the 5 different clX tags when I send the email, and nothing for the <%body%> tag. If I include the .html or .text values in the api call, it substitutes for that but not the clX fields. I’ve tried leaving the html and text values out (which gives a “Missing email body" error), making them blank (same error), and making them a single space (no error, but the email is completely empty).

How can I get these fields substituted into the template?

This is the code I’m using to send:

recipients = {
  "Adam Fields" => "[email protected]"
}
recipients.each{|name, email|
  mail = SendGrid::Mail.new do |m|
    m.to = email
    m.to_name = name
    m.from = "[email protected]"
    m.from_name = "YYYYYYYY"
    m.subject = 'Daily Summary'
     #        m.html = all_output
    m.html = " "
    m.text = " "
  end
  header = Smtpapi::Header.new
  header.add_category("Daily Email")
  header.add_filter('template', 'enable', 1)     # necessary for each time the template engine is used
  header.add_filter('template', 'template_id', 'ZZZZZZZZZZZZZZZZZZZ')
  header.add_substitution('-cl1-', ['ishkabibble'])
  mail.smtpapi = header 
  puts "sending email to #{name} <#{email}>"
  puts sg_client.send(mail)
}

Send generated file as attachment

It seems the add_attachment method only works with files. What about generated attachments that live in memory? How can I send those?

reply_to has no effect

I'm setting the reply_to but when you click to reply to the email, it's replying to the to email. Am I doing something wrong?

Upgrading from 1.x to 4.x breaks BCC email setting configuration

Issue Summary

I've sent in a ticket to [email protected] and am just getting generic replies.. not much help there, so I thought I'd post here...

In SendGrid, Settings > Mail Settings > BCC is configured.

I migrated 1.x to 4.x, wrote the new code, tested it, everything works great.

The only problem is that now my BCC (sends a copy of every email sent) is now broken: there is no subject or to address for the email, but the body is there. I thought it had something to do with personalizations, so I set the subject on both the SendGrid::Mail object and the Personalization object, no effect.

screen shot 2016-08-08 at 3 44 18 pm

Desired effect:

My BCC address receives the exact email that the recipient received, including body, subject, to field, etc.

Technical details:

  • sendgrid-ruby Version: 4.0.2
  • Ruby Version: 2.3

documentation is poor / lacking

Issue Summary

I received the "we have a new version of the api" email and decided to upgrade. Certainly feels more like a downgrade to me. Before, sending email with the sendgrid-ruby gem was simple. Now it is not. I don't see how these changes benefit your customers (i.e. programmers trying to leverage sendgrid), it looks like you just wanted to refactor the code and then release a version that breaks everybody and then you provide poor documentation. You may like the code more this way but your customers (i.e. me) do not. Why don't you get your ego out of the way and stop writing code that serves you and write code that serves us. Regarding documentation, in your kitchen_sink example:

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'], host: 'https://api.sendgrid.com')
response = sg.client.mail._('send').post(request_body: mail.to_json)
puts response.status_code
puts response.response_body
puts response.response_headers

I followed this and get:
undefined method `response_body' for #SendGrid::Response:0x005602531ef810

muppets...

Steps to Reproduce

  1. This is the first step
  2. This is the second step
  3. Further steps, etc.

Any other information you want to share that is relevant to the issue being reported. Especially, why do you consider this to be a bug? What do you expect to happen instead?

Technical details:

  • sendgrid-ruby Version: master (latest commit: [commit number])
  • Ruby Version: 2.2

Subuser support

Hi,

I need to be able send email through a subuser/account. I don't see that support documented or in the source code.

No upgrade notes for 3.0?

The note in the changelog regarding Breaking change to support the v3 Web API doesn't help the upgrade process much.

Any chance of some documentation on upgrading from 2.x?

Question about variable substitution using the Mail helper

This is basically the same question as #58 but I'm afraid I didn't understand the answer there.

I'm trying to use the Mail object in this gem to hit the Web v3 API, but I can't seem to get variable substitution working. Is my only option to use the SMTP API or am I missing something?

My template has the following included in it: -templatevar-

My mail.to_json looks like this:
{"from"=>{"email"=>"[email protected]"}, "subject"=>"Trying out substitutions", "personalizations"=>[{"to"=>[{"email"=>[email protected]"}]}], "content"=>[{"type"=>"text/html", "value"=>"A variable should go right here: -variable-"}], "template_id"=>"ZZZZZ", "sections"=>{"%variable%"=>"Percent sub", "-variable-"=>"Dash sub", "-templatevar-"=>"Dash sub on template var"}}

I've been banging my head against this and feel like I'm missing something critical here. Thanks in advance for any help!

substitutions with transactional templates is broken

Issue Summary

substitutions with transactional templates is broken

Steps to Reproduce

  1. create a transactional template
  2. create some substitution vars with %user_name% or user_name format
  3. Try to send email using example code (v3 api)

variables should be replaced properly in the transactional template. This is badly broken. Also %var% inside things like href="%var%" or src="%var%" are not respected at all when trying to save in the code editor online on sendgrid.com. The template removes the % symbols after saving.

Technical details:

  • sendgrid-ruby Version: master
  • Ruby Version: 2.2.3

Add/set section doesn't seem to do anything

I set up a test script nearly directly from the readme file to play with substitutions and sections. Subs work, but sections don't seem to have any effect.

#based on the repo sendgrid/sendgrid-ruby

require 'sendgrid-ruby'

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

mail = SendGrid::Mail.new do |m|
  m.to = '[email protected]'
  m.from = '[email protected]'
  m.subject = 'Hello ' + Time.now.strftime('%Y%m%d%H%M%S') + '-charger-'
  m.text = '-bomber- I heard you like pineapple. keep this other thing! <br /> -charge-'
end

mail.smtpapi.set_sections({'-charge-' => 'This ship is useful.'})
mail.smtpapi.add_section('-bomber-', ['Only for sad kansans.'])

mail.smtpapi.add_substitution('keep', ['secret'])        # sub = {keep: ['secret']}
mail.smtpapi.add_substitution('other', ['one', 'two'])   # sub = {keep: ['secret'], other: ['one', 'two']}

mail.smtpapi.add_section('-charger-', ['This ship is useless.'])

mail.smtpapi.add_substitution('useless', ['ITWORKED'])        # sub = {keep: ['secret']}

#client.send(SendGrid::Mail.new(to: '[email protected]', from: '[email protected]', subject: 'Hello world!', text: 'Hi there!', html: '<b>Hi there!</b>'))

puts client.send(mail)
# {"message":"success"}

The email I receive is:

Subject:

Hello 20141015123749-charger-

Message:

-bomber- I heard you like pineapple. secret this one thing! <br /> -charge-

"keep" is replaced, "other" is replaced, but "-charger-", "-bomber-", and "-charge-" don't get replaced

Updating the template's text & html content via the sendgrid api

The documentation only shows updating the name of the template via the api. Is there a way to update the template's content through an api instead of only through the web UI? It looks like there is the TemplateMailer but I'm not sure if this is the same thing as the basic actionmailer config.

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

Does setting the html here update the template when it's passed into the TemplateMailer: SendGrid::TemplateMailer.new(client, template, recipients)

Sender Identities API End Point Location?

Issue Summary & Steps to Reproduce

I can't find the following end point in the ruby gem Docs
https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/sender_identities.html

As a result I made my best guess and tried

SENDGRID_API.client.senders.post(request_body: {
   "nickname" => "Alert",
   "from" => {
     "email" => "[email protected]",
     "name" => "Alert"
   }
})

But, I get a 403 error, even though other end points are working fine, and I have given the API Key full permissions.

Am I not using the correct end point? I believe I am following the pattern.

Also I have already whitelisted the domain the email is coming from.

Technical details:

  • sendgrid-ruby latest version
  • Ruby Version: 2.3.1

Sendgrid adding :default attachment

When inlining an image based on the code example:

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

'
end
mail.add_content('/tmp/beach.jpg', 'beach')
result = client.send(mail)

This generates a ":default" attachment which is a file with a single "0" in it when opened in a text editor. The image gets inserted as expected.

SendGrid's X-SMTPAPI Header - delivering to multiple addresses with template and subs

Hi,
I am unable to send emails to multiple users with the predefined template and substitutions. Code is as follows:

client = SendGrid::Client.new(api_key: ENV['SENDGRID_API'])
header = Smtpapi::Header.new
header.add_to(recipients_emails) // array of emails
header.add_substitution('-invitation_text-', invitation_texts) // arrays of customised texts
header.add_substitution('-landing_url-', landing_urls) // arrays of customised links
header.add_filter('templates', 'enable', 1)
header.add_filter('templates', 'template_id', ENV['BULK_EMAIL_TEMPLATE']) // template that has <% body %> only, I want the substitution to be done from my email html and text parameter

mail = SendGrid::Mail.new(email.except(:to)) // email has subject from, subject, text and html
mail.smtpapi = header
client.send(mail)

It always sends the proper email for the first recipient, but not for the rest.
Am I missing something obvious?
Thank you!

Running "Hello Email" sample code gets a 400 error response from the API

Issue Summary

I am attempting to set up my Sendgrid integration and as a first step I copied the Hello Email code on this project's root page, changed the email address to be valid, and then ran it in the Rails console. (The environment variable for my API key is valid, as well.) I get the following error:
2.3.1 :040 > response = sg.client.mail._('send').post(request_body: mail.to_json) => #<SendGrid::Response:0x007f9df0fdfa80 @status_code="400", @body="{\"errors\":[{\"message\":\"Invalid type. Expected: object, given: string.\",\"field\":\"(root)\",\"help\":\"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Request-Body-Parameters\"}]}", @headers="{\"server\"=>[\"nginx\"], \"date\"=>[\"Mon, 20 Jun 2016 19:29:20 GMT\"], \"content-type\"=>[\"application/json\"], \"content-length\"=>[\"191\"], \"connection\"=>[\"close\"], \"x-frame-options\"=>[\"DENY\"]}">

Steps to Reproduce

  1. Copy "Hello Email" code into text editor.
  2. Replace to: email address with valid personal email address.
  3. Paste the modified code into the Rails console.

Technical details:

  • sendgrid-ruby Version: 3.0.4
  • Ruby Version: 2.3.1

Invalid user name and password exception handling

We started using this gem for simple email sending. During the building phase I came across an error because I did not have my configuration setup properly. The error from SendGrid was "{"message": "error", "errors": ["Bad username / password"]}".

When the gem raises the error the message is being passed straight to the SendGrid::Exception class. Should the exception parse the json string and parse the error message out and do something like:
j = JSON.parse( message )
return super(j.try( :[], 'error' )) if ( message.try( :[], 'message' ) == 'error' && message.try(:[], 'error'.present?)
super( message )

No test

Restclient is slow, so I'd like to create a pull request to use https://github.com/nahi/httpclient instead, but there are no tests to verify functionality. Are there tests that can be checked into the repo to aid in opensource development?

Thanks,
Josh

Support add attachment into SendGrid::TemplateMailer

Hello guys.

Currently I can add a attachment into a Mail object like well described in Attachments section:
mail.add_attachment('/tmp/report.pdf', 'july_report.pdf')
Nice, I understand! My question is about this same approach but working with templates.

As described in section Working with Templates there is SendGrid::Recipient Class that supports add_substitution method, but is there a way to pass a attachment to a SendGridRecipient object? This feature could be a good ideia to a pull request?

I hope you understand my question and I really appreciate if you can help me with this.

Method #send

Hello guys,

Overriding the :send method in ruby is a very bad idea. It can lead to very strange behaviors and stop anyone from pushing a bit the enveloppe by meta-programming SendGrid::Client objects or using them in any other way than a plain client.send.

And there are use to doing these stuffs :)

No big deal given the simplicity ofthe gem. But I think it's definitely worth pointing out.

Cheers.

Error on README

Thank you for the nice Gem.
The example in X-SMTPAPI Header section doesn't work. The added filter should be "templates" instead of "template"

header.add_filter('templates', 'enable', 1)
header.add_filter('templates', 'template_id', '1234-5678-9100-abcd')

Unrecognized UTF8 Byte

Hey,

Some of our requests seem to be having UTF8 encoding issues when using the new API. Running a request with the same html body (I'm assuming that's where this fall) against the old API results in a successful send.

From what I can tell, it is rather similar to this issue brought up in the Go client: sendgrid/sendgrid-go#66

Error below.

{"errors":[{"message":"Unrecognized UTF8 Byte at position 31051","field":null,"help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Encoding-Errors"}]}

Can provide more details upon request, but just wanted to bring it to your attention since it seems to be impacting multiple clients.

Technical details:

  • sendgrid-ruby Version: master (latest commit: [commit number])
  • Ruby Version: 2.2.3

API Key support

Hi, documentation denotes that for the api_user and api_key, it requires the actual account name and password. Could you please implement the feature to use an API key instead of the SendGrid password?

require 'sendgrid-ruby'

# As a hash
client = SendGrid::Client.new(api_user: 'SENDGRID_USERNAME', api_key: 'SENDGRID_PASSWORD')

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

Thanks,
Preston

Unsubscribe tags not working on Transactional Emails

I am able to set a template and asm group id using the following: (it works great, thanks!)

mail = SendGrid::Mail.new do |m|
m.to = email_address
m.from = "Kudoso"
m.subject = ' '
m.html = " "
m.text = " "
end
header = Smtpapi::Header.new
header.add_filter('template', 'enable', 1)
header.add_filter('template', 'template_id', template_id)
header.set_asm_group(group_id)
mail.smtpapi = header
mail.template = template
client.send(mail)

However, the [unsubscribe] and [Unsubscribe_Preferences] tags in the template are not getting wired up. Instead, there is a div placed at the bottom of the email with the proper links.
Thoughts?

THANKS so much.

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.