Skip to content

Instantly share code, notes, and snippets.

@sulmanweb
Created September 7, 2022 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sulmanweb/eab697301cf8209572c5a95af6543b3a to your computer and use it in GitHub Desktop.
Save sulmanweb/eab697301cf8209572c5a95af6543b3a to your computer and use it in GitHub Desktop.
Send Emails using SendGrid SDK for Ruby in Rails using Dynamic SendGrid Email Templates
# frozen_string_literal: true
require 'sendgrid-ruby'
#### Example Call
# EmailJob.new.perform(
# @user.id,
# { name: @user.name },
# ENV.fetch('EXPORT_TEMPLATE', nil),
# [
# {
# file: @tempfile.path,
# type: 'application/csv',
# name: @tempfile.path.split('/').last,
# content_id: 'export_file'
# }
# ]
# )
# This is the email job that will be sent to the user
class EmailJob
include SendGrid
# From Email and Name
NOREPLY_FROM_EMAIL = 'no-reply@allwallet.app'
NOREPLY_FROM_NAME = 'All Wallet'
# include sidekiq to call perform as perform_async
def perform(user_id, subsitutions, template_id, attachments = nil) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
# initialize sendgrid api
sg = SendGrid::API.new(api_key: ENV.fetch('SENDGRID_API_KEY', nil))
# we will get to_email from user object saved in db
user = User.kept.find_by(id: user_id)
return unless user
# initialize mail object of sendgrid
mail = Mail.new
# fill 'from' data from the constants mentioned above
mail.from = Email.new(email: NOREPLY_FROM_EMAIL, name: NOREPLY_FROM_NAME)
# personalization is object for email to data and templates
personalization = Personalization.new
# add user data to which email to be sent
personalization.add_to(Email.new(email: user.email, name: user.name))
# add substitutions to template created in sendgrid to replace the variable in template like `{{name}}`
# {
# "name": "Sulman Baig"
# }
personalization.add_dynamic_template_data(subsitutions)
mail.add_personalization(personalization)
mail.template_id = template_id
# If attachments are sent as arguments
if attachments.present? && attachments.is_a?(Array) && attachments.size.positive?
attachments.each do |attachment_input|
attachment = Attachment.new
# attachment has to be sent as base64 encoded string
attachment.content = Base64.strict_encode64(File.read(attachment_input[:file])) # file: path of file saved in local or remote
attachment.type = attachment_input[:type] # type of file e.g. application/csv
attachment.filename = attachment_input[:name] # filename
attachment.disposition = 'attachment'
attachment.content_id = attachment_input[:content_id] # e.g. export_file
mail.add_attachment(attachment)
end
end
begin
# Send Email
sg.client.mail._('send').post(request_body: mail.to_json)
rescue StandardError => e
# TODO: capture exception
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment