### Install Twilio SDK for PHP Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md Installs the Twilio SDK for PHP using Composer, a dependency manager for PHP. ```bash composer require twilio/sdk ``` -------------------------------- ### Execute Example Script Source: https://github.com/sendgrid/sendgrid-php/blob/main/CONTRIBUTING.md Command to run an example PHP script from the examples directory to demonstrate the library's usage. ```Bash php examples/example.php ``` -------------------------------- ### Install and Run SendGrid PHP Locally Source: https://github.com/sendgrid/sendgrid-php/blob/main/CONTRIBUTING.md Steps to clone the SendGrid PHP repository, navigate into the directory, and install dependencies using Composer. ```Bash git clone https://github.com/sendgrid/sendgrid-php.git cd sendgrid-php composer install ``` -------------------------------- ### Run Recipients Example (Bash) Source: https://github.com/sendgrid/sendgrid-php/blob/main/lib/contacts/README.md This snippet shows how to execute the SendGrid PHP Recipients helper example using a bash command. Ensure your SENDGRID_API_KEY environment variable is set. ```bash php examples/helpers/contacts/recipients.php ``` -------------------------------- ### Install SendGrid PHP Library with Composer (v4.0.4) Source: https://github.com/sendgrid/sendgrid-php/blob/main/TROUBLESHOOTING.md This JSON snippet shows how to specify the sendgrid/sendgrid package with version 4.0.4 in your composer.json file for installation. ```json { "require": { "sendgrid/sendgrid": "~4.0.4" } } ``` -------------------------------- ### PHP SendGrid Attach File Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This example demonstrates how to attach a text file to an email using the SendGrid PHP library. It shows how to encode the file content and use the `addAttachment` method. ```php /sendgrid-php.php'; use SendGrid\Mail\Mail; $email = new Mail(); $email->setFrom("test@example.com", "Example User"); $email->setSubject("Sending with Twilio SendGrid is Fun"); $email->addTo("test@example.com", "Example User"); $email->addContent("text/plain", "and easy to do anywhere, even with PHP"); $email->addContent( "text/html", "and easy to do anywhere, even with PHP" ); $file_encoded = base64_encode(file_get_contents('my_file.txt')); $email->addAttachment( $file_encoded, "application/text", "my_file.txt", "attachment" ); $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { $response = $sendgrid->send($email); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; } ``` -------------------------------- ### Clone and Setup SendGrid PHP Repository Source: https://github.com/sendgrid/sendgrid-php/blob/main/CONTRIBUTING.md This snippet demonstrates how to clone the sendgrid-php repository, navigate into the directory, and set up the upstream remote for tracking changes from the original project. ```bash git clone https://github.com/sendgrid/sendgrid-php cd sendgrid-php git remote add upstream https://github.com/sendgrid/sendgrid-php ``` -------------------------------- ### Attach Local File with SendGrid PHP Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This snippet demonstrates how to attach a local file to an email using the SendGrid PHP library. It includes setting the file content, type, filename, and disposition. The example also shows how to send the email and handle the response or exceptions. ```php $email->addTo("test@example.com", "Example User"); $email->addContent("text/plain", "See attached file from Box."); $email->addContent( "text/html", "See attached file from Box." ); $attachment = new \SendGrid\Mail\Attachment(); $attachment->setContent($attachmentContent); $attachment->setType($attachmentContentType); $attachment->setFilename($attachmentFilename); $attachment->setDisposition("attachment"); $attachment->setContentId($attachmentFilename); // Only used if disposition is set to inline $email->addAttachment($attachment); $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { $response = $sendgrid->send($email); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage() ."\n"; } } ``` -------------------------------- ### Install Specific SendGrid PHP Library Version with Composer Source: https://github.com/sendgrid/sendgrid-php/blob/main/TROUBLESHOOTING.md This JSON snippet shows the general format for specifying a version constraint for the sendgrid/sendgrid package in your composer.json file, allowing you to install a particular version (e.g., '~X.X.X'). ```json { "require": { "sendgrid/sendgrid": "~X.X.X" } } ``` -------------------------------- ### Execute SendGrid Mail Helper Example (Bash) Source: https://github.com/sendgrid/sendgrid-php/blob/main/lib/mail/README.md This command executes a PHP script that demonstrates the usage of the SendGrid Mail Helper. Ensure your SENDGRID_API_KEY environment variable is set before running. ```bash php examples/helpers/mail/example.php ``` -------------------------------- ### Set Windows Environment Variables for Twilio API Keys Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md Demonstrates how to temporarily and permanently set environment variables on Windows for Twilio API keys and secrets, or account SID and auth token. ```bash set TWILIO_API_KEY=YOUR_TWILIO_API_KEY set TWILIO_API_SECRET=YOUR_TWILIO_API_SECRET : or set TWILIO_ACCOUNT_SID=YOUR_TWILIO_ACCOUNT_SID set TWILIO_AUTH_TOKEN=YOUR_TWILIO_AUTH_TOKEN ``` ```bash setx TWILIO_API_KEY "YOUR_TWILIO_API_KEY" setx TWILIO_API_SECRET "YOUR_TWILIO_API_SECRET" : or setx TWILIO_ACCOUNT_SID "YOUR_TWILIO_ACCOUNT_SID" setx TWILIO_AUTH_TOKEN "YOUR_TWILIO_AUTH_TOKEN" ``` -------------------------------- ### Initialize Twilio Email Client in PHP Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md Shows how to initialize the Twilio Email client in PHP using either API keys or account SID and auth token retrieved from environment variables. ```php $twilioEmail = new \TwilioEmail(\getenv('TWILIO_API_KEY'), \getenv('TWILIO_API_SECRET')); // or $twilioEmail = new \TwilioEmail(\getenv('TWILIO_ACCOUNT_SID'), \getenv('TWILIO_AUTH_TOKEN')); ``` -------------------------------- ### Configure Google App Engine for Curl Lite Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md Configures Google App Engine to enable curl_lite for PHP applications by adding a php.ini file with the specified setting. ```ini google_app_engine.enable_curl_lite = 1 ``` -------------------------------- ### Validate Domain Authentication Source: https://github.com/sendgrid/sendgrid-php/blob/main/USAGE.md This code example demonstrates how to validate a domain's authentication setup using the SendGrid PHP client. It requires the domain ID and returns an error message if validation fails. ```php $id = "test_url_param"; $response = $sg->client->whitelabel()->domains()->_($id)->validate()->post(); print $response->statusCode() . "\n"; print $response->body() . "\n"; print_r($response->headers()); ``` -------------------------------- ### Send Multiple Emails with Personalizations using SendGrid PHP Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This code snippet demonstrates how to send multiple emails with unique personalizations using the SendGrid PHP library. It includes setting up sender and recipient details, adding multiple recipients to a personalization object, and setting individual subjects for each personalization. The example also shows how to send the email and handle potential exceptions. ```php /sendgrid-php.php'; use SendGrid\Mail\From; use SendGrid\Mail\Mail; use SendGrid\Mail\Personalization; use SendGrid\Mail\Subject; use SendGrid\Mail\To; $from = new From("test@example.com", "Twilio Sendgrid"); $to = new To( "test+test1@example.com", "Example User1", [ '-name-' => 'Example User 1' ], "Example User1 -name-" ); $subject = new Subject("Hello from Twilio Sendgrid!"); $plainTextContent = new PlainTextContent( "How's it going -name-?" ); $htmlContent = new HtmlContent( "How's it going -name-?" ); $email = new Mail($from, $to, $subject, $plainTextContent, $htmlContent); $personalization0 = new Personalization(); $personalization0->addTo(new To( "test+test2@example.com", "Example User2", [ '-name-' => 'Example User 2' ], "Example User2 -name-" )); $personalization0->addTo(new To( "test+test3@example.com", "Example User3", [ '-name-' => 'Example User 3' ], "Example User3 -name-" )); $personalization0->setSubject(new Subject("Hello from Twilio Sendgrid!")); $email->addPersonalization($personalization0); $personalization1 = new Personalization(); $personalization1->addTo(new To( "test+test3@example.com", "Example User4", [ '-name-' => 'Example User 4' ], "Example User4 -name-" )); $personalization1->addTo(new To( "test+test4@example.com", "Example User5", [ '-name-' => 'Example User 5' ], "Example User5 -name-" )); $personalization1->addFrom(new From( "test5@example.com" => "Twilio" )) $personalization1->setSubject(new Subject("Hello from Twilio!")); $mail->addPersonalization($personalization1); $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { $response = $sendgrid->send($email); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; } ``` -------------------------------- ### Send Email to Single Recipient (Method 1) Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This example shows how to send an email to a single recipient using the SendGrid PHP library. It sets the sender, subject, recipient, and content in both plain text and HTML formats. ```php /sendgrid-php.php'; use SendGrid\Mail\Mail; $email = new Mail(); $email->setFrom("test@example.com", "Example User"); $email->setSubject("Sending with Twilio SendGrid is Fun"); $email->addTo("test@example.com", "Example User"); $email->addContent("text/plain", "and easy to do anywhere, even with PHP"); $email->addContent( "text/html", "and easy to do anywhere, even with PHP" ); $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { $response = $sendgrid->send($email); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; } ``` -------------------------------- ### Install SendGrid PHP Package with Composer Source: https://github.com/sendgrid/sendgrid-php/blob/main/README.md This snippet shows how to add the SendGrid PHP library as a dependency to your project using Composer. It specifies the required package and version. ```json { "require": { "sendgrid/sendgrid": "~7" } } ``` -------------------------------- ### Set Up Twilio Environment Variables (Bash) Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This bash snippet demonstrates how to set up environment variables for Twilio API authentication using either an API key/secret or Account SID/Auth Token. It shows exporting variables to a `twilio.env` file and adding it to `.gitignore` for security. ```bash echo "export TWILIO_API_KEY='YOUR_TWILIO_API_KEY'" > twilio.env echo "export TWILIO_API_SECRET='YOUR_TWILIO_API_SECRET'" >> twilio.env # or echo "export TWILIO_ACCOUNT_SID='YOUR_TWILIO_ACCOUNT_SID'" > twilio.env echo "export TWILIO_AUTH_TOKEN='YOUR_TWILIO_AUTH_TOKEN'" >> twilio.env ``` ```bash echo "twilio.env" >> .gitignore source ./twilio.env ``` -------------------------------- ### Create a Campaign Source: https://github.com/sendgrid/sendgrid-php/blob/main/USAGE.md Creates a marketing campaign. Requires parameters like subject, sender ID, content, and list/segment IDs to be sent or scheduled. This endpoint allows for initial campaign setup. ```php $request_body = json_decode('{ "categories": [ "spring line" ], "custom_unsubscribe_url": "", "html_content": "

