Send emails with a Bootstrap template using Gmail
Tags: rails, ruby, programming, webdev
Published: 2020-12-09 20:20:57

In this tutorial, we are going to use Rails ActionMailer and Gmail to send emails with bootstrap styling. This tutorial has 2 parts, first is setting up the ActionMailer and Gmail and the second part is setting up bootstrap email template.

## Set up Mailer

### Generate a mailer

```
rails g mailer sample_mailer
```
This will generate a ruby `app/mailers/sample_mailer.rb` file and a directory `app/views/sample_mailer` for SampleMailer's view files.
The `app/mailers/sample_mailer.rb` file looks like
```ruby
class SampleMailer < ApplicationMailer
  default from: "from@example.com"
end
```
Change the `from@example.com` with the Gmail account email which you want to use for sending emails, and then write a method that will construct the email. We've named the method `welcome_email`(which will construct a very dull welcome email for the sake of this tutorial).
```ruby
class SampleMailer < ActionMailer::Base
  default from: "your_email_here@gmail.com"

  def welcome_email(welcome_message, name, email_to, subject)
    @message = welcome_message
    @name = name
    make_bootstrap_mail(to: email_to, subject: subject)
  end
end
```
### Gmail configuration

Write the following config in your `/config/environments/production.rb` or `/config/environments/development.rb` (whichever you're going to use for sending the emails, of course you can use both; in that case put the config in both the files)

```ruby
config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
  address: 'smtp.gmail.com',
  port: 587,
  user_name: ENV['GMAIL_USERNAME'],
  password: ENV['GMAIL_PASSWORD'],
  authentication: 'plain',
  enable_starttls_auto: true
}
```
Gmail username and password are sensitive data so we have stored them in the environment variables, for the rails `development` environment, you can set up environment variables by using the [Dotenv gem](https://github.com/bkeepers/dotenv) or [Figaro gem](https://github.com/laserlemon/figaro). Don't forget to restart server after setting up environment variables.

### Enable Gmail's Less secure apps setting

Go to [this settings link](https://myaccount.google.com/lesssecureapps) and enable less secure apps. Without enabling this setting Gmail won't let you send emails from your app.

## Set up Bootstrap email template

### Include the bootstrap-email gem

Add this to your Gemfile
```ruby
gem 'bootstrap-email'
```
and then do
```
bundle install
```
### Create bootstrap layout file

Create a file `/app/views/layouts/bootstrap-mailer.html.erb` and paste the following HTML into it. This file will act as a container file for the mailer views that you're going to render. 
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <%= stylesheet_link_tag "application-mailer", media: "all" %>
  </head>
  <body class="bg-light">
    <%= yield %>
  </body>
</html>
```
### Tell mailer to use the Bootstrap email layout
Specifying this in the `ApplicationMailer` class configures the layout option for all the descendants of the `ApplicationMailer` class

```ruby
# app/mailers/application_mailer.rb

class ApplicationMailer < ActionMailer::Base
  layout 'bootstrap-mailer'
end
```
### Create stylesheet for bootstrap email template

Create a new stylesheet `/app/assets/stylesheets/application-mailer.scss` and import `bootstrap-email`. This is where your custom styles and overrides that you want to be inlined should live.
```scss
// /app/assets/stylesheets/application-mailer.scss

@import 'bootstrap-email';
```
### Precompiling the stylesheet

Add this line in `/config/initializers/asset.rb` to compile your new SASS file.
```ruby
Rails.application.config.assets.precompile += %w( application-mailer.scss )
```

### Create the view file

Create the view file `/app/views/sample_mailer/welcome_email.html.erb`. Any instance variables you had in the `welcome_email` method in the file `app/views/products_mailer/sample_email.html.erb` can be used in this view file.
Let's use this as an example view file for sending the email.
```erb
<div class="card">
  <div class="card-header">
    Welcome
  </div>
  <div class="card-body">
    <h5 class="card-title">Welcome <%= name %></h5>
    <p class="card-text"><%= welcome_message %></p>
    <a href="#" class="btn btn-primary">Platform</a>
  </div>
</div>

```
### And finally, send the email

To send the email, you need to do this in your application
```ruby
welcome_message = "Hello your're welcome to our platform!"
name = current_user.name
email_to = current_user.email
subject = 'Welcome Email'

SampleMailer.welcome_email(welcome_message, name, email_to, subject).deliver if email_to
```
### References
The resources used for creating this tutorial are listed below
1. https://launchschool.com/blog/handling-emails-in-rails
2. https://github.com/stuyam/bootstrap-email

Cover Image credits: <span><a href="https://unsplash.com/@mathyaskurmann?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mathyas Kurmann</a> on <a href="https://unsplash.com/s/photos/mail?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>