You are here:
< Back

Ruby on Rails

This example shows how to send an email for user signups.

Setup ActionMailer

Let’s generate a Mailer class. Mailer classes function as our controllers for email views.

$ rails generate mailer UserNotifier

Now we open up the mailer we’ve just generated, app/mailers/user_notifier.rb and add a mailer action that sends users a signup email.

class UserNotifier < ActionMailer::Base
  default :from => 'any_from_address@example.com'

  # send a signup email to the user, pass in the user object that   contains the user's email address
  def send_signup_email(user)
    @user = user
    mail( :to => @user.email,
    :subject => 'Thanks for signing up for our amazing app' )
  end
end

Now we need a view that corresponds to our action and outputs HTML for our email. Create a file app/views/User_notifier/send_signup_email.html.erb as follows:

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Thanks for signing up, <%= @user.name %>!</h1>
    <p>Thanks for joining and have a great day! Now sign in and do
awesome things!</p>
  </body>
</html>

If you don’t have a user model quite yet, generate one quickly.

$ rails generate scaffold user name email login
$ rake db:migrate

Now in the controller for the user model app/controllers/users_controller.rb, add a call to UserNotifier.sendsignupemail when a user is saved.

class UsersController < ApplicationController
  def create
    # Create the user from params
    @user = User.new(params[:user])
    if @user.save
      # Deliver the signup email
      UserNotifier.send_signup_email(@user).deliver
      redirect_to(@user, :notice => 'User created')
    else
      render :action => 'new'
    end
  end
end

Alright, now we’re cooking! Let’s get it all going through Mail250.

In config/environment.rb specify your ActionMailer settings to point to Mail250’s servers.

ActionMailer::Base.smtp_settings = {
  :user_name => 'mail250_username',
  :password => 'mail250_password',
  :domain => 'yourdomain.com',
  :address => 'smtp.swipemail.in',
  :port => 2525,
  :authentication => :plain,
  :enable_starttls_auto => false
}

That’s it! When a new user object is saved, an email will be sent to the user via Mail250.

Latest posts by Mail250 (see all)
    Menu
    During this difficult period, keep people safe and informed. We are enabling up to 30% of additional discount for all users. Show Offer Code
    Lighting Deal - Up to 30% OFF | Making Email Marketing Affordable!!! GET OFFER CODE!