Check out our spring line!

", "ip_pool": "marketing", "list_ids": [ 110, 124 ], "plain_content": "Check out our spring line!", "segment_ids": [ 110 ], "sender_id": 124451, "subject": "New Products for Spring!", "suppression_group_id": 42, "title": "March Newsletter" }'); $response = $sg->client->campaigns()->post($request_body); print $response->statusCode() . "\n"; print $response->body() . "\n"; print_r($response->headers()); ``` -------------------------------- ### Get User Account Information - PHP Source: https://github.com/sendgrid/sendgrid-php/blob/main/USAGE.md Retrieves detailed information about your SendGrid user account, including account type and reputation. This is done via a GET request to the /user/account endpoint. ```php $response = $sg->client->user()->account()->get(); print $response->statusCode() . "\n"; print $response->body() . "\n"; print_r($response->headers()); ``` -------------------------------- ### Attach File from S3 with SendGrid PHP Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This example shows how to attach a file stored in Amazon S3 to an email using SendGrid PHP. It requires the AWS SDK for PHP to retrieve the file from S3. The code retrieves the file, encodes its content, and then attaches it to the email before sending. ```php 'latest', 'region' => 'us-east-1' // This should match the region of your S3 bucket. ]); try { // Get the object. // See https://docs.aws.amazon.com/AmazonS3/latest/dev/RetrieveObjSingleOpPHP.html $result = $s3->getObject([ 'Bucket' => $bucket, 'Key' => $keyname ]); $keyExplode = explode('/',$keyname); $attachmentFilename = end($keyExplode); $attachmentContent = base64_encode($result['Body']); $attachmentContentType = $result['ContentType']; $email = new \SendGrid\Mail\Mail(); $email->setFrom("test@example.com", "Example User"); $email->setSubject("Attaching a File from S3"); $email->addTo("test@example.com", "Example User"); $email->addContent("text/plain", "See attached file from S3."); $email->addContent( "text/html", "See attached file from S3." ); $attachment = new \SendGrid\Mail\Attachment(); $attachment->setContent($attachmentContent); $attachment->setType($attachmentContentType); $attachment->setFilename($attachmentFilename); $attachment->setDisposition("attachment"); $attachment->setContentId($attachmentFilename); //Only used if disposition is set to inline $email->addAttachment($attachment); $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { $response = $sendgrid->send($email); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage() ."\n"; } } catch (S3Exception $e) { echo 'Caught exception: '. $e->getMessage() . "\n"; } ``` -------------------------------- ### Configure Email with Headers, Sections, Categories, and Settings Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This snippet demonstrates how to configure an email with global headers, sections, categories, reply-to addresses, ASM settings, IP pool names, and various mail settings like BCC, bypass spam management, footer, sandbox mode, and spam check. It also includes tracking settings for clicks, opens, subscriptions, and Google Analytics. ```php $globalHeaders = [ new Header("X-Month", "January"), new Header("X-Year", "2017") ]; $email->addGlobalHeaders($globalHeaders); $email->addSection( new Section( "%section1%", "Substitution for Section 1 Tag" ) ); $sections = [ new Section( "%section3%", "Substitution for Section 3 Tag" ), new Section( "%section4%", "Substitution for Section 4 Tag" ) ]; $email->addSections($sections); $email->addCategory(new Category("Category 1")); $categories = [ new Category("Category 2"), new Category("Category 3") ]; $email->addCategories($categories); $email->setBatchId( new BatchId( "MWQxZmIyODYtNjE1Ni0xMWU1LWI3ZTUtMDgwMDI3OGJkMmY2LWEzMmViMjYxMw" ) ); $email->setReplyTo( new ReplyTo( "dx+replyto2@example.com", "DX Team Reply To 2" ) ); $asm = new Asm( new GroupId(1), new GroupsToDisplay([1,2,3,4]) ); $email->setAsm($asm); $email->setIpPoolName(new IpPoolName("23")); $mail_settings = new MailSettings(); $mail_settings->setBccSettings( new BccSettings(true, "bcc@example.com") ); // Note: Bypass Spam, Bounce, and Unsubscribe management cannot // be combined with Bypass List Management $mail_settings->setBypassBounceManagement( new BypassBounceManagement(true) ); $mail_settings->setBypassSpamManagement( new BypassSpamManagement(true) ); $mail_settings->setBypassUnsubscribeManagement( new BypassUnsubscribeManagement(true) ); // OR $mail_settings->setBypassListManagement( new BypassListManagement(true) ); $mail_settings->setFooter( new Footer(true, "Footer", "Footer") ); $mail_settings->setSandBoxMode(new SandBoxMode(true)); $mail_settings->setSpamCheck( new SpamCheck(true, 1, "http://mydomain.com") ); $email->setMailSettings($mail_settings); $tracking_settings = new TrackingSettings(); $tracking_settings->setClickTracking( new ClickTracking(true, true) ); $tracking_settings->setOpenTracking( new OpenTracking(true, "--sub--") ); $tracking_settings->setSubscriptionTracking( new SubscriptionTracking( true, "subscribe", "subscribe", "%%sub%%" ) ); $tracking_settings->setGanalytics( new Ganalytics( true, "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign" ) ); $email->setTrackingSettings($tracking_settings); $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { $response = $sendgrid->send($email); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; } ``` -------------------------------- ### General v3 Web API Usage (Fluent Interface) with SendGrid PHP Source: https://github.com/sendgrid/sendgrid-php/blob/main/README.md This example shows how to interact with the SendGrid v3 Web API using the fluent interface provided by the SendGrid PHP library. It demonstrates fetching suppression data (bounces). ```php $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); try { $response = $sg->client->suppression()->bounces()->get(); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; } ``` -------------------------------- ### SendGrid PHP: Handling Exceptions Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This snippet shows how to catch and handle exceptions that may occur during the email sending process using the SendGrid PHP library. It prints the exception message to the output. ```php print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; } ``` -------------------------------- ### Send Email with Legacy Template (Alternative SendGrid PHP) Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This alternative snippet demonstrates sending an email with a legacy SendGrid template using a more fluent interface. It shows setting the 'From' address, subject, multiple recipients with personalization, and content using `addContent`. The template ID is also set, and API key authentication with error handling is included. ```php /sendgrid-php.php'; use SendGrid\Mail\Mail; $email = new Mail(); $email->setFrom("test@sendgrid.com", "Example User"); $email->setSubject("I'm replacing the subject tag"); $email->addTo( "test+test1@example.com", "Example User1", [ "-name-" => "Example User 1", "-city-" => "Denver" ], 0 ); $email->addTo( "test+test2@example.com", "Example User2", [ "-name-" => "Example User 2", "-city-" => "Denver" ], 1 ); $email->addTo( "test+test3@example.com", "Example User3", [ "-name-" => "Example User 3", "-city-" => "Redwood City" ], 2 ); $email->addContent("text/plain", "I'm replacing the **body tag**"); $email->addContent("text/html", "I'm replacing the body tag"); $email->setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932"); $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { $response = $sendgrid->send($email); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; } ``` -------------------------------- ### SendGrid PHP: Basic Email Sending Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This snippet demonstrates the fundamental process of creating and sending an email using the SendGrid PHP library. It includes setting the subject, recipients (To, Cc, Bcc), content (plain text and HTML), and attachments. It also shows how to set a template ID and global headers. ```php /sendgrid-php.php'; use SendGrid\Mail\Asm; use SendGrid\Mail\Attachment; use SendGrid\Mail\BatchId; use SendGrid\Mail\Bcc; use SendGrid\Mail\BccSettings; use SendGrid\Mail\BypassBounceManagement; use SendGrid\Mail\BypassListManagement; use SendGrid\Mail\BypassSpamManagement; use SendGrid\Mail\BypassUnsubscribeManagement; use SendGrid\Mail\Category; use SendGrid\Mail\Cc; use SendGrid\Mail\ClickTracking; use SendGrid\Mail\Content; use SendGrid\Mail\CustomArg; use SendGrid\Mail\Footer; use SendGrid\Mail\From; use SendGrid\Mail\Ganalytics; use SendGrid\Mail\GroupId; use SendGrid\Mail\GroupsToDisplay; use SendGrid\Mail\Header; use SendGrid\Mail\HtmlContent; use SendGrid\Mail\IpPoolName; use SendGrid\Mail\Mail; use SendGrid\Mail\MailSettings; use SendGrid\Mail\OpenTracking; use SendGrid\Mail\PlainTextContent; use SendGrid\Mail\ReplyTo; use SendGrid\Mail\SandBoxMode; use SendGrid\Mail\Section; use SendGrid\Mail\SendAt; use SendGrid\Mail\SpamCheck; use SendGrid\Mail\Subject; use SendGrid\Mail\SubscriptionTracking; use SendGrid\Mail\Substitution; use SendGrid\Mail\TemplateId; use SendGrid\Mail\To; use SendGrid\Mail\TrackingSettings; $email = new Mail(); // For a detailed description of each of these settings, // please see the // [documentation](https://sendgrid.com/docs/API_Reference/api_v3.html). $email->setSubject( new Subject("Sending with Twilio SendGrid is Fun 2") ); $email->addTo(new To("test@example.com", "Example User")); $email->addTo(new To("test+1@example.com", "Example User1")); $toEmails = [ new To("test+2@example.com", "Example User2"), new To("test+3@example.com", "Example User3") ]; $email->addTos($toEmails); $email->addCc(new Cc("test+4@example.com", "Example User4")); $ccEmails = [ new Cc("test+5@example.com", "Example User5"), new Cc("test+6@example.com", "Example User6") ]; $email->addCcs($ccEmails); $email->addBcc( new Bcc("test+7@example.com", "Example User7") ); $bccEmails = [ new Bcc("test+8@example.com", "Example User8"), new Bcc("test+9@example.com", "Example User9") ]; $email->addBccs($bccEmails); $email->addHeader(new Header("X-Test1", "Test1")); $email->addHeader(new Header("X-Test2", "Test2")); $headers = [ new Header("X-Test3", "Test3"), new Header("X-Test4", "Test4") ]; $email->addHeaders($headers); $email->addDynamicTemplateData( new Substitution("subject1", "Example Subject 1") ); $email->addDynamicTemplateData( new Substitution("name", "Example Name 1") ); $email->addDynamicTemplateData( new Substitution("city1", "Denver") ); $substitutions = [ new Substitution("subject2", "Example Subject 2"), new Substitution("name2", "Example Name 2"), new Substitution("city2", "Orange") ]; $email->addDynamicTemplateDatas($substitutions); $email->addCustomArg(new CustomArg("marketing1", "false")); $email->addCustomArg(new CustomArg("transactional1", "true")); $email->addCustomArg(new CustomArg("category", "name")); $customArgs = [ new CustomArg("marketing2", "true"), new CustomArg("transactional2", "false"), new CustomArg("category", "name") ]; $email->addCustomArgs($customArgs); $email->setSendAt(new SendAt(1461775051)); // You can add a personalization index or personalization parameter to the above // methods to add and update multiple personalizations. You can learn more about // personalizations [here](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html). // The values below this comment are global to an entire message $email->setFrom(new From("test@example.com", "Twilio SendGrid")); $email->setGlobalSubject( new Subject("Sending with Twilio SendGrid is Fun and Global 2") ); $plainTextContent = new PlainTextContent( "and easy to do anywhere, even with PHP" ); $htmlContent = new HtmlContent( "and easy to do anywhere, even with PHP" ); $email->addContent($plainTextContent); $email->addContent($htmlContent); $contents = [ new Content("text/calendar", "Party Time!!"), new Content("text/calendar2", "Party Time 2!!") ]; $email->addContents($contents); $email->addAttachment( new Attachment( "base64 encoded content1", "image/png", "banner.png", "inline", "Banner" ) ); $attachments = [ new Attachment( "base64 encoded content2", "banner2.jpeg", "image/jpeg", "attachment", "Banner 3" ), new Attachment( "base64 encoded content3", "banner3.gif", "image/gif", "inline", "Banner 3" ) ]; $email->addAttachments($attachments); $email->setTemplateId( new TemplateId("d-13b8f94fbcae4ec6b75270d6cb59f932") ); $email->addGlobalHeader(new Header("X-Day", "Monday")); ``` -------------------------------- ### Send Email with Legacy Template (SendGrid PHP) Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This snippet shows how to send an email using a legacy SendGrid transactional template. It demonstrates setting the 'From' address, multiple 'To' recipients with personalization data (like -name- and -city-), subject, plain text content, HTML content, and the template ID. It also includes API key authentication and error handling. ```php /sendgrid-php.php'; use \SendGrid\Mail\From; use \SendGrid\Mail\To; use \SendGrid\Mail\Subject; use \SendGrid\Mail\PlainTextContent; use \SendGrid\Mail\HtmlContent; use \SendGrid\Mail\Mail; $from = new From("test@example.com", "Example User"); $tos = [ new To( "test+test1@example.com", "Example User1", [ '-name-' => 'Example User 1', '-city-' => 'Denver' ] ), new To( "test+test2@example.com", "Example User2", [ '-name-' => 'Example User 2', '-city-' => 'Irvine' ] ), new To( "test+test3@example.com", "Example User3", [ '-name-' => 'Example User 3', '-city-' => 'Redwood City' ] ) ]; $subject = new Subject("I'm replacing the subject tag"); $plainTextContent = new PlainTextContent( "I'm replacing the **body tag**" ); $htmlContent = new HtmlContent( "I'm replacing the body tag" ); $email = new Mail( $from, $tos, $subject, $plainTextContent, $htmlContent ); $email->setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932"); $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { $response = $sendgrid->send($email); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; } ``` -------------------------------- ### General v3 Web API Usage (Without Fluent Interface) with SendGrid PHP Source: https://github.com/sendgrid/sendgrid-php/blob/main/README.md This example demonstrates interacting with the SendGrid v3 Web API without using the fluent interface, by directly specifying the API endpoint. It also shows fetching suppression data (bounces). ```php $apiKey = getenv('SENDGRID_API_KEY'); $sg = new \SendGrid($apiKey); try { $response = $sg->client->_("suppression/bounces")->get(); print $response->statusCode() . "\n"; print_r($response->headers()); print $response->body() . "\n"; } catch (Exception $e) { echo 'Caught exception: '. $e->getMessage(). "\n"; } ``` -------------------------------- ### Update Local Repository with Upstream Changes Source: https://github.com/sendgrid/sendgrid-php/blob/main/CONTRIBUTING.md Instructions for updating your local repository with the latest changes from the upstream development branch. This ensures your local copy is up-to-date before starting new work. ```bash git checkout git pull upstream ``` -------------------------------- ### Send SMS Message using Twilio PHP SDK Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md Sends an SMS message using the Twilio PHP SDK. It requires Twilio account credentials and a valid Twilio phone number. ```php messages->create( '8881231234', // Text this number [ 'from' => '9991231234', // From a valid Twilio number 'body' => 'Hello from Twilio!' ] ); ``` -------------------------------- ### SendGrid PHP Email Composition and Sending Source: https://github.com/sendgrid/sendgrid-php/blob/main/USE_CASES.md This snippet demonstrates how to compose an email using the SendGrid PHP library, including setting recipients, subjects, content, attachments, and various mail/tracking settings. It then sends the email using the SendGrid API and prints the response status code and headers. ```php /sendgrid-php.php'; use SendGrid\Mail\Mail; $email = new Mail(); // For a detailed description of each of these settings, // please see the // [documentation](https://sendgrid.com/docs/API_Reference/api_v3.html). $email->setSubject("Sending with Twilio SendGrid is Fun 2"); $email->addTo("test@example.com", "Example User"); $email->addTo("test+1@example.com", "Example User1"); $toEmails = [ "test+2@example.com" => "Example User2", "test+3@example.com" => "Example User3" ]; $email->addTos($toEmails); $email->addCc("test+4@example.com", "Example User4"); $ccEmails = [ "test+5@example.com" => "Example User5", "test+6@example.com" => "Example User6" ]; $email->addCcs($ccEmails); $email->addBcc("test+7@example.com", "Example User7"); $bccEmails = [ "test+8@example.com" => "Example User8", "test+9@example.com" => "Example User9" ]; $email->addBccs($bccEmails); $email->addHeader("X-Test1", "Test1"); $email->addHeader("X-Test2", "Test2"); $headers = [ "X-Test3" => "Test3", "X-Test4" => "Test4", ]; $email->addHeaders($headers); $email->addDynamicTemplateData("subject1", "Example Subject 1"); $email->addDynamicTemplateData("name1", "Example Name 1"); $email->addDynamicTemplateData("city1", "Denver"); $substitutions = [ "subject2" => "Example Subject 2", "name2" => "Example Name 2", "city2" => "Orange" ]; $email->addDynamicTemplateDatas($substitutions); $email->addCustomArg("marketing1", "false"); $email->addCustomArg("transactional1", "true"); $email->addCustomArg("category", "name"); $customArgs = [ "marketing2" => "true", "transactional2" => "false", "category" => "name" ]; $email->addCustomArgs($customArgs); $email->setSendAt(1461775051); // You can add a personalization index or personalization parameter to the above // methods to add and update multiple personalizations. You can learn more about // personalizations [here](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html). // The values below this comment are global to an entire message $email->setFrom("test@example.com", "Twilio SendGrid"); $email->setGlobalSubject("Sending with Twilio SendGrid is Fun and Global 2"); $email->addContent( "text/plain", "and easy to do anywhere, even with PHP" ); $email->addContent( "text/html", "and easy to do anywhere, even with PHP" ); $contents = [ "text/calendar" => "Party Time!!", "text/calendar2" => "Party Time 2!!" ]; $email->addContents($contents); $email->addAttachment( "base64 encoded content1", "image/png", "banner.png", "inline", "Banner" ); $attachments = [ [ "base64 encoded content2", "image/jpeg", "banner2.jpeg", "attachment", "Banner 3" ], [ "base64 encoded content3", "image/gif", "banner3.gif", "inline", "Banner 3" ] ]; $email->addAttachments($attachments); $email->setTemplateId("d-13b8f94fbcae4ec6b75270d6cb59f932"); $email->addGlobalHeader("X-Day", "Monday"); $globalHeaders = [ "X-Month" => "January", "X-Year" => "2017" ]; $email->addGlobalHeaders($globalHeaders); $email->addSection("%section1%", "Substitution for Section 1 Tag"); $sections = [ "%section3%" => "Substitution for Section 3 Tag", "%section4%" => "Substitution for Section 4 Tag" ]; $email->addSections($sections); $email->addCategory("Category 1"); $categories = [ "Category 2", "Category 3" ]; $email->addCategories($categories); $email->setBatchId( "MWQxZmIyODYtNjE1Ni0xMWU1LWI3ZTUtMDgwMDI3OGJkMmY2LWEzMmViMjYxMw" ); $email->setReplyTo("dx+replyto2@example.com", "DX Team Reply To 2"); $email->setAsm(1, [1, 2, 3, 4]); $email->setIpPoolName("23"); // Mail Settings $email->setBccSettings(true, "bcc@example.com"); // Note: Bypass Spam, Bounce, and Unsubscribe management cannot // be combined with Bypass List Management $email->enableBypassBounceManagement(); $email->enableBypassListManagement(); $email->enableBypassSpamManagement(); $email->enableBypassUnsubscribeManagement(); //$email->disableBypassListManagement(); $email->setFooter(true, "Footer", "Footer"); $email->enableSandBoxMode(); //$email->disableSandBoxMode(); $email->setSpamCheck(true, 1, "http://mydomain.com"); // Tracking Settings $email->setClickTracking(true, true); $email->setOpenTracking(true, "--sub--"); $email->setSubscriptionTracking( true, "subscribe", "subscribe", "%%sub%%" ); $email->setGanalytics( true, "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign" ); $sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY')); try { $response = $sendgrid->send($email); print $response->statusCode() . "\n"; print_r($response->headers()); ```