This example shows how to send an email for user signups. You can also checkout this gem for more advanced features.
Let's generate a Mailer class. Mailer classes function as our controllers for email views.
rails generate mailer UserNotifierMailer
Now we open up the mailer we've just generated, app/mailers/user_notifier_mailer.rb
and add a mailer action that sends users a signup email.
1class UserNotifierMailer < ApplicationMailer2default :from => 'any_from_address@example.com'34# send a signup email to the user, pass in the user object that contains the user's email address5def send_signup_email(user)6@user = user7mail( :to => @user.email,8:subject => 'Thanks for signing up for our amazing app' )9end10end
Now we need a view that corresponds to our action and outputs HTML for our email. Create a file app/views/user_notifier_mailer/send_signup_email.html.erb
as follows:
1<!DOCTYPE html>2<html>3<head>4<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />5</head>6<body>7<h1>Thanks for signing up, <%= @user.name %>!</h1>8<p>Thanks for joining and have a great day! Now sign in and do9awesome things!</p>10</body>11</html>
If you don't have a user model quite yet, generate one quickly.
1rails generate scaffold user name email login2rake db:migrate
Now in the controller for the user model app/controllers/users_controller.rb
, add a call to UserNotifierMailer.send_signup_email
when a user is saved.
1class UsersController < ApplicationController2def create3# Create the user from params4@user = User.new(user_params)5if @user.save6# Deliver the signup email7UserNotifierMailer.send_signup_email(@user).deliver8redirect_to(@user, :notice => 'User created')9else10render :action => 'new'11end12end1314private1516def user_params17params.require(:user).permit(:name, :email, :login)18end19end
Alright, now we're cooking! Let's get it all going through SendGrid.
In config/environment.rb
specify your ActionMailer settings to point to SendGrid's servers.
1ActionMailer:\:Base.smtp_settings = {2:user_name => 'apikey', # This is the string literal 'apikey', NOT the ID of your API key3:password => '<SENDGRID_API_KEY>', # This is the secret sendgrid API key which was issued during API key creation4:domain => 'yourdomain.com',5:address => 'smtp.sendgrid.net',6:port => 587,7:authentication => :plain,8:enable_starttls_auto => true9}
That's it! When a new user object is saved, an email will be sent to the user via SendGrid.
As a best practice, you should not store your credentials directly in the source but should instead store them in configuration files or environment variables. See this tutorial on environment variables in Rails. And for Rails Versions 5.2+ see Securely storing custom credentials in Rails.