Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • How to send emails in sendgrid in php.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 654
    Comment on it

    Hello Readers ,

    For sending emails in sendgrid initially we need two things.

    1. Sendgrid API key : To configure API keys, visit or you may create sendgrid account to have the API keys.
    2. Sendgrid Library :  Sendgrid Library :  You may have the full sendgrid Library in github

    We can send send emails by various methods as follows:

    Using SendGrid’s PHP Library

    After installing sendgrid library into the project folder.

    require 'vendor/autoload.php';
    $sendgrid = new SendGrid("SENDGRID_APIKEY");
    $email    = new SendGrid\Email();
          ->setSubject("Sending with SendGrid is Fun")
          ->setHtml("and easy to do anywhere, even with PHP");

    Using PHP with cURL

    require 'vendor/autoload.php';
    $sendgrid_apikey = getenv('YOUR_SENDGRID_APIKEY');
    $sendgrid = new SendGrid($sendgrid_apikey);
    $url = '';
    $pass = $sendgrid_apikey;
    $template_id = '<your_template_id>';
    $js = array(
      'sub' => array(':name' => array('Elmer')),
      'filters' => array('templates' => array('settings' => array('enable' => 1, 'template_id' => $template_id)))
    $params = array(
        'to'        => "",
        'toname'    => "Example User",
        'from'      => "",
        'fromname'  => "Your Name",
        'subject'   => "PHP Test",
        'text'      => "I'm text!",
        'html'      => "<strong>I'm HTML!</strong>",
        'x-smtpapi' => json_encode($js),
    $request =  $url.'api/mail.send.json';
    // Generate curl request
    $session = curl_init($request);
    // Tell PHP not to use SSLv3 (instead opting for TLS)
    curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
    curl_setopt($session, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $sendgrid_apikey));
    // Tell curl to use HTTP POST
    curl_setopt ($session, CURLOPT_POST, true);
    // Tell curl that this is the body of the POST
    curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
    // Tell curl not to return headers, but do return the response
    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    // obtain response
    $response = curl_exec($session);
    // print everything out

    And that’s all there is to it.

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: