### 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", "