I'm fairly new to Ruby on Rails and SendGrid.
I cannot figure out why the code sample below does not work? It does send an email using the correct template, but the dynamic data does not fill in. Any input/insight is appreciated.
require 'sendgrid-ruby'
include SendGrid
mail = SendGrid::Mail.new
mail.template_id = 'template id'
mail.from = Email.new(
email: 'someone#somewhere.com',
name: 'ABC')
personalization = SendGrid::Personalization.new
personalization.add_to(Email.new(email: 'someone#somewhere.com', name: 'ABC'))
personalization.add_dynamic_template_data(
'variable' => [
{ 'first_name' => 'John' },
{ 'last_name' => 'Doe' },
{ 'email' => 'john#doe.com' },
{ 'message' => 'The message is as follows' }
]
)
mail.add_personalization(personalization)
sgp = SendGrid::API.new(api_key: ENV['sendgrid_api_key'])
response = sgp.client.mail._('send').post(request_body: mail.to_json)
The template code looks like the following.
Hello from {{first_name}} {{last_name}}.
{{message}}
And the result ends up without the variable values filled in.
Hello from .
Twilio SendGrid developer evangelist here.
The dynamic data that you are adding is more complicated than the template. Instead of sending an array of hashes as the dynamic data, you can just send a hash. Try this instead:
personalization.add_dynamic_template_data({
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john#doe.com',
'message' => 'The message is as follows'
})
See this example in the SendGrid Ruby library docs too.
Related
I would like for a user within my ruby on rails app to be able to submit a ticket to my external ticket management system, squishlist.com. They have an api and instructions as follows. You need to authenticate and get a token and then submit the ticket with the token. From squishlist.
# get the token
https://api.squishlist.com/auth/?cfg=testcorp&user_key=privatekey&api_key=TEST-KEY-12345
=> {"token": "authtoken",
"expires": "2010-06-16 13:31:56"}
# and then the ticket with the token
https://api.squishlist.com/rest/?cfg=testcorp&token=authtoken&method=squish.issue.submit&prj=demo
POST data: {'issue_type': 1, 'subject': 'Hello, world.', 4: 'Open', 5: 10}
For testing purposes, I created a controller, route and view (page) for testing. On my controller I have the following
require 'httparty'
require 'json'
class SubmitticketController < ApplicationController
def submit_a_ticket
#cfg = 'xxxsupport'
#user_key = '4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b'
#api_key = 'MrUser411'
#project = 'excelm-manoke'
#url_new_string = 'https://api.squishlist.com/auth/?cfg='+#cfg+'&user_key='+#user_key+'&api_key='+#api_key
# https://api.squishlist.com/auth/?cfg=xxxsupport&user_key=4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b&api_key=MrUser411 - this is what is created by #url_new_string
response = HTTParty.get(#url_new_string.to_str) #submit the string to get the token
#parsed_and_a_hash = JSON.parse(response)
#token = #parsed_and_a_hash["token"]
#make a new string with the token
#urlstring_to_post = 'https://api.squishlist.com/rest/?cfg='+#cfg+'&token='+#token+'&method=squish.issue.submit&prj='+#project
#submit and get a result
#result = HTTParty.post(#urlstring_to_post.to_str, :body => {:subject => 'This is the screen name', :issue_type => 'Application Problem', :status => 'Open', :priority => 'Normal', :description => 'This is the description for the problem'})
end
end
And then I have a page that I go to to see the result of the controllers actions and it has the following code.
<p><%= #result %></p>
I know that it is working in general because of responses I have received along the way. My json is different from the example because of fields I have defined in squishlist. Can anyone help me out on this issue?
I guess the real problem is that I can't really see what the json looks like and if it is even close to match. I really don't know much about json. Should I be using something that might be easy. Should I be using ajax to submit this. Any help is greatly appreciated. I love the community here.
I solved this by adding .to_json and some heading information
#result = HTTParty.post(#urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}
I am trying to test the docusign_rest gem for possible integration into my rails app. I have set up the gem and configured it with my username, password, and integrator key. I have set the version of the api to 'v2' and checked all the of the names of both the signers and the tab fields multiple times. Here is the code I am using to make the request:
response = c.create_envelope_from_template(
status: 'sent',
email: {
subject: "Test email subject",
body: "Test email body",
},
template_id: template["templateId"],
signers: [
{
embedded: false,
name: "Name",
email: 'example#gmail.com',
role_name: "Signer1",
tabs: {
textTabs: [
{
tabLabel: "\\*address",
value: "123 Example St.",
locked: true
}
]
}
}
]
)
The request gets sent and the envelope gets sent but the 'address' field is not populated. Is there anything I am doing obviously wrong?
Thanks in advance.
Try changing the signers node in you request body to templateRoles. When you use templates in DocuSign instead of specifying the signers and their types and tabs, you assign them to existing template roles that are configured in the template. That's why no signer types should be specified in this call, just the template roles that each recipient will get matched to, and the values of any tabs you want to populate.
I've never used Ruby before so there might be some formatting or syntax issues I'm missing here, and I also have never seen the ruby gem you're referring to so not sure how stable or correct that code is. But basically this is what I think you need to do...
Right now you have:
status: 'sent',
email: {
subject: "Test email subject",
body: "Test email body",
},
template_id: template["templateId"],
signers: [
{
...
Try changing signers to templateRoles, like so:
status: 'sent',
email: {
subject: "Test email subject",
body: "Test email body",
},
template_id: template["templateId"],
templateRoles: [
{
...
The resulting http request body that you need to construct should look something like the following (in JSON format):
{
"emailSubject": "DocuSign API - Signature Request from Template",
"templateId": "ABCD1234",
"templateRoles": [
{
"email": "firstperson#email.com",
"name": "John Doe",
"roleName": "Template Role Name goes here",
"tabs": [
{
"textTabs": [
{
"tabLabel": "\\*address",
"value": "432 Sorrento Dr.",
"locked": "true"
}
]
}
]
}
],
"status": "sent"
}
Lastly, the DocuSign API Walkthrough for requesting a signature from a template is a great resource for sending from a template so this might help too. There's sample code for making this api call in 6 different languages (unfortunately Ruby is not one of them):
http://iodocs.docusign.com/APIWalkthrough/requestSignatureFromTemplate
Finally figured it out myself by modifying the gem to inspect the request. With the docusign_rest gem, the documentation on the github page is incorrect. The tabs dictionary should not be there and the items in this specific request should be underscore separated instead of camel case. Therefore, the actual request would look something like:
response = c.create_envelope_from_template(
status: 'sent',
email: {
subject: 'Test email subject',
body: 'Test email body',
},
template_id: template["templateId"],
signers: [
{
embedded: false,
name: 'Name',
email: 'example#gmail.com',
role_name: 'Signer1',
text_tabs: [
{
label: 'Address',
name: 'Address',
value: '123 Example Street.',
}
]
}
]
)
This request will allow you with the gem and v2 of the api to create an envelope from a template and prepopulate any fields. All other field types go the same way as the text_tabs array.
I am using the mailchimp-api gem and can get the submitted email to work by submitting an email and having a confirmation email sent to that email that signed up but I want to disable the double_optin flag. I am trying to do it with:
#mc = Mailchimp::API.new('my api key here')
#mc.list.subscribe('list_id', {'email' => params[:email]}, :double_optin => false)
This is still sending a confirmation email to that email address.
I really don't like how it redirects to a mailchimp page to have you confirm your subscription and have to click another button to be redirected to the site. If you could customize the confirmation email that would be one thing but having this generic confirmation page is terrible.
I am wondering if you have to have a paid account to be able to toggle the :double_optin flag?
This is what I used from mailchimp-api
subscribe(id, email, merge_vars = nil, email_type = 'html', double_optin = true, update_existing = false, replace_interests = true, send_welcome = false) ⇒ Hash
The double_optin is the parameter which will be passed
So, I used:
client.lists.subscribe(#list_id, email, nil, 'html', false)
This just expands on the answer from #Jordan above to explain why that works and why the accepted answer is incorrect.
If you are using the mailchimp-api gem, you can see in the documentation that the format for a single subscribe is subscribe(id, email, merge_vars = nil, email_type = 'html', double_optin = true, update_existing = false, replace_interests = true, send_welcome = false). After a lot of guessing and testing, I figured out that they don't want you to pass the parameter names, just the values. So, while I was originally passing double_optin: false in the function, they really just want you to pass false as the 5th parameter. In other words, this is what worked for me:
mailchimp = Mailchimp::API.new('mailchimp_api_key')
subscribe = mailchimp.lists.subscribe(
'list_ID_number',
{ email: user.email },
{ fname: user.first_name, lname: user.last_name },
'html',
false,
false,
false,
false
)
Note that the second and third parameters (email and merge_vars) were passed as hashes because that's how those parameters are defined in the documentation referenced above.
After making that change (removing the parameter names), subscriptions went right through without the confirmation emails.
Ended up getting this to work with the following:
#mc = Mailchimp::API.new('my api key here')
#mc.list.subscribe({:id => 'list_id', :email => {:email => params[:email]}, :double_optin => false})
Note the difference here is that every parameter in #mc.list.subscribe is in a hash.
The accepted answer using subscribe method does not work and will still send the confirmation email, but it is easy to do this using the batch_subscribe method instead.
First, create an array containing a hash for each subscriber you want to add (or just one), like this:
subscribers = [{ "EMAIL" => { "email" => user.email},
:EMAIL_TYPE => 'html',
:merge_vars => { "NAME" => user.name
}
}]
Then, use batch_subscribe method, like this:
mailchimp = Mailchimp::API.new(MAILCHIMP_API_KEY)
mailchimp.lists.batch_subscribe(MAILCHIMP_LIST_ID, subscribers, false, false, false)
The three "falses" at the end refer to, in order: double_optin, update_existing, and replace_interests. You can set those to true or false, but double_optin needs to be "false" if you want to skip sending the confirmation email.
Here is the documentation for the batch_subscribe method.
After going through mailchimp-api gem I found this solution
#mc.list.subscribe('list_id', { email: params[:email] }, nil, double_optin = false)
The following code seems to work if there is one user, but truncate the email for multiple users:
users.each do |user|
mail(
:to => user.email,
:subject => 'Hi',
:template_name => 'notification'
).deliver
Is this the proper way to send a few emails?
Ruby on Rails 3.2.2
Heroku
SendGrid
I think this is what you're looking for:
def my_mailer_method
users = User.find({ ... })
headers['X-SMTPAPI'] = { :to => users.to_a }.to_json
mail(
:to => "this.will#be.ignored.com",
:subject => "Hi",
:template_name => "notification"
).deliver
end
This sends a message to any number of recipients use the SendGrid's SMTP API. You can find further information on the docs page.
You might also want to take a look at the sendgrid rails gem
To send email to multiple users: pass an array
Replace
:to => user.email
with
:to => users.map(&:email)
more > rails guide
If it is not important for you to hide email addresses from each other, you can specify recipients in a comma delimited string.
It seems that the problem is that each instance of the Mailer can only send one email. Perhaps the mail object is falling out of scope and getting cleaned up by the garbage collector...
The solution that worked was to iterate over the users outside of the Mailer, and call it once for each user. It may be slow but it should happen in the background anyway so it's fine.
I would like for a user within my ruby on rails app to be able to submit a ticket to my external ticket management system, squishlist.com. They have an api and instructions as follows. You need to authenticate and get a token and then submit the ticket with the token. From squishlist.
# get the token
https://api.squishlist.com/auth/?cfg=testcorp&user_key=privatekey&api_key=TEST-KEY-12345
=> {"token": "authtoken",
"expires": "2010-06-16 13:31:56"}
# and then the ticket with the token
https://api.squishlist.com/rest/?cfg=testcorp&token=authtoken&method=squish.issue.submit&prj=demo
POST data: {'issue_type': 1, 'subject': 'Hello, world.', 4: 'Open', 5: 10}
For testing purposes, I created a controller, route and view (page) for testing. On my controller I have the following
require 'httparty'
require 'json'
class SubmitticketController < ApplicationController
def submit_a_ticket
#cfg = 'xxxsupport'
#user_key = '4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b'
#api_key = 'MrUser411'
#project = 'excelm-manoke'
#url_new_string = 'https://api.squishlist.com/auth/?cfg='+#cfg+'&user_key='+#user_key+'&api_key='+#api_key
# https://api.squishlist.com/auth/?cfg=xxxsupport&user_key=4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b&api_key=MrUser411 - this is what is created by #url_new_string
response = HTTParty.get(#url_new_string.to_str) #submit the string to get the token
#parsed_and_a_hash = JSON.parse(response)
#token = #parsed_and_a_hash["token"]
#make a new string with the token
#urlstring_to_post = 'https://api.squishlist.com/rest/?cfg='+#cfg+'&token='+#token+'&method=squish.issue.submit&prj='+#project
#submit and get a result
#result = HTTParty.post(#urlstring_to_post.to_str, :body => {:subject => 'This is the screen name', :issue_type => 'Application Problem', :status => 'Open', :priority => 'Normal', :description => 'This is the description for the problem'})
end
end
And then I have a page that I go to to see the result of the controllers actions and it has the following code.
<p><%= #result %></p>
I know that it is working in general because of responses I have received along the way. My json is different from the example because of fields I have defined in squishlist. Can anyone help me out on this issue?
I guess the real problem is that I can't really see what the json looks like and if it is even close to match. I really don't know much about json. Should I be using something that might be easy. Should I be using ajax to submit this. Any help is greatly appreciated. I love the community here.
I solved this by adding .to_json and some heading information
#result = HTTParty.post(#urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}