Hello brotherhood/sisterhood(except the women that love me...anyone!?)!
Let us send mails to the users of our application.
Again it is EZ!
rails g mailer <your_model_name>
See, EZ.
Let's use the example provided in Rails Guides: ActionMailer
For User model:
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
end
This will also generate two email templates on your views folder.
# app/views/user_mailer
# ../email.html.erb -> html format
# ../email.text.erb -> text format if html fails to load or otherwise
As from the Rails Guides:
class UserMailer < ApplicationMailer
default from: 'newsletter@mdevroot.com'
def welcome_email
@user = params[:user] # collecting the parameters of the user passed from the controller **eg:** [:id,
:username, :email, :number, ...]
@url = 'http://example.com/login'
mail(to: @user.email, subject: 'Welcome to My Awesome Site')
end
end
You can write your own email templates in app/views/user_mailer:
- welcome_email.html.erb
- welcome_email.text.erb
The name welcome_email refers to the action :welcome_email in your UserMailer. Remeber, Rails' naming convention. Rails' core principle: CONVENTION OVER CONFIGURATION.
Now, let's write code to send email to user each time a new user is created in the UsersController.
# app/controllers/users_controller.rb
class UsersController < ApplicationController
# ...
def create
# ...
if @user.save
UserMailer.with(user: @user).welcome_email.deliver_later
# :deliver_later action comes from Action Job module which we will discuss in the coming articles
end
# ...
end
end
Easy, Right!?
That is it. There is nothing more to send a basic email on sending an email when a user is created in your Rails Application.
Love Rails yet!?
Wait till you learn how to send a live mail from your app using free SMTP-mail providers like sendgrid, AWS-SES, smtp2go, etc ...
Even more easy. Coming up in the next article.
Thank you for checking in. That's it for today!
Please subscribe to the newsletter to get notified on time. Thank you again.
Love,
M.
liked_the_post == true ? comment and share : comment and share