### Local Testing Setup with Sample Data Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/inbound/README.md This sequence of commands prepares your environment for local testing using predefined sample data. It involves cloning the SendGrid Ruby repository, navigating into the project directory, and installing all necessary Ruby gem dependencies. ```Bash git clone https://github.com/sendgrid/sendgrid-ruby.git cd sendgrid-ruby bundle install ``` -------------------------------- ### Local Testing Setup with Real Data Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/inbound/README.md This setup prepares your local environment to receive and process real inbound email data. It involves cloning the repository, installing dependencies, and starting the local Inbound Parse listener, which will then be exposed to the internet via ngrok. ```Bash git clone https://github.com/sendgrid/sendgrid-ruby.git cd sendgrid-ruby bundle install rackup ``` -------------------------------- ### Run SendGrid Ruby Mail Helper Example Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/mail/README.md Executes the provided Ruby example script for the SendGrid Mail helper. This command demonstrates how to run the helper's example, requiring the 'SENDGRID_API_KEY' environment variable to be set for successful execution. ```bash ruby examples/helpers/mail/example.rb ``` -------------------------------- ### Install SendGrid Ruby Gem Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/README.md This section details the methods for installing the `sendgrid-ruby` library. Users can either add the gem to their application's Gemfile and run `bundle`, or install it directly using the `gem install` command. This step makes the library's functionalities accessible within Ruby projects. ```bash gem 'sendgrid-ruby' ``` ```bash bundle ``` ```bash gem install sendgrid-ruby ``` -------------------------------- ### Run Ruby Examples with Local Library Version Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/CONTRIBUTING.md Instructions to modify example files to use the locally built version of the `sendgrid-ruby` library instead of the installed gem, facilitating local testing and development. This involves changing the `require` statement and then executing the Ruby script. ```ruby require_relative './lib/sendgrid-ruby.rb' ``` ```bash ruby example.rb ``` -------------------------------- ### Install Latest or Specific Version of SendGrid Ruby Gem Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/TROUBLESHOOTING.md Provides instructions for installing the `sendgrid-ruby` gem using RubyGems, allowing users to specify a particular version (X.X.X) or implicitly install the latest. This involves adding the gem to the Gemfile and running `bundle`, or direct installation via `gem install`. ```bash gem 'sendgrid-ruby', 'X.X.X' ``` ```bash bundle ``` ```bash gem install sendgrid-ruby -v X.X.X ``` -------------------------------- ### Run SendGrid Ruby Settings Example Script Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/settings/README.md Executes the example script for the SendGrid Ruby settings helper module from the command line. This script demonstrates how to use the Settings object to interact with Twilio SendGrid API settings, requiring the SENDGRID_API_KEY environment variable to be set. ```bash ruby examples/helpers/settings/example.rb ``` -------------------------------- ### Install Ruby Dependencies with Bundler Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/CONTRIBUTING.md Command to install all required Ruby gems for the project using Bundler, ensuring all dependencies are met for development and testing. ```bash bundle install ``` -------------------------------- ### Install Specific Version of SendGrid Ruby Gem Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/TROUBLESHOOTING.md Instructions for installing a specific version of the `sendgrid-ruby` gem using RubyGems, either by adding it to your Gemfile or installing it directly via the command line. This is useful for maintaining compatibility or working with older versions. ```bash gem 'sendgrid-ruby', '1.1.6' ``` ```bash bundle ``` ```bash gem install sendgrid-ruby -v 1.1.6 ``` -------------------------------- ### Configure and Send Email with SendGrid Ruby (Comprehensive) Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/mail_helper_v3.md Demonstrates how to construct a SendGrid email message in Ruby, setting various properties like sender, subject, content (text/HTML), multiple attachments, global headers, sections, and sending the email via the SendGrid API client. This example showcases a wide range of message customization options. ```ruby msg.set_from(SendGrid::Email.new('test0@example.com', 'Example User0')) msg.set_global_subject('Sending with Twilio SendGrid is Fun'); msg.add_content(MimeType::Text, 'and easy to do anywhere, even with Ruby') msg.add_content(MimeType::Html, 'and easy to do anywhere, even with Ruby') contents = [ SendGrid::Content.new('text/calendar', 'Party Time!!'), SendGrid::Content.new('text/calendar2', 'Party Time 2!!') ] msg.add_contents(contents) msg.add_attachment('balance_001.pdf', 'base64 encoded content', 'application/pdf', 'attachment', 'Balance Sheet') attachments = [ SendGrid::Attachment.new('banner.png', 'base64 encoded content', 'image/png', 'inline', 'Banner'), SendGrid::Attachment.new('banner2.png', 'base64 encoded content', 'image/png', 'inline', 'Banner 2'), ] msg.add_attachments(attachments) msg.set_template_id('13b8f94f-bcae-4ec6-b752-70d6cb59f932') msg.add_global_header('X-Day', 'Monday') global_headers = [ 'X-Month' => 'January', 'X-Year' => '2017' ] msg.set_global_headers(global_headers) msg.add_section('%section1%', 'Substitution for Section 1 Tag') sections = [ '%section2%' => 'Substitution for Section 2 Tag', '%section3%' => 'Substitution for Section 3 Tag' ] msg.add_sections(sections) begin response = client.send_email(msg) rescue Exception => e puts e.message end puts response.status_code puts response.body puts response.headers ``` -------------------------------- ### Install Twilio Ruby Gem Directly Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/sms.md Alternative method to install the Twilio Ruby helper library directly using the gem command. This is useful for standalone scripts or when not using Bundler. ```bash gem install twilio-ruby ``` -------------------------------- ### SendGrid Ruby Email with Transactional Templates and Substitutions Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/mail_helper_v3.md Demonstrates how to send an email using a SendGrid transactional template. This example shows how to set a template ID and provide substitutions for dynamic content within the template, such as names and cities. ```ruby client = SendGrid::Client.new(api_key: ENV['SENDGRID_API_KEY']) from = SendGrid::Email.new('test@example.com', 'Example User') to = SendGrid::Email.new('test@example.com', 'Example User') subject = 'Sending with Twilio SendGrid is Fun' plain_text_content = 'and easy to do anywhere, even with Ruby' html_content = 'and easy to do anywhere, even with Ruby' msg = SendGrid::Message.new(from, to, subject, plain_text_content, html_content) substitutions = [ '-name-' => 'Example User', '-city-' => 'Denver' ] msg.add_substitutions(substitutions) msg.set_template_id('13b8f94f-bcae-4ec6-b752-70d6cb59f932') begin response = client.send_email(msg) rescue Exception => e puts e.message end puts response.status_code puts response.body puts response.headers ``` -------------------------------- ### Configure SendGrid API Key Environment Variable Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/CONTRIBUTING.md Steps to set up the `SENDGRID_API_KEY` environment variable for local development and running examples. This includes saving the key to a local file (`sendgrid.env`), adding it to `.gitignore`, and sourcing it into the current shell session. ```bash echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env echo "sendgrid.env" >> .gitignore source ./sendgrid.env ``` -------------------------------- ### Constructing a SendGrid Email Message with Advanced Settings in Ruby Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/mail_helper_v3.md This Ruby snippet illustrates the full capabilities of the SendGrid client library for email composition. It covers setting up the client, defining sender and recipient emails, subject, and content. Crucially, it shows how to add various email components like individual and batch recipients (To, CC, BCC), custom headers, dynamic substitutions, and custom arguments. The example further demonstrates how to apply these settings to multiple personalization blocks within a single email, providing a robust foundation for complex email sending scenarios. ```ruby client = SendGrid::Client.new(api_key: ENV['SENDGRID_API_KEY']) from = SendGrid::Email.new('test@example.com', 'Example User') to = SendGrid::Email.new('test@example.com', 'Example User') subject = 'Sending with Twilio SendGrid is Fun' plain_text_content = 'and easy to do anywhere, even with Ruby' html_content = 'and easy to do anywhere, even with Ruby' msg = SendGrid::Message.new(from, to, subject, plain_text_content, html_content) # For a detailed description of each of these settings, please see the [documentation](https://sendgrid.com/docs/API_Reference/api_v3.html). msg.add_to(SendGrid::Email.new('test1@example.com', 'Example User1')) to_emails = [ SendGrid::Email.new('test2@example.com', 'Example User2'), SendGrid::Email.new('test3@example.com', 'Example User3') ]; msg.add_tos(to_emails) msg.add_cc(SendGrid::Email.new('test4@example.com', 'Example User4')) cc_emails = [ SendGrid::Email.new('test5@example.com', 'Example User5'), SendGrid::Email.new('test6@example.com', 'Example User6') ]; msg.add_ccs(cc_emails) msg.add_bcc(SendGrid::Email.new('test7@example.com', 'Example User7')) bcc_emails = [ SendGrid::Email.new('test8@example.com', 'Example User8'), SendGrid::Email.new('test9@example.com', 'Example User9') ]; msg.add_bccs(bcc_emails) msg.add_header('X-Test1', 'Test1') msg.add_header('X-Test2', 'Test2') headers = [ 'X-Test3' => 'Test3', 'X-Test4' => 'Test4' ] msg.add_headers(headers) msg.add_substitution('%name1%', 'Example Name 1'); msg.add_substitution('%city1%', 'Denver'); substitutions = [ '%name2%' => 'Example Name 2', '%city2%' => 'Orange' ] msg.add_substitutions(substitutions) msg.add_custom_arg('marketing1', 'false') msg.add_custom_arg('transactional1', 'true') custom_args = [ 'marketing2' => 'true', 'transactional2' => 'false' ] msg.add_custom_args(custom_args) msg.set_send_at(1461775051) msg.set_subject('this subject overrides the Global Subject on the default Personalization') # If you need to add more [Personalizations](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html), here is an example of adding another Personalization by passing in a personalization index. msg.add_to(SendGrid::Email.new('test10@example.com', 'Example User10'), 1) to_emails = [ SendGrid::Email.new('test11@example.com', 'Example User11'), SendGrid::Email.new('test12@example.com', 'Example User12') ]; msg.add_tos(to_emails, 1) msg.add_cc(SendGrid::Email.new('test13@example.com', 'Example User13'), 1) cc_emails = [ SendGrid::Email.new('test14@example.com', 'Example User14'), SendGrid::Email.new('test15@example.com', 'Example User15') ]; msg.add_ccs(cc_emails, 1) msg.add_bcc(SendGrid::Email.new('test16@example.com', 'Example User16'), 1) bcc_emails = [ SendGrid::Email.new('test17@example.com', 'Example User17'), SendGrid::Email.new('test18@example.com', 'Example User18') ]; msg.add_bccs(bcc_emails, 1) msg.add_header('X-Test5', 'Test5', 1) msg.add_header('X-Test6', 'Test6', 1) headers = [ 'X-Test7' => 'Test7', 'X-Test8' => 'Test8' ] msg.add_headers(headers, 1) msg.add_substitution('%name3%', 'Example Name 3', 1); msg.add_substitution('%city3%', 'Redwood City', 1); substitutions = [ '%name4%' => 'Example Name 4', '%city4%' => 'London' ] msg.add_substitutions(substitutions, 1) msg.add_custom_arg('marketing3', 'true', 1) msg.add_custom_arg('transactional3', 'false', 1) custom_args = [ 'marketing4' => 'false', 'transactional4' => 'true' ] msg.add_custom_args(custom_args, 1) msg.set_send_at(1461775052, 1) msg.set_subject('this subject overrides the Global Subject on the second Personalization', 1) ``` -------------------------------- ### Install Ruby Dependencies with Bundler Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/sms.md Command to install the dependencies listed in the Gemfile, including the Twilio Ruby gem, using Bundler. This ensures all required libraries are available. ```bash bundle ``` -------------------------------- ### SendGrid Ruby Email with File Attachments Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/mail_helper_v3.md Illustrates how to initialize the SendGrid client, create an email message, encode a local file to Base64, and attach it to the email before sending. It highlights the process of adding a single attachment from a file path. ```ruby client = SendGrid::Client.new(api_key: ENV['SENDGRID_API_KEY']) from = SendGrid::Email.new('test@example.com', 'Example User') to = SendGrid::Email.new('test@example.com', 'Example User') subject = 'Sending with Twilio SendGrid is Fun' plain_text_content = 'and easy to do anywhere, even with Ruby' html_content = 'and easy to do anywhere, even with Ruby' msg = SendGrid::Message.new(from, to, subject, plain_text_content, html_content) bytes = File.read('/path/to/the/attachment.pdf') encoded = Base64.encode64(bytes) msg.add_attachment('balance_001.pdf', encoded, 'application/pdf', 'attachment', 'Balance Sheet') begin response = client.send_email(msg) rescue Exception => e puts e.message end puts response.status_code puts response.body puts response.headers ``` -------------------------------- ### Run Inbound Parse Listener Locally Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/inbound/README.md Starts the Inbound Parse listener using `rackup`, which runs the Sinatra server to process incoming email data. This command should be executed in the `sendgrid-ruby` directory to listen for inbound parse webhooks. ```Ruby rackup ``` -------------------------------- ### SendGrid Ruby: Send Multiple Emails with Substitutions Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/mail_helper_v3.md Shows how to send multiple emails to multiple recipients, incorporating dynamic content through substitutions, using the SendGrid Ruby library. This advanced example uses arrays for recipients and subjects, and a hash for substitutions, allowing personalized content for each email sent through a single API call. ```ruby require 'sendgrid-ruby' from = SendGrid::Email.new('test@example.com', 'Example User') tos = [ SendGrid::Email.new('test1@example.com', 'Example User1'), SendGrid::Email.new('test2@example.com', 'Example User2'), SendGrid::Email.new('test3@example.com', 'Example User3') ]; subjects = [ 'Sending with Twilio SendGrid is Fun', 'Sending with Twilio SendGrid is Super Fun', 'Sending with Twilio SendGrid is Super Duper Fun' ]; plain_text_content = 'and easy to do anywhere, even with Ruby' html_content = 'and easy to do anywhere, even with Ruby' values = [ 'Name 1', 'Name 2', 'Name 3' ] substitutions = { '-name1-' => values } msg = SendGrid::Mail.create(from: from, tos: tos, subject: subjects, plain_text_content: plain_text_content, html_content: html_content, substitutions: substitutions) client = SendGrid::Client.new(api_key: ENV['SENDGRID_API_KEY']) begin response = client.send_email(msg) rescue Exception => e puts e.message end puts response.status_code puts response.body puts response.headers ``` -------------------------------- ### SendGrid Ruby: Send Single Email to Multiple Recipients Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/mail_helper_v3.md Illustrates sending a single email to multiple recipients using the SendGrid Ruby library. This example creates an array of `SendGrid::Email` objects for recipients, then uses it to construct and send a `SendGrid::Mail` object. It also handles API key retrieval from environment variables. ```ruby require 'sendgrid-ruby' from = SendGrid::Email.new('test@example.com', 'Example User') tos = [ SendGrid::Email.new('test1@example.com', 'Example User1'), SendGrid::Email.new('test2@example.com', 'Example User2'), SendGrid::Email.new('test3@example.com', 'Example User3') ]; subject = 'Sending with Twilio SendGrid is Fun' plain_text_content = 'and easy to do anywhere, even with Ruby' html_content = 'and easy to do anywhere, even with Ruby' msg = SendGrid::Mail.create(from: from, tos: tos, subject: subject, plain_text_content: plain_text_content, html_content: html_content, substitutions: {}) client = SendGrid::Client.new(api_key: ENV['SENDGRID_API_KEY']) begin response = client.send_email(msg) rescue Exception => e puts e.message end puts response.status_code puts response.body puts response.headers ``` -------------------------------- ### SendGrid Inbound Parse Webhook Example Payload Structure Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/inbound/sample_data/default_data.txt An example of the `multipart/form-data` payload that SendGrid sends to a configured Inbound Parse Webhook URL. This payload contains parsed email data, including email headers, sender and recipient information, HTML and plain text body content, attachment count, and authentication details like DKIM and SPF results. It demonstrates the typical structure for processing incoming emails via SendGrid's API. ```APIDOC Content-Disposition: form-data; name="headers" MIME-Version: 1.0 Received: by 0.0.0.0 with HTTP; Wed, 10 Aug 2016 18:10:13 -0700 (PDT) From: Example User Date: Wed, 10 Aug 2016 18:10:13 -0700 Subject: Inbound Parse Test Data To: inbound@inbound.example.com Content-Type: multipart/alternative; boundary=001a113df448cad2d00539c16e89 --xYzZY Content-Disposition: form-data; name="dkim" {@sendgrid.com : pass} --xYzZY Content-Disposition: form-data; name="to" inbound@inbound.example.com --xYzZY Content-Disposition: form-data; name="html" Hello Twilio SendGrid! --xYzZY Content-Disposition: form-data; name="from" Example User --xYzZY Content-Disposition: form-data; name="text" Hello Twilio SendGrid! --xYzZY Content-Disposition: form-data; name="sender_ip" 0.0.0.0 --xYzZY Content-Disposition: form-data; name="envelope" {"to":["inbound@inbound.example.com"],"from":"test@example.com"} --xYzZY Content-Disposition: form-data; name="attachments" 0 --xYzZY Content-Disposition: form-data; name="subject" Testing non-raw --xYzZY Content-Disposition: form-data; name="charsets" {"to":"UTF-8","html":"UTF-8","subject":"UTF-8","from":"UTF-8","text":"UTF-8"} --xYzZY Content-Disposition: form-data; name="SPF" pass ``` -------------------------------- ### Clone Fork and Configure Upstream Remote Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/CONTRIBUTING.md This snippet demonstrates how to clone your forked repository, navigate into its directory, and add the original repository as an 'upstream' remote. This setup is crucial for keeping your fork synchronized with the main project and pulling the latest changes. ```bash git clone https://github.com/sendgrid/sendgrid-ruby cd sendgrid-ruby git remote add upstream https://github.com/sendgrid/sendgrid-ruby ``` -------------------------------- ### SendGrid Transactional Template Structure Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/mail_helper_v3.md Defines the structure and placeholders for a SendGrid transactional email template, including the template ID, subject line with a substitution, and an HTML body with multiple substitution tags for dynamic content. ```text Template ID: 13b8f94f-bcae-4ec6-b752-70d6cb59f932 ``` ```text Email Subject: <%subject%> ``` ```html Template Body: Hello -name-,

I'm glad you are trying out the template feature!

<%body%>

I hope you are having a great day in -city- :)

``` -------------------------------- ### Example SendGrid Inbound Parse Webhook Payload (Multipart/form-data) Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/inbound/sample_data/raw_data.txt This snippet provides a complete example of the `multipart/form-data` payload that SendGrid sends to a configured inbound parse webhook URL. It demonstrates how an incoming email's various components, such as headers, plain text, HTML content, and metadata like sender, recipient, and authentication results (DKIM, SPF), are encapsulated within the POST request body. This format is crucial for applications to correctly parse and process incoming emails. ```HTTP --xYzZY Content-Disposition: form-data; name="dkim" {@sendgrid.com : pass} --xYzZY Content-Disposition: form-data; name="email" MIME-Version: 1.0 Received: by 0.0.0.0 with HTTP; Wed, 10 Aug 2016 14:44:21 -0700 (PDT) From: Example User Date: Wed, 10 Aug 2016 14:44:21 -0700 Subject: Inbound Parse Test Raw Data To: inbound@inbound.inbound.com Content-Type: multipart/alternative; boundary=001a113ee97c89842f0539be8e7a --001a113ee97c89842f0539be8e7a Content-Type: text/plain; charset=UTF-8 Hello Twilio SendGrid! --001a113ee97c89842f0539be8e7a Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Hello Twilio SendGrid! --001a113ee97c89842f0539be8e7a-- --xYzZY Content-Disposition: form-data; name="to" inbound@inbound.inbound.com --xYzZY Content-Disposition: form-data; name="from" Example User --xYzZY Content-Disposition: form-data; name="sender_ip" 0.0.0.0 --xYzZY Content-Disposition: form-data; name="envelope" {"to":["inbound@inbound.inbound.com"],"from":"test@example.com"} --xYzZY Content-Disposition: form-data; name="subject" Testing with Request.bin --xYzZY Content-Disposition: form-data; name="charsets" {"to":"UTF-8","subject":"UTF-8","from":"UTF-8"} --xYzZY Content-Disposition: form-data; name="SPF" pass --xYzZY-- ``` -------------------------------- ### SendGrid Ruby: Send Single Email to Single Recipient Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/mail_helper_v3.md Demonstrates how to send a single email to one recipient using the SendGrid Ruby library. It initializes `SendGrid::Email` objects for sender and recipient, constructs a `SendGrid::Mail` object with content, and sends it via `SendGrid::Client`. The API key is expected from an environment variable. ```ruby require 'sendgrid-ruby' from = SendGrid::Email.new('test@example.com', 'Example User') to = SendGrid::Email.new('test@example.com', 'Example User') subject = 'Sending with Twilio SendGrid is Fun' plain_text_content = 'and easy to do anywhere, even with Ruby' html_content = 'and easy to do anywhere, even with Ruby' msg = SendGrid::Mail.create(from: from, tos: to, subject: subject, plain_text_content: plain_text_content, html_content: html_content, substitutions: {}) client = SendGrid::Client.new(api_key: ENV['SENDGRID_API_KEY']) begin response = client.send_email(msg) rescue Exception => e puts e.message end puts response.status_code puts response.body puts response.headers ``` -------------------------------- ### Clone GitHub Repository and Add Upstream Remote Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/FIRST_TIMERS.md Clones a forked GitHub repository to the local machine, navigates into the directory, and adds the original repository as an 'upstream' remote. This setup is crucial for synchronizing your fork with the main project's changes. ```bash git clone https://github.com/your_username/sendgrid-ruby cd sendgrid-ruby git remote add upstream https://github.com/sendgrid/sendgrid-ruby ``` -------------------------------- ### Send SMS Message using Twilio Ruby API Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/sms.md Ruby code example demonstrating how to initialize the Twilio REST API client and send an SMS message. It uses environment variables for credentials and specifies 'from', 'to', and 'body' parameters for the message. ```ruby require 'twilio-ruby' # put your own credentials here account_sid = ENV['TWILIO_ACCOUNT_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] # set up a client to talk to the Twilio REST API @client = Twilio::REST::Client.new account_sid, auth_token @client.api.account.messages.create( from: '+14159341234', to: '+16105557069', body: 'Hey there!' ) ``` -------------------------------- ### SendGrid Dynamic Template Subject Placeholder Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/transactional-templates.md An example of a dynamic placeholder for the email subject within a SendGrid transactional template, allowing the subject to be customized at send time. ```text {{subject}} ``` -------------------------------- ### SendGrid Inbound Parse Webhook Payload Fields Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/inbound/sample_data/raw_data.txt This section details the individual fields included in the SendGrid Inbound Parse webhook payload. Each field is sent as a part of a `multipart/form-data` POST request, providing comprehensive information about the received email. ```APIDOC Webhook Payload Fields: - dkim: string Description: The DKIM authentication result for the email. Example: "{@sendgrid.com : pass}" - email: string (MIME formatted email) Description: The full raw MIME-encoded content of the incoming email, including headers, plain text, and HTML parts. Example: (See main code snippet for full content) - to: string Description: The recipient email address(es) as extracted from the email's 'To' header. Example: "inbound@inbound.inbound.com" - from: string Description: The sender's email address and name as extracted from the email's 'From' header. Example: "Example User " - sender_ip: string Description: The IP address of the sender. Example: "0.0.0.0" - envelope: JSON object Description: A JSON string containing the 'to' and 'from' addresses as determined by the SMTP envelope. Properties: - to: array of strings Description: An array of recipient email addresses from the SMTP envelope. Example: ["inbound@inbound.inbound.com"] - from: string Description: The sender's email address from the SMTP envelope. Example: "test@example.com" Example: {"to":["inbound@inbound.inbound.com"],"from":"test@example.com"} - subject: string Description: The subject of the email. Example: "Testing with Request.bin" - charsets: JSON object Description: A JSON string indicating the character sets used for various email fields. Properties: - to: string Description: Character set for the 'To' field. Example: "UTF-8" - subject: string Description: Character set for the 'Subject' field. Example: "UTF-8" - from: string Description: Character set for the 'From' field. Example: "UTF-8" Example: {"to":"UTF-8","subject":"UTF-8","from":"UTF-8"} - SPF: string Description: The SPF authentication result for the email. Example: "pass" ``` -------------------------------- ### Sync Local Branch with Upstream Changes Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/CONTRIBUTING.md This command sequence is used to update your local development branch with the latest changes from the upstream repository. It ensures your local work is based on the most current version of the project before starting new features or fixes, preventing merge conflicts. ```bash git checkout git pull upstream ``` -------------------------------- ### Retrieve Bounces with SendGrid Ruby Fluent API Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/README.md This Ruby snippet demonstrates how to make a GET request to the SendGrid v3 Web API using the fluent interface to retrieve bounce suppression list entries. It initializes the API client with an API key and then accesses the `suppression.bounces` endpoint, printing the response details. ```ruby require 'sendgrid-ruby' sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) response = sg.client.suppression.bounces.get() puts response.status_code puts response.body puts response.parsed_body puts response.headers ``` -------------------------------- ### Fetching SendGrid Email Statistics with Ruby Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/email-statistics.md This Ruby code snippet demonstrates how to use the `sendgrid-ruby` gem to fetch email statistics from the SendGrid API. It shows examples of retrieving daily statistics between two dates and weekly statistics for a specific category, then iterating through the results to display metrics like requests, bounces, opens, and clicks. It requires a SendGrid API key and the `sendgrid-ruby` gem. ```ruby require 'sendgrid-ruby' require 'date' include SendGrid sg_client = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']).client stats = SendGrid::EmailStats.new(sendgrid_client: sg_client) # Fetch stats by day, between 2 dates from = Date.new(2017, 10, 01) to = Date.new(2017, 10, 12) email_stats = stats.by_day(from, to) email_stats.metrics if !email_stats.error? email_stats.metrics.each do |metric| puts "Date - #{metric.date}" puts "Number of Requests - #{metric.requests}" puts "Bounces - #{metric.bounces}" puts "Opens - #{metric.opens}" puts "Clicks - #{metric.clicks}" end end # Fetch stats by week, between 2 dates for a category from = Date.new(2017, 10, 01) to = Date.new(2017, 10, 12) category = 'abcd' email_stats = stats.by_week(from, to, category) if !email_stats.error? email_stats.metrics.each do |metric| puts "Date - #{metric.date}" puts "Number of Requests - #{metric.requests}" puts "Bounces - #{metric.bounces}" puts "Opens - #{metric.opens}" puts "Clicks - #{metric.clicks}" end end ``` -------------------------------- ### Retrieve Bounces with SendGrid Ruby Non-Fluent API Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/README.md This Ruby snippet shows an alternative way to make a GET request to the SendGrid v3 Web API without using the fluent interface. It directly constructs the endpoint path `_("suppression/bounces")` to retrieve bounce suppression list entries, then prints the status code, body, parsed body, and headers of the API response. ```ruby require 'sendgrid-ruby' sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) response = sg.client._("suppression/bounces").get() puts response.status_code puts response.body puts response.parsed_body puts response.headers ``` -------------------------------- ### Clone SendGrid Ruby Repository Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/CONTRIBUTING.md Instructions to clone the SendGrid Ruby project repository from GitHub and navigate into its directory, which is the first step for local development. ```bash git clone https://github.com/sendgrid/sendgrid-ruby.git cd sendgrid-ruby ``` -------------------------------- ### Load Twilio Environment Variables and Add to Gitignore (Linux/Mac) Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/twilio-setup.md This snippet shows how to add the `twilio.env` file to `.gitignore` to prevent committing sensitive credentials to version control. It also demonstrates how to source the file to load the environment variables into the current shell session, making them available for applications. ```bash echo "twilio.env" >> .gitignore source ./twilio.env ``` -------------------------------- ### Initialize SendGrid API Client with API Key Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/TROUBLESHOOTING.md Shows two methods for initializing the SendGrid API client in Ruby: one using an environment variable for the API key (recommended for security) and another by directly embedding the API key string. The `api_key` parameter is used to pass the authentication token. ```ruby sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) ``` ```ruby sg = SendGrid::API.new(api_key: 'SENDGRID_API_KEY') ``` -------------------------------- ### Run Dockerized Tests for SendGrid Ruby Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/CONTRIBUTING.md Command to execute all project tests using Docker, which simplifies setting up the required Twilio SendGrid mock API. It also shows how to open an interactive shell within the test container. ```bash make test-docker ``` ```bash command=bash make test-docker ``` -------------------------------- ### Set Twilio API Credentials as Environment Variables (Linux/Mac) Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/twilio-setup.md This snippet demonstrates how to export Twilio API Key/Secret or Account SID/Auth Token to a `twilio.env` file on Linux or macOS. This file can then be sourced to load the variables into the current shell session, providing a secure way to manage credentials. ```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 ``` -------------------------------- ### Initialize Twilio Email Client in Ruby Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/twilio-email.md This Ruby snippet demonstrates how to instantiate the `TwilioEmail::API` client. It shows two common authentication methods: using `TWILIO_API_KEY` and `TWILIO_API_SECRET`, or `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` from environment variables. This client is designed to have an interface similar to `SendGrid::API`. ```ruby mail_client = TwilioEmail::API(username: ENV['TWILIO_API_KEY'], password: ENV['TWILIO_API_SECRET']) # or mail_client = TwilioEmail::API(username: ENV['TWILIO_ACCOUNT_SID'], password: ENV['TWILIO_AUTH_TOKEN']) ``` -------------------------------- ### Send Sample Inbound Parse Data Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/inbound/README.md Executes a Ruby script to send predefined sample data to the local Inbound Parse listener. This is useful for testing the parsing logic without needing to send actual emails, especially while waiting for MX record propagation. ```Bash cd [path to sendgrid-ruby] bundle install ruby ./lib/sendgrid/helpers/inbound/send.rb ./lib/sendgrid/helpers/inbound/sample_data/default_data.txt ``` -------------------------------- ### Create New Git Topic Branch Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/FIRST_TIMERS.md Creates and switches to a new Git branch, typically used for developing a new feature, change, or fix. This isolates your work from the main development branch, allowing for independent development and easier integration later. ```bash git checkout -b ``` -------------------------------- ### SendGrid Ruby: Send Email with Transactional Template using Mail Helper Class Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/legacy-templates.md This Ruby code demonstrates how to send an email using the SendGrid Ruby SDK's Mail Helper Class. It constructs the email object by setting the sender, recipient, subject, template ID, and adding custom substitutions, then sends the email via the SendGrid API. ```ruby require 'sendgrid-ruby' include SendGrid mail = SendGrid::Mail.new mail.from = Email.new(email: 'test@example.com') mail.subject = 'I\'m replacing the subject tag' personalization = Personalization.new personalization.add_to(Email.new(email: 'test@example.com')) personalization.add_substitution(Substitution.new(key: '-name-', value: 'Example User')) personalization.add_substitution(Substitution.new(key: '-city-', value: 'Denver')) mail.add_personalization(personalization) mail.template_id = '13b8f94f-bcae-4ec6-b752-70d6cb59f932' sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) begin response = sg.client.mail._("send").post(request_body: mail.to_json) rescue Exception => e puts e.message end puts response.status_code puts response.body puts response.parsed_body puts response.headers ``` -------------------------------- ### Push Local Topic Branch to Origin Fork Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/FIRST_TIMERS.md Pushes the local topic branch and its commits to the 'origin' remote, which typically points to the user's forked repository on GitHub. This makes your changes available online and prepares them for a pull request. ```bash git push origin ``` -------------------------------- ### Expose Local Server with ngrok Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/inbound/README.md Uses ngrok to create a public URL that tunnels to your local Sinatra server running on port 9292. This allows SendGrid's Inbound Parse Webhook to send real-time email data to your local machine for development and testing. ```Bash ngrok http 9292 ``` -------------------------------- ### Push Local Topic Branch to Fork Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/CONTRIBUTING.md This command pushes your local topic branch, along with all its commits, to your remote fork on GitHub. This step makes your changes available online, allowing you to open a pull request against the main repository for review and potential merging. ```bash git push origin ``` -------------------------------- ### Send Email using SendGrid Ruby Mail Helper Class Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/README.md This Ruby code demonstrates how to send an email using the `sendgrid-ruby` library's Mail Helper Class. It constructs the email content, sender, recipient, and subject using dedicated helper objects, then sends the email via the SendGrid API client. The response status, body, parsed body, and headers are printed for debugging. ```ruby require 'sendgrid-ruby' include SendGrid from = SendGrid::Email.new(email: 'test@example.com') to = SendGrid::Email.new(email: 'test@example.com') subject = 'Sending with Twilio SendGrid is Fun' content = SendGrid::Content.new(type: 'text/plain', value: 'and easy to do anywhere, even with Ruby') mail = SendGrid::Mail.new(from, subject, to, content) sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) response = sg.client.mail._('send').post(request_body: mail.to_json) puts response.status_code puts response.body puts response.parsed_body puts response.headers ``` -------------------------------- ### Set Permanent Twilio Environment Variables (Windows) Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/twilio-setup.md This snippet demonstrates how to permanently set Twilio API Key/Secret or Account SID/Auth Token as environment variables on Windows using the `setx` command. Variables set this way will persist across CLI sessions and system reboots, making them globally available. ```cmd 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" ``` -------------------------------- ### Set SendGrid API Key Environment Variable (Bash) Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/README.md This snippet provides instructions for setting the `SENDGRID_API_KEY` environment variable, which is essential for authenticating requests to the SendGrid API. It creates a local file to store the key, adds it to `.gitignore`, and sources it to make the key available in the current shell session. ```bash echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env echo "sendgrid.env" >> .gitignore source ./sendgrid.env ``` -------------------------------- ### Add Sinatra Gem Dependency Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/lib/sendgrid/helpers/inbound/README.md Adds the Sinatra gem to your Gemfile, specifying a version range compatible with the Inbound Parse helper. This dependency is crucial for running the local web server that processes inbound email data. ```Ruby gem 'sinatra', '>= 1.4.7', '< 3' ``` -------------------------------- ### Create a New Git Topic Branch Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/CONTRIBUTING.md This command creates and switches to a new topic branch, which is essential for isolating your feature, change, or fix. Working on a dedicated branch prevents direct modifications to the main development branch and simplifies pull request management and code reviews. ```bash git checkout -b ``` -------------------------------- ### Add Twilio Ruby Gem to Gemfile Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/sms.md Instructions to add the Twilio Ruby helper library to your application's Gemfile for dependency management, ensuring it's included in your project. ```bash gem 'twilio-ruby' ``` -------------------------------- ### Set Temporary Twilio Environment Variables (Windows) Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/twilio-setup.md This snippet illustrates how to temporarily set Twilio API Key/Secret or Account SID/Auth Token as environment variables in a Windows command prompt. These variables will only be accessible within the current CLI session and will be lost once the session is closed. ```cmd 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 ``` -------------------------------- ### Handle SendGrid API Error Messages in Ruby Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/TROUBLESHOOTING.md Demonstrates how to catch and display error messages returned by the SendGrid API when making a mail send request. This snippet uses a `begin...rescue` block to capture exceptions and print the error message. ```ruby begin response = sg.client.mail._("send").post(request_body: mail.to_json) rescue Exception => e puts e.message end ``` -------------------------------- ### SendGrid Send Email with Ruby Mail Helper Class Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/use-cases/transactional-templates.md Demonstrates how to send a transactional email using SendGrid's Ruby library with the Mail Helper Class. This method constructs the email object programmatically, adding personalizations and dynamic template data before sending. ```Ruby require 'sendgrid-ruby' include SendGrid mail = Mail.new mail.from = Email.new(email: 'test@example.com') personalization = Personalization.new personalization.add_to(Email.new(email: 'test@example.com')) personalization.add_dynamic_template_data({ "subject" => "Testing Templates", "name" => "Example User", "city" => "Denver" }) mail.add_personalization(personalization) mail.template_id = 'd-2c214ac919e84170b21855cc129b4a5f' sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) begin response = sg.client.mail._("send").post(request_body: mail.to_json) rescue Exception => e puts e.message end puts response.status_code puts response.body puts response.parsed_body puts response.headers ``` -------------------------------- ### Synchronize Local Branch with Upstream Main Source: https://github.com/sendgrid/sendgrid-ruby/blob/main/FIRST_TIMERS.md Pulls changes from the upstream 'main' branch into the current local topic branch. This command ensures your local branch is up-to-date with the latest changes from the original repository, optionally using rebase for a cleaner commit history. ```bash git pull [--rebase] upstream main ```