Wednesday, August 12, 2015

How to send email using Node.js?

 Send email using Node.js:

In this blog i am going to discuss about sending e-mail with Node.js, Express.js and NodeMailer package. In many forums and blogs people used to ask about sending e-mail’s using Node.js for account verification, password recovery and promotion. So let’s begin with tutorial and at the end you will have Node application which is able to send e-mail’s to any one’s account.



Create package.json file and keep it in any folder. Put the below code in it.

package.json

{
"name": "email-node",
"version": "1.0.0",
"dependencies": {
"nodemailer": "~0.7.1",
"express": "~4.5.1"
}
}




Once done. Switch to that folder using Command prompt or Terminal and type npm install. It will download and install the dependencies our project need.

npm install

After completion you will able to see node_modules folder in your project directory.

Implementing Server.js:



Let’s begin with creation of our Server file. Paste code shown below in file named as “Server.js”.

Server.js

var express=require('express');
var nodemailer = require("nodemailer");
var app=express();
app.listen(3000,function(){
console.log("Express Started on Port 3000");
});




This is basic block of our app. If you run it in Terminal you will see console message. Now let’s add some routing logic to tell our app what is supposed to do when Request comes from browser. Add these code just above the app.listen line.

app.get('/',function(req,res){
res.sendFile('index.html');
});


Now when you try to open your app from browser, it will return the index.html as response. Let me show you basic snippet of HTML code.

index.html

<div id="container">
<div></div>
Node.JS Email application
<div>
<h1>Mailer In Node.JS</h1>
<input id="to" type="text" placeholder="Enter E-mail ID where you want to send" />
<input id="subject" type="text" placeholder="Write Subject" />
<textarea id="content" cols="40" rows="5" placeholder="Write what you want to send"></textarea>
<button id="send_email">Send Email</button>
<span id="message"></span>
</div>


Now next thing to do is to call our Server from HTML page when user hit on ‘Send Email’ Button. To do so at client end i am using jQuery. Here is code snippet of jQuery inside HTML page only.

index.html

<script>
$(document).ready(function(){
    var from,to,subject,text;
    $("#send_email").click(function(){    
        to=$("#to").val();
        subject=$("#subject").val();
        text=$("#content").val();
        $("#message").text("Sending E-mail...Please wait");
        $.get("http://localhost:3000/send",{to:to,subject:subject,text:text},function(data){
        if(data=="sent")
        {
            $("#message").empty().html("Email is been sent at "+to+" . Please check inbox !");
        }

});
    });
});
</script>



Notice : At $.get we are calling our app with ‘/send’ as handler so now we have to add router in our Server.js file in order to deal with this request. So let’s add some code to handle this route request. Add these code just below of app.get(‘/’) line. File name : Server.js

Server.js

app.get('/send',function(req,res){
//code to send e-mail.
//Will be shown soon.
});


Adding NodeMailer code:

Okay we are almost there, now we have to handle the Mail system. First of all we have to Define Mail transport System (SMTP) so that from that E-mail box our e-mail will be sent. For ease, you can add your Gmail account and password. Add this code just in Server.js just below the ‘var app=express()’ line.

var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "yourID@gmail.com",
pass: "Your Gmail Password"
}
});


We will use this Object to send e-mail. Our app design is when user click on ‘Send email’ Button then only e-mail should be sent, and we have did that part in “app.get(‘/send’)” router. So in that block only paste the code shown below.

var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});




In above code we have read GET variables send from HTML page and we have call “sendMail()” function using Transport object we have created above. In case there is any confusion here is a complete Server.js file.

Server.js

var express=require('express');
var nodemailer = require("nodemailer");
var app=express();
/*
Here we are configuring our SMTP Server details.
STMP is mail server which is responsible for sending and recieving email.
*/
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "yourID@gmail.com",
pass: "Your G-mail password"
}
});

/*------------------SMTP Over-----------------------------*/

/*------------------Routing Started ------------------------*/

app.get('/',function(req,res){
res.sendFile('index.html');
});
app.get('/send',function(req,res){
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});



/*--------------------Routing Over----------------------------*/

app.listen(3000,function(){
console.log("Express Started on Port 3000");
});


And this is how HTML page looks like with all styles and JS.

index.html

<html>
<head>
<title>Node.JS Email application</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script>// <![CDATA[
$(document).ready(function(){
    var from,to,subject,text;
    $("#send_email").click(function(){    
        to=$("#to").val();
        subject=$("#subject").val();
        text=$("#content").val();
        $("#message").text("Sending E-mail...Please wait");
        $.get("http://localhost:3000/send",{to:to,subject:subject,text:text},function(data){
        if(data=="sent")
        {
            $("#message").empty().html("

Email is been sent at "+to+" . Please check inbox !

");
        }

});
    });
});
</script>
</head>
<body>
<div id="container">
<h1>Mailer In Node.JS</h1>
<input id="to" type="text" placeholder="Enter E-mail ID where you want to send" />
<input id="subject" type="text" placeholder="Write Subject" />
<textarea id="content" cols="40" rows="5" placeholder="Write what you want to send"></textarea>
<button id="send_email">Send Email</button>
<span id="message"></span>
</div>
</div>
</body>
</html>

Secure site with Password Protection

Secure Site using password:

Step1:- At first open your apache configuration file and add the line AllowOverride All to it.



<Directory /home/abhimanyu/workspace/test/>

    AllowOverride All

Step2:- Now open your .htaccess file and add the following line of code to it



AuthType Basic
AuthName "Restricted Files"
AuthUserFile /etc/apache2/securepass/.htpasswd
Require valid-user

For details of these lines go here.




Step3:- We need a package of apache as utils to get password utility
and can get it by the following command

sudo apt-get install apache2-utils



Step 4:-Now create securepass dir by running



sudo mkdir /etc/apache2/securepass/
                                              then
sudo htpasswd -c /etc/apache2/securepass/.htpasswd username
and add your password



Step 5:--Now restart your apache server by following command
  sudo service apache2 restart
and check at for your site(domain)  and its got password protected.

Tuesday, August 11, 2015

How to solve [ReflectionException] error in Laravel 5.1 seeding

Resolve [ReflectionException] error in seeding:

Sometimes its make a problem which we are getting in Laravel 5.1 and this is [ReflectionException]

I just got this error when i was running this command for seeding

php artisan db:seed --class=ZoneTableSeeder

and it was showing this error:

  [ReflectionException]                
  Class ZoneTableSeeder does not exist 


For solved out, I just found a solution and its working in my case.

composer dump-autoload

After that run again this command and it will work

php artisan db:seed --class=ZoneTableSeeder

 Thanks

Sunday, August 9, 2015

Easy way to set multiple seeders in Laravel 5.1

Multiple seeders in a table:

For entry multiple data in table it is a easy way to create a seeder.

For creating a seeder run the following command:

php artisan makd:seeder ClassNameSeeder

After this , in its run() function, write it

        $zones = [
            ['zone_id' => 1, 'zip' => '94133', 'rate' => '1.00'],
            ['zone_id' => 1, 'zip' => '94111', 'rate' => '2.00'],
            ['zone_id' => 1, 'zip' => '94104', 'rate' => '3.00'],
            ['zone_id' => 2, 'zip' => '94109', 'rate' => '4.00']

        ];

            \App\Zone::insert($zones);


Here the upper array is the multiple value , which you wana enter in your table.

After that run this command.

php artisan db:seed --class=ClassNameSeeder
Thanks

Friday, August 7, 2015

How and why to use Middleware in Laravel 5.1

Middleware in Laravel 5.1:

Middleware is used for check the request and then process it for particular url.

e.g. There are two types of users. One is Vendor and another is Users. Then for both kind of users will get different authorization.

For this:

Create a Middleware File

php artisan make:middleware VendorMiddleware

Now in routes.php we will set its url

route code
Route::group(['middleware' => 'auth'], function () {
    Route::get('/', ['middleware' => 'vendor', function () {
        return view('welcome');
    }]);


In VendorMiddleware:
<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class VendorMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user= Auth::user();
        if($user->user_type=='vendor'){
            echo "vendor login";
        }else{
            echo "you are unauthorized person";
        }
        //return $next($request);
    }
}


Write in app/Http/Kernel.php

 'vendor' => \App\Http\Middleware\VendorMiddleware::class,

Thanks

Friday, July 31, 2015

How to run Wordpress in a directory & its sub-directory?

Run Wordpress in Directory & Sub-Directory:

We have a wordpress site which is runnung in root directory. Now we want to install same site with different database name in subdirectory for testing purpose.

STARTING POINT:
http://www.mywordpress.com   /var/www/
http://www.mywordpress.com/foldername   /var/www/foldername

Step 1:

Put same code in /var/www/foldername as in /var/www/ . Connect it with new database.

Step 2:

Change .htaccess file in /var/www/foldername as given below

# BEGIN WordPress

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /foldername/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /foldername/index.php [L]
</IfModule>

# END WordPress

At this point the configuration will not be working because the .htaccess directives at /var/www/.htaccess with be controlling all aspects of the URL so the directives at /var/www/foldername/.htaccess will have no bearing.

Step 3 :

The final step is to modify the default WordPress htaccess directives so that they will have control in for all variations of the URL.
Now change .htaccess file in /var/www as given below

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
Options +FollowSymLinks
RewriteRule ^/?foldername/$ /var/www/foldername/index.php [L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Step 4:

Now login to your http://www.mywordpress.com/foldername/wp-admin/ section. Go to Setting->Permalinks.

Choose Post name in common setting.
Thanks

Friday, July 24, 2015

Join Query for multiple condition in Laravel 5.1

Join Query for Multiple Condition:

For join query in multiple condition we will use it by the following way:

DB::table('users')
        ->join('contacts', function($join) use($userId)
        {
            $join->on('users.id', '=', 'contacts.user_id')
            ->where('contacts.user_id','=',$userId);
        })
        ->get();


Also sometime we need to use condition that field is null or field is not null in where condition so we can do the following

$users = DB::table('users')
                    ->whereNull('updated_at')
                    ->get();


Thanks.