in this article, we will explain to you how to send emails using in php. we are using sendgrid library in this article. so you can see below sendgrid php example.

Step 1: Install SendGrid library using Composer

In this step, we will download sendgrid library using composer. so you can follow below command and store this library into /sendgrid_lib/ directory.

composer require sendgrid/sendgrid

Step 2: Create Library file

in this step, we will create a MailSendLib.php library file into root directory and paste below code in this file

require_once "./sendgrid_lib/vendor/autoload.php';
class MailSendLib
{
    public function __construct()
    {
    }

    public function welcome_mail($data_arr)
    {
        $email = $data_arr["email"];
        $subject = $data_arr["subject"];
        $message = $data_arr["message"];

        $mail_data = [
            "to" => $email,
            "from" => "EMAIL_FROM",
            "subject" => $subject,
            "message" => $message_template
        ];
        return $this->mailsend($mail_data);
    }

    public function mailsend($data)
    {
        if (!empty($data["to"]) && !empty($data["from"]) &&  !empty($data["subject"]) &&  !empty($data["message"])) {
            $to = $data["to"];

            $from = $data["from"];
            $subject = $data["subject"];
            $message = $data["message"];
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= "From: " . $from . "\r\n";
            $headers .= "Reply-To: " . $from . "\r\n";

            $apikey = "SENDGRID_APIKEY";
            $replyTo = "";
            if ($replyTo == "") {
                $replyTo = $from;
            }
            $from_name = "EMAIL_FROM_NAME";
            $email = new \SendGrid\Mail\Mail();
            $email->setFrom($from, $from_name);
            $email->setSubject($subject);
            $email->addTo($to);
            if (isset($data["addCc"]) && $data["addCc"] != "") {
                $email->addCc($data["addCc"]);
            }
            $email->setReplyTo($replyTo);
            $email->addContent("text/plain", "subject");
            $email->addContent("text/html", $message);

            $sendgrid = new \SendGrid($apikey);
            try {
                $response = $sendgrid->send($email);
                return 1;
            } catch (Exception $e) {
                return 0;
            }
        } else {
            return 0;
        }
    }
}
?>

Step 3: Use the Library into file

<?php

require_once("./MailSendLib.php");

$mail_send = new MailSendLib();


$email = "to email";
$subject = "your subject";
$message = "

you message

"; $email_arr = array( "email"=>$email, "subject"=>$subject, "message"=>$message ); $data = $mail_send->welcome_mail($email_arr); if($data == 1){ echo "email send has been succssfully"; }else{ echo "mail send failed"; } ?>