Skip to contentSkip to navigationSkip to topbar
On this page

SMTP Ruby Code Example


These examples require the JSON Ruby Library(link takes you to an external page).

(error)

Danger

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.


SmtpApiHeader.rb

smtpapiheaderrb page anchor

This header is required for each example.

1
# !/usr/bin/ruby
2
# Version 1.0
3
# Last Updated 6/22/2009
4
require 'json'
5
6
class SmtpApiHeader
7
8
def initialize()
9
@data = {}
10
end
11
12
def addTo(to)
13
@data['to'] ||= []
14
@data['to'] += to.kind_of?(Array) ? to : [to]
15
end
16
17
def addSubVal(var, val)
18
if not @data['sub']
19
@data['sub'] = {}
20
end
21
if val.instance_of?(Array)
22
@data['sub'][var] = val
23
else
24
@data['sub'][var] = [val]
25
end
26
end
27
28
def setUniqueArgs(val)
29
if val.instance_of?(Hash)
30
@data['unique_args'] = val
31
end
32
end
33
34
def setCategory(cat)
35
36
@data['category'] = cat
37
end
38
39
def addFilterSetting(fltr, setting, val)
40
if not @data['filters']
41
@data['filters'] = {}
42
end
43
if not @data['filters'][fltr]
44
@data['filters'][fltr] = {}
45
end
46
if not @data['filters'][fltr]['settings']
47
@data['filters'][fltr]['settings'] = {}
48
end
49
@data['filters'][fltr]['settings'][setting] = val
50
end
51
52
def asJSON()
53
json = JSON.generate @data
54
return json.gsub(/(["\]}])([,:])(["\[{])/, '\\1\\2 \\3')
55
end
56
57
def as_string()
58
json = asJSON()
59
str = 'X-SMTPAPI: %s' % json.gsub(/(.{1,72})( +|$\n?)|(.{1,72})/,"\\1\\3\n")
60
return str
61
end
62
63
end

1
require './SmtpApiHeader.rb'
2
require 'mail'
3
4
Mail.defaults do
5
delivery_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 }
12
end
13
14
hdr = SmtpApiHeader.new
15
16
receiver = ['recipienteexampexample@example.com', 'recipient2@domain.com']
17
18
hdr.addTo(receiver)
19
hdr.setUniqueArgs({'test' => 1, 'foo' =>2})
20
hdr.setCategory('yourCategory')
21
22
mail = Mail.deliver do
23
header['X-SMTPAPI'] = hdr.asJSON()
24
to 'willnotdeliver@domain.com' # When using SMTPAPI's 'to' parameter, this address will not get delivered to
25
from 'yourEmailAddress@domain.com'
26
subject 'Ruby Example using X-SMTPAPI header'
27
text_part do
28
body 'You would put your content here, but I am going to say: Hello world!'
29
end
30
html_part do
31
content_type 'text/html; charset=UTF-8'
32
body '<b>Hello world!</b> Glad to have you here!'
33
end
34
end
35