Sending One Time Password via SMS Using Rails3 and SMSAPI


Hi friends,

My need was send one time password via e-mail/sms ,who registered with their E-mail/mobile no.

Lets see “How to send SMS using Rails3 application and smsAPI”

At first we need a smsapi to send SMS via Rails3 application. There is a site, which provides FREE API to send SMS via programming. So, here we need to register with your Domain and mail-id. They also provide codes for various languages 🙂

EX code for RUBY:

require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('http://s1.freesmsapi.com/messages/send?skey=8c0185641435ac8a43cf10230a1417ac&message=YOUR_MESSAGE&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBER')

We just modify the code, what ever our application needs,

require 'net/http'
require 'uri'
pass = "Hi+This+is+ur+one+time+passwd:" + rand(999999).to_s
mobile = ARGV.shift
url = "http://s1.freesmsapi.com/messages/send?skey=9600152989freesmsaPI&message=#{pass}&senderid=slash&recipient=#{mobile}"
Net::HTTP.get_print URI.parse(url)
Then create a new rails project using,
  $ rails new sms
Go to project directory using,
  $ cd sms
Create scoffold using,
  $ rails generate scaffold name:string phone:string
Now, we have to edit the user controller
  $ gedit /app/controller/users_controller.rb
# POST /users
# POST /users.xml
def create
@user = User.new(params[:user])

smspasswd

respond_to do |format|
if @user.save
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml  { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end
Now, we have to write a small def function into that “usres_controller.rb” file
# POST /users
# POST /users.xml
def create
@user = User.new(params[:user])

smspasswd  #Note this Function

respond_to do |format|
if @user.save
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml  { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end

def smspasswd
name = @user.name
pass = "Hi+#{name},+This+is+ur+one+time+passwd:" + rand(999999).to_s
phone = @user.phone
url = "http://s1.freesmsapi.com/messages/send?skey=8c0185641435ac8a43cf10230a1417ac&message=#{pass}&senderid=slash&recipient=#{phone}"
Net::HTTP.get_print URI.parse(url)

end
That’s all
Sample Application: http://send-sms.heroku.com
Download from GitHub link: https://github.com/thasuresh/sms
Note:
      But, This “freesmsapi” does not work with the numbers who activated DND support. 😦

Power of PYTHON and RUBY languages


Hi friends,

Since last week i had worked with Send SMS via rails application. After long search, i found a site called “freesmsapi.com” which provides API and sends SMS. This site  is very much helpful in sending automated SMS.

They also provide  codes for different languages like “Python, Ruby, PHP, Perl, Java, C, C#, VB.NET”

When i compared the same code for different languages, I was surprised (shocked 😛 )to see that PYTHON and RUBY has the minimal and very efficient code. 🙂

RUBY:

require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('<a href="http://s1.freesmsapi.com/messages/send?skey=9600152989passwd&message=YOUR_MESSAGE&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBER">http://s1.freesmsapi.com/messages/send?skey=8c0185641435ac8a43cf10230a1417ac&message=YOUR_MESSAGE&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBER</a>')

PYTHON:

from urllib
import urlopen
print urlopen('http://s1.freesmsapi.com/messages/send?skey=9600152989passwd&message=YOUR_MESSAGE&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBER').read()

Here are the codes for other languages.

PHP:


echo file_get_contents("http://s1.freesmsapi.com/messages/send?skey=9600152989passwd&message=".urlencode('YOUR MESSAGE')."&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBERS");

PERL:

use strict;

use LWP::UserAgent;

my $ua = new LWP::UserAgent;
$ua->timeout(120);
my $url='http://s1.freesmsapi.com/messages/send?skey=89600152989passwd&message=YOUR_MESSAGE&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBER';
my $request = new HTTP::Request('GET', $url);
my $response = $ua->request($request);
my $content = $response->content();
print $content;

JAVA:

import java.net.*;
import java.io.*;

public class JavaGetUrl {
public static void main(String[] args) throws Exception {
URL myurl = new URL("http://s1.freesmsapi.com/messages/send?skey=89600152989passwd&message=YOUR_MESSAGE&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBER");
BufferedReader in = new BufferedReader(
new InputStreamReader(
myurl.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);

in.close();
}
}

C:

#include <curl/curl.h>

void main() {

long http_code = 0;
CURL *curl;
CURLcode res;

//Initializing the CURL module
curl = curl_easy_init();

if(curl) {

curl_easy_setopt(curl, CURLOPT_URL, "http://s1.freesmsapi.com/messages/send?skey=9600152989passwd&message=YOUR_MESSAGE&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBER");
res = curl_easy_perform(curl);

if(CURLE_OK == res) {
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);

if(http_code == 200) {
puts("Received 200 status code");
} else {
puts("Did not received 200 status code");
}
}
} else {
puts("Could not initialize curl");
}
}

C#:

using System.IO;
using System.Net;
string connectionString = "http://s1.freesmsapi.com/messages/send?skey=9600152989passwd&message=YOUR_MESSAGE&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBER";
try
{
System.IO.Stream SourceStream = null;
System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
myRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse webResponse = (HttpWebResponse)myRequest.GetResponse();
SourceStream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
string str = reader.ReadLine();
MessageBox.Show(str);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
VB.NET:
Imports System.IO
Imports System.Net
Dim connectionString As String = "http://s1.freesmsapi.com/messages/send?skey=9600152989passwd&message=YOUR_MESSAGE&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBER"
Try
Dim SourceStream As System.IO.Stream
Dim myRequest As System.Net.HttpWebRequest = WebRequest.Create(connectionString)
myRequest.Credentials = CredentialCache.DefaultCredentials
Dim webResponse As WebResponse = myRequest.GetResponse
SourceStream = webResponse.GetResponseStream()
Dim reader As StreamReader = New StreamReader(webResponse.GetResponseStream())
Dim str As String = reader.ReadLine()
MessageBox.Show(str)

Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

     

Sending SMS via “freesmsapi.com”


Hi friends,

I found a site which sends sms via website and programs. http://freesmsapi.com.

They provides their own API and programing codes in ruby,python.php.java,c,c#., etc.,

First we have to signup with our own domain and register with mail-id and phone number. that’s all. 🙂

Ex code in ruby:


require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('<a href="http://s1.freesmsapi.com/messages/send?skey=8c0185641435ac8a43cf10230a1417ac&message=Password:7876&senderid=fsmsapi&recipient=9943239066" target="_blank">http://s1.<wbr>freesmsapi.com/messages/send?<wbr>skey=<wbr>8c0185641435ac8a43cf10230a1417<wbr>ac&message=Password:7876&<wbr>senderid=fsmsapi&recipient=<wbr>9943239066</wbr></wbr></wbr></wbr></wbr></wbr></a>')

Now i’m trying to integrate this code into rails3 🙂

How to Send a mail using Gmail account with Rails3, ActionMailer and SMTP


Hi friends,

Action Mailer:

Action Mailer is a framework for building e-mail services. You can use Action Mailer to receive and process incoming email and send simple plain text or complex multipart emails based on flexible templates.

Lets see how to setup the actionmailer with Gmail SMTP.

First we have to create a rails application using

   $ rails new action_mailer

Next we’ll generate a scaffold for a User model with name and email attributes to act as a simple user-registration page.

$ rails genetate scaffold user name:string email:string

Now we have to migrate with DB.

$ rake db:migrate

The generated scaffolding code includes a page for creating users. We want to create a new user and then send them a confirmation email when the form on this page is submitted.

Now, just run the rails server command,

$ rails s

Then, open the “http://localhost:3000

Adding New User

The first thing we’ll do is create a new initializer file called setup_mail.rb and put some configuration options in it. ActionMailer will use sendmail if it’s set up on your machine but we can instead specify SMTP settings in the initializer.

  $ cd /config/initializers/

  $ gedit setup_mail.rb

ActionMailer::Base.smtp_settings = {  
      :address              => "smtp.gmail.com",  
      :port                 => 587,  
      :domain               => "gmail.com",  
     :user_name            => "thasuresh", #Your user name
      :password             => "actionmailer", # Your password
      :authentication       => "plain",  
      :enable_starttls_auto => true  
   }

You’ll probably want to use a different approach in a production application but this is a good enough approach while our application is in development. Obviously you’ll want to change the domain, user_name and password options to suit your own Gmail account.

Now that we’ve completed the configuration we can generate a new mailer with the following code:

  $ rails generate mailer user_mailer

$ cd /app/mailer

  $ gedit user_mailer.rb


class UserMailer < ActionMailer::Base
default :from => "thasuresh@gmail.com"

def registration_confirmation(user)
mail(:to => user.email, :subject => "Registered")
end
end

Now we have to create a file called registration_confirmation.text.erb under app/views/user_mailer.

  $ gedit app/views/user_mailer/registration_confirmation.text.erb

Thank you for registering!

/app/controllers/users_controller.rb  (Note the 6th line)


def create
@user = User.new(params[:user])

respond_to do |format|
if @user.save
UserMailer.registration_confirmation(@user).deliver  #include this line in your users_controller.rb file
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml  { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end

mail sent by "ActionMailer"

If you want add user name at the mail, add the following line into registration_confirmation.text.erb

/app/views/user_mailer/registration_confirmation.text.erb.

<%= @user.name %>,

Thank you for registering!

Added User name

Now if you want add any attachments in the mail add this line into /app/mailer/user_mailer.rb


def registration_confirmation(user)
@user = user
attachments["rails.png"] = File.read("#{Rails.root}/public/images/rails.png")
mail(:to => "#{user.name} <#{user.email}>", :subject => "Registered")
end

Here my need is send a numeric password, when a user subscribe with his mail id. The password will send by actionmailer. So i added the a single ruby command into


Hi <%= @user.name %>,

This is the one time password, You can login into our site using the password given below

Password: <%=rand(999999)%>

Thank You For Registering!

Final output 🙂

That’s all !!!

Here sample “actionmailer” application and which deployed in heroku http://actionmailer.heroku.com

GitHub Account link: https://github.com/thasuresh/action_mailer

Actionmailer


Hi frinds,

I created a module for random password generation using “Actionmailer” in rails 3  🙂

And also I’m trying to find a solution for sending password to mobile via sms.

but i didn’t succeed so for. 😦

I think their is no sms provider in india. If anyone know, pls let me know  !

check this link http://actionmailer.heroku.com/

I’ll tell the simple procedure to play wit actionmailer on my next post 🙂