Using sendgrid templates, you can customize a template once via sendgrid's GUI email creator tool, and send the email via the sendgrid api with our own custom content. This makes it easier than going through the steps of creating a mailer and coding a template manually, pushing an update to the server and sending via command line (pain in the ass)
Create A Dynmaic Template
buttonTemplate ID
, example: d-7d913b9fb74d454db6fc6bb507254741
{{first_name}}
require 'sendgrid-ruby'
include SendGrid
class Users::SendgridTemplateMailerWorker
include Sidekiq::Worker
sidekiq_options retry: false
def perform(user_id, template_id)
@user = User.find(user_id)
mail = SendGrid::Mail.new
mail.from = Email.new(email: 'announcements@sample.com')
personalization = Personalization.new
personalization.add_to(Email.new(email: @user.email))
personalization.add_dynamic_template_data(
{ subject: 'Testing Templates Subject', first_name: @user.first_name }
)
mail.add_personalization(personalization)
mail.template_id = template_id
sg = SendGrid::API.new(api_key: SENDGRID_API_KEY)
begin
response = sg.client.mail._('send').post(request_body: mail.to_json)
rescue Exception => e
puts e.message
end
end
end
template_id
created on sendgrid webappUsers.SendgridTemplateMailerWorker(@user.id, template_id)