Benjamin Crouzier
Benjamin Crouzier

Reputation: 41945

How to specify a template in a transational email with mailjet

I am using the mailjet gem in my rails app.

In the Gemfile

gem 'mailjet'

And some config: initializers/mailjet.rb

Mailjet.configure do |config|
  config.api_key = 'your-api-key'
  config.secret_key = 'your-secret-key'
  config.default_from = '[email protected]'
end

application.rb (or environments/development.rb for testing)

config.action_mailer.delivery_method = :mailjet

So far so good. The emails are correctly sent with mailjet. But I would like to be able to specify a template. This way, every sent emails look the same as the ones sent via the mailjet interface.

In interface, you can choose a template when creating a new campain in "my templates". I would like to specify one of those when sending an email

How do I do that ?

Upvotes: 2

Views: 1866

Answers (2)

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41945

I had created a solution that wraps around the current campaign system. It works like this:

  • Create a campaign in mailjet
  • Create a template for that campaign
  • Return to the campaign list, inspect the start, and get the id of this campaign.
  • Add 510969 => 'my_new_email_template' in mailjet.rake
  • Run rake mailjet:import
  • The new template will be saved as erb in app/views/shared/_auto_my_new_email_template.html.erb
  • You can send an email with the new template by calling: CustomMailer.send_mailjet_email('my_new_email_template', emails, subject, {USER_NAME: 'John'})

The last parameter will replace ===USER_NAME=== by John in the email (as a means to be able to have variables in the emails). In mailjet you would write something like this:

Hello, ===USER_NAME===, 
click here to activate your account: ===ACTIVATION_LINK=== ...

lib/tasks/mailjet.rake:

# WARNING: you need to add gem 'mailjet' in Gemfile for development group to use this task
# if mailjet is included in development, this breaks mails_viewer
# (see http://stackoverflow.com/questions/17083110/the-gem-mailjet-breaks-mails-viewer)

namespace :mailjet do
  desc "Importe les templates d'emails de mailjet dans l'appli. (inscription, mot de passe perdu etc)"
  task :import => :environment do
    templates = {
        510969 => 'reset_password_instructions',
        510681 => 'contact_request'
        # more templates here
    }
    templates.each do |id, path|
      fullpath = "app/views/shared/_auto_#{path}.html.erb"
      out_file = File.new(fullpath, 'w')
      out_file.puts(Mailjet::Campaign.find(id).html)
      out_file.close
      puts "Importing email ##{id} to #{fullpath}\n"
    end
  end

end

app/mailers/custom_mailer.rb:

class CustomMailer < ActionMailer::Base
  default :from => "\"Support\" <[email protected]>"
  default :to => "\"Support\" <[email protected]>"

  def send_email(emails, content, subject, reply_to = nil)
    @emails = emails.split(',')
    @content = content

    @emails.each do |m|
      #logger.info "==========> sending email to #{m}"
      mail(to: m, subject: subject, reply_to: reply_to) do |format|
        format.html { content }
        #format.text { content }                                                                 
      end.deliver
    end

  end

  def send_mailjet_email(template, emails, subject, params = {}, reply_to = nil)
    template = "app/views/shared/_auto_#{template}.html.erb"
    content = File.read(template) # can't render twice with rails
    params.each do |key, value|
      key = "===#{key.upcase}==="
      content.gsub!(key, value)
    end
    content.gsub!('Voir la version en ligne', '')
    content.gsub!(t('mailjet_unsubscribe'), '')
    content.gsub!(/Voir[^\w]+la[^\w]+version[^\w]+en[^\w]+ligne/, '')
    content.gsub!('https://fr.mailjet.com/campaigns/template/', '') # sometimes mailjet appends this at the begining of links
    content = content.html_safe
    CustomMailer.send_email(emails, content, subject, reply_to)
  end

end

With this in place, I can tell my manager to just go edit the emails as he wants. I tell him that he can use ===USER_NAME=== or other variables. When he is done, I just rake mailjet:import, and that retrieves all templates as erb. This has been in production for a few months now, and it has been very useful.

One last note: @madflo, If you can let us see all sent emails in the mailjet interface, that would be awesome. (Right now, you can see the last 50 or so sent emails). I would love to be able to check whether some emails have been sent for, say, at least a month ago.

Upvotes: 1

madflo
madflo

Reputation: 292

Disclamer: I am working with the Developer Relations group of Mailjet.

Calling a Template from the API is a feature that should be accessible from the API in the coming months. We are currently beta-testing it!

In the meantime — I would suggest using an erb or another local template with your code.

You can always use (and copy/paste) the HTML code from our Template Builder into your rails template and call it to generate the body of your e-mail. This is a quick fix — and we will improve this in the coming weeks.

Upvotes: 1

Related Questions