Sending sms from twilio in rails - ruby-on-rails

new to ruby/rails here so please forgive my ignorance. Working on adding SMS capabilities to an existing app and I’ve been successful while just setting up a ruby document and sending a sms message but when I go to incorporate it in my rails app, I’m getting a little lost.
I’ve followed this document (https://www.twilio.com/blog/2012/02/adding-twilio-sms-messaging-to-your-rails-app.html) and created a SendTextController with the following code but included the account_sid and account_token in my application.yml file using ENV and figaro. In my actual file, I have my twilio phone number and the number I'd like to send it to (just blocked it out here).
Once I set this up, I’m lost at how to call this method from a view in my app?
class TwilioController < ApplicationController
def index
end
def send_text_message
number_to_send_to = "+1XXXXXXXXXX"
twilio_sid = ENV["TWILIO_SID"]
twilio_token = ENV["TWILIO_TOKEN"]
twilio_phone_number = "+1XXXXXXXXXX"
#twilio_client = Twilio::REST::Client.new twilio_sid, twilio_token
#twilio_client.account.sms.messages.create(
:from => "+1#{twilio_phone_number}",
:to => number_to_send_to,
:body => "Test Message from testing"
)
end
end

Your code to send the text message looks pretty much solid - if you have that code defined in your controller, and you'd like to call it when rendering, say, the index view of your TwilioController, you should be able to call self.send_text_message().
But if you're just getting started (and presumably using Rails 4?) there's a more up-to-date tutorial that can take you through the entire integration process.

Related

Why won't my Twilio SMS send in Sidekiq background worker?

I am having issues sending a text with Twilio through my SideKiq background worker. The worker is supposed to send a text and then send an email (with Mandrill).
The email works fine.
The text never happens.
I haven't had issues with other jobs (including ones that also involve use
of environment variables).
I haven't had issues sending Twilio texts outside of a background worker.
I'm using Foreman to start my application.
In console, running UserNotifier.new.perform(1) works fine - both the email and the text are sent.
Here is some of the code in question:
This is the class that I'm using to send my SMS:
(My Gemfile includes the twilio-ruby gem)
class SendSMS
def initialize
#twilio_client = Twilio::REST::Client.new "#{ENV['TWILIO_SID']}", "#{ENV['TWILIO_TOKEN']}"
end
def send(message, user)
#twilio_client.account.sms.messages.create(
:from => "+1#{ENV['TWILIO_PHONE_NUMBER']}",
:to => user.phone_number,
:body => message
)
end
end
My worker looks like this:
class UserNotifier
include Sidekiq::Worker
sidekiq_options queue: :immediate
def perform(user_id)
user = User.find(user_id)
message = "Hi #{user.name}!"
SendSMS.new.send(message, user)
UserMailer.send(message, user).deliver
end
end
Can anyone see an issue with my code? Please let me know if there is anything else I should post or if there is any clarification that I could make.
My server was displaying the worker logs and it didn't seem to be running into an error.
Any suggestions on how to debug background workers would be appreciated as well.
Try catching REST errors from Twilio and logging some debug info. You can discover errors that might prevent messages from sending, or investigate sent messages in your Twilio account logs via their sid (Twilio's internal id). Also updated your create call to use the messages resource instead of deprecated sms/messages.
begin
message = #twilio_client.account.messages.create(
:from => "+1#{ENV['TWILIO_PHONE_NUMBER']}",
:to => user.phone_number,
:body => message
)
logger.debug "sent #{message.sid}"
rescue Twilio::REST::RequestError => e
logger.debug "error: #{e.message}"
end

RubyOnbRails - Render mail to string

I have a RubyOnRails 3.2.x application that sends out mails using Actionmailer.
The code goes something like this:
class Mymailer < ActionMailer::Base
def sendout
mail(:to->"someone#somewhere.com", :from ...........
end
end
Instead of sending out that email, I want it to be rendered to a string which I then plan to process differently
PS: In my specific case I want to pass that string to a Node.JS server who will do the actual sending of the mail, I am using RubyOnRails to handle the multi language support and number formatting (yes I have multiple templates for the different languages that I support).
Since Ruby won't be doing the email sending, there's no need to use the Mailer.
Ideally you could generate a JSON string representation of the email like:
# at the top of the file
require 'json'
# then in your method
json_string = {
:to => "email#example.com",
:from =>"sender#example.com",
:body => "this is the body"
}.to_json
Then post this string to your node.js server from (for example) your controller or whatever is currently calling your mailer.
However, since you want to render the email using templates which pull in DB fields and use the i18n functionality of Rails, you could use the Mailer but render the result to a string like follows:
mail(to: "mail#example.com") do |format|
format.html do
string = render_to_string("your_template")
call_node_js(string)
end
end
If what you want is getting the whole mail representation, including headers, then you might want to browse the source code to see what happens behind the curtain.
A good starting point is the ActionMailer::Base method #mail (Rails 4):
http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail
Anyway, if the sending is handled by Node.js, you don't need to do it. Just build a JSON object like Olly suggested and pass it through.

Rails 3: Contact form to send messages from User Profiles

I worked through some basic tutorials on Rails 3. The goal is a community-website on abilities and activities. I am using Devise for authentication. The creation of user profiles with avatars worked well (thanks to paperclip).
As a next step, I want to enable registered users to send an e-mail to a user from his (or her) profile page. I found a great tutorial on creating a contact form using Google Apps:
http://matharvard.ca/posts/2011/aug/22/contact-form-in-rails-3/
The mailer class in this tutorial looks like:
class NotificationsMailer < ActionMailer::Base
default :from => "noreply#youdomain.dev"
default :to => "you#youremail.dev"
def new_message(message)
#message = message
mail(:subject => "[YourWebsite.tld] #{message.subject}")
end
end
My question: What is the best way to replace you#youremail.dev with the receivers E-Mail-Address? (from the User-Model)
Thanks in advance!
You can modify the new_message to accept the user (or list of users) to whom you want to send the email. Or an array of email addresses if you want to. Then pass the receiver's email address to the mail method as the :to option.
def new_message(receiver, message)
#message = message
mail(:subject => "[YourWebsite.tld] #{message.subject}",
:to => receiver.email_address) # or something similar
end
Then you can invoke your mailer like this
NotificationEmail.new_message(a_user, a_message).deliver
To read the API see here or here (I prefer APIdock).
Also a more comprehensive guide on ActionMailer is available here. If you are new to Rails, you can find more guides here.

How does one use delayed_job to make an Rails 3.0 ActionMailer run asynchronously? Encountering ArgumentErrors

I'm trying to delay a notification email to be sent to users upon signing up to my app. The emails are sent using an ActionMailer which I call InitMailer. The way I am trying to delay the jobs is using collectiveidea's delayed_job https://github.com/collectiveidea/delayed_job. To do this you can see that i specify handle_asynchronously after defining the method initial_email:
class InitMailer < ActionMailer::Base
default :from => "info#blahblahblah.com"
def initial_email(user)
#user = user
#url = "http://www.blahblahblah.com"
mail(:to => user.email,
:subject => "Welcome to my website!"
)
end
handle_asynchronously :initial_email
end
However, I encounter an argument error in my log file "delayed_job.log":
Class#initial_email failed with ArgumentError: wrong number of arguments (1 for 0) - 5
failed attempts
For your information, the email is sent in a controller using the line:
#user = InitUser.new(params[:init_user])
InitMailer.delay.initial_email(#user)
Additionally, when I set up my code without the delay, the emails were sent out without problem (except for the fact that it slowed down my app waiting for gmail servers)
Where is causing the errors here? How can I get the delayed mail to send properly?
Due to the way that Rails3 implements mailers, there are some unusual workarounds for delayed_jobs. For instance, you have seen that to delay the mailing, you write
ExampleMailer.delay.example(user)
While typically you would have to write handle_asynchronously after the method definition, in the case of mailers this declaration (for some reason) prevents that delayed job from working.
So in this code, drop the declaration entirely:
class InitMailer < ActionMailer::Base
default :from => "info#blahblahblah.com"
def initial_email(user)
#user = user
#url = "http://www.blahblahblah.com"
mail(:to => user.email,
:subject => "Welcome to my website!"
)
end
#No handle_asynchronously needed here
end

what is the best way to make a newsletter in rails3

Is there a gem to do this, and if not, what is the best approach. I'm assuming i'd store the emails in a newsletter database, and would want a form that emails everyone at once. thanks!
No gem for this that I know of.
Actually, due to processing issues, the best way would be to use external bulk email service provider via provider's API.
However, building your own newsletter system is no different from building your regular MVC. Only addition are mailers and mailer views.
(1) So you create model that deals with registration data (:name, :email, :etc...) and model that deals with newsletter itself.
(2) Controller that deals with it (CRUD) + (:send). Send takes each recipient, sends data to mailer which creates email and then sends it.
def send
#newsletter = Newsletter.find(:params['id'])
#recipients = Recipient.all
#recipients.each do |recipient|
Newsletter.newsletter_email(recipient, #newsletter).deliver
end
end
(3) Mailer builds an email, makes some changes in each email if you want to do something like that and returns it to controller action send for delivery.
class Newsletter < ActionMailer::Base
default :from => "my_email#example.com", :content_type => "multipart/mixed"
def newsletter_email(recipient, newsletter)
# these are instance variables for newsletter view
#newsletter = newsletter
#recipient = recipient
mail(:to => recipient.email, :subject => newsletter.subject)
end
end
(4) Ofc, you need mailer views which are just like regular views. Well in multipart there is:
newsletter_email.html.erb (or haml)
newsletter_email.txt.erb
When you want to send both html and text only emails. Instance variables are defined in mailer ofc.
And... that is it. Well you could use delayed job to send them since sending more than several hundred emails can take a while. Several ms times n can be a lot of time.
Have fun.
Please check the maktoub gem there is a blog post over it.
No gem that I know of too and building on #Krule's answer, here's a screencast of setting up mailers in Rails.
How to create, preview and send email from your rails app
I was looking for something similar when I found this. I think with a bit of customization, it can easily be used to create newsletter emails too.
Save money! Spend somewhere else.

Resources