#!/usr/bin/ruby# Version 1.0# Last Updated 6/22/2009require'json'classSmtpApiHeaderdefinitialize()@data={}enddefaddTo(to)@data['to']||=[]@data['to']+=to.kind_of?(Array)?to:[to]enddefaddSubVal(var,val)ifnot@data['sub']@data['sub']={}endifval.instance_of?(Array)@data['sub'][var]=valelse@data['sub'][var]=[val]endenddefsetUniqueArgs(val)ifval.instance_of?(Hash)@data['unique_args']=valendenddefsetCategory(cat)@data['category']=catenddefaddFilterSetting(fltr,setting,val)ifnot@data['filters']@data['filters']={}endifnot@data['filters'][fltr]@data['filters'][fltr]={}endifnot@data['filters'][fltr]['settings']@data['filters'][fltr]['settings']={}end@data['filters'][fltr]['settings'][setting]=valenddefasJSON()json=JSON.generate@datareturnjson.gsub(/(["\]}])([,:])(["\[{])/,'\\1\\2 \\3')enddefas_string()json=asJSON()str='X-SMTPAPI: %s'%json.gsub(/(.{1,72})( +|$\n?)|(.{1,72})/,"\\1\\3\n")returnstrendend
require'./SmtpApiHeader.rb'require'mail'Mail.defaultsdodelivery_method:smtp,{:address=>'smtp.sendgrid.net',:port=>587,:domain=>'sendgrid.com',:user_name=>'yourSendGridUsername',:password=>'yourSendGridPassword',:authentication=>'plain',:enable_starttls_auto=>true}endhdr=SmtpApiHeader.newreceiver=['recipienteexampexample@example.com','recipient2@example.com']hdr.addTo(receiver)hdr.setUniqueArgs({'test'=>1,'foo'=>2})hdr.setCategory('yourCategory')mail=Mail.deliverdoheader['X-SMTPAPI']=hdr.asJSON()to'willnotdeliver@example.com'# When using SMTPAPI's 'to' parameter, this address will not get delivered tofrom'yourEmailAddress@domain.com'subject'Ruby Example using X-SMTPAPI header'text_partdobody'You would put your content here, but I am going to say: Hello world!'endhtml_partdocontent_type'text/html; charset=UTF-8'body'<b>Hello world!</b><br>Glad to have you here!'endend