These examples require the JSON Ruby Library.
Categories and Unique Arguments will be stored as a "Not PII" field and may be used for counting or other operations as SendGrid runs its systems. These fields generally cannot be redacted or removed. You should take care not to place PII in this field. SendGrid does not treat this data as PII, and its value may be visible to SendGrid employees, stored long-term, and may continue to be stored after you've left SendGrid's platform.
This header is required for each example.
1# !/usr/bin/ruby2# Version 1.03# Last Updated 6/22/20094require 'json'56class SmtpApiHeader78def initialize()9@data = {}10end1112def addTo(to)13@data['to'] ||= []14@data['to'] += to.kind_of?(Array) ? to : [to]15end1617def addSubVal(var, val)18if not @data['sub']19@data['sub'] = {}20end21if val.instance_of?(Array)22@data['sub'][var] = val23else24@data['sub'][var] = [val]25end26end2728def setUniqueArgs(val)29if val.instance_of?(Hash)30@data['unique_args'] = val31end32end3334def setCategory(cat)3536@data['category'] = cat37end3839def addFilterSetting(fltr, setting, val)40if not @data['filters']41@data['filters'] = {}42end43if not @data['filters'][fltr]44@data['filters'][fltr] = {}45end46if not @data['filters'][fltr]['settings']47@data['filters'][fltr]['settings'] = {}48end49@data['filters'][fltr]['settings'][setting] = val50end5152def asJSON()53json = JSON.generate @data54return json.gsub(/(["\]}])([,:])(["\[{])/, '\\1\\2 \\3')55end5657def as_string()58json = asJSON()59str = 'X-SMTPAPI: %s' % json.gsub(/(.{1,72})( +|$\n?)|(.{1,72})/,"\\1\\3\n")60return str61end6263end
1require './SmtpApiHeader.rb'2require 'mail'34Mail.defaults do5delivery_method :smtp, { :address => 'smtp.sendgrid.net',6:port => 587,7:domain => 'sendgrid.com',8:user_name => 'apikey',9:api_key => 'yourSendGridAPIKey',10:authentication => 'plain',11:enable_starttls_auto => true }12end1314hdr = SmtpApiHeader.new1516receiver = ['recipienteexampexample@example.com', 'recipient2@domain.com']1718hdr.addTo(receiver)19hdr.setUniqueArgs({'test' => 1, 'foo' =>2})20hdr.setCategory('yourCategory')2122mail = Mail.deliver do23header['X-SMTPAPI'] = hdr.asJSON()24to 'willnotdeliver@domain.com' # When using SMTPAPI's 'to' parameter, this address will not get delivered to25from 'yourEmailAddress@domain.com'26subject 'Ruby Example using X-SMTPAPI header'27text_part do28body 'You would put your content here, but I am going to say: Hello world!'29end30html_part do31content_type 'text/html; charset=UTF-8'32body '<b>Hello world!</b> Glad to have you here!'33end34end35