How to send Emails using Sendgrid in PHP
Today, We explain to you and how to send Emails using Sendgrid in PHP. so We give you a simple example of send mail using sendgrid in php.
First, we should have Sendgrid account. if you have not then you can create a new Sendgrid account. we need sendgrid_API_key so we need to sendgrid account.
we need to also Sendgrid PHP libraries. so you can below command to download the Sendgrid PHP library. or you can directly download sendgrid library on the official github.
1 | composer require sendgrid/sendgrid |
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php require_once("./MailSendLib.php"); $mail_send = new MailSendLib(); $email = "to email"; $subject = "your subject"; $message = "<h1>you message</h1>"; $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"; } ?> |
MailSendLib.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | <?php require_once "./sendgrid_lib/sendgrid-php.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; } } } ?> |
Please follow and like us: