Press "Enter" to skip to content

How to send Emails using Sendgrid in PHP?


In this tutorial, we are going to know how to send emails using Sendgrid in PHP. SendGrid is a customer communication platform marketing email. For PHP, SendGrid also provides its library that can be used for calling the SendGrid API.

Here is the Step you have to follow for API Setup on SendGrid:-

Before using its library, you have to create an account on SendGrid

Now, Create an API Key

Download the PHP library and put it in your Project Directory.

Include “sendgrid-php.php” file in your code, below is the code you can copy & paste it.

function send_grid_mail($mail){//$mail variable have array of data "to, sub, msg"
        require_once APPPATH."third_party/sendgrid/sendgrid-php.php";
        $email = new \SendGrid\Mail\Mail(); 
        $email->setFrom("[email protected]", "TechLifeDiary");
        // $email->addContent("text/plain", "and easy to do anywhere, even with PHP");
            "text/html", $mail['msg']
        $sendgrid = new \SendGrid('YOUR API KEY');
        try {
            $response = $sendgrid->send($email);
            // print $response->statusCode() . "\n";
            // print_r($response->headers());
            // print $response->body() . "\n";
            return true;
        } catch (Exception $e) {
            // echo 'Caught exception: '. $e->getMessage() ."\n";
            return false;

You can print the response by removing the comment code. Note that this above function is created for CodeIgniter, you can remove the line “APPPATH.third_party/” according to your directory.

Before start sending the email, you have to authenticate the sender email user by going in setting. Please ignore if you are using Gmail SMTP it popup msg for domain verification ignore it and just submit the form, you will receive a verification email just verify it.

Now, we are all set, call the function, and mail is triggered to the user.






What is explode and implode in PHP?
How to use JWT in CodeIgniter for creating API Authorization token