Email Functionality:-
In our rails application we want to create email functionality so that rails application will send an email to the user when a new user is created.
Following step will show how to send email through ActionMailer, ActionMailer Preview and third party email provider.
Step-1 :-
In your rails app on terminal start with following command.
$ rails g mailer example_mailer
this will create mailer
folder in our application.
Step-2 :-
Then go for the following path
app/mailers/example_mailer.rb
Add following code
class ExampleMailer < ActionMailer::Base
default from: "from@example.com"
end
It will set a sender’s email address by default
Step-3 :-
Create a sample_email method it will take the parameter and send email to email address of user.
class ExampleMailer < ActionMailer::Base
default from: "from@example.com"
def sample_email(user)
@user = user mail(to: @user.email, subject: 'Sample Email')
end
end
Step-4 :-
Now we will write a mail we want to send to our user and this can be done by adding sample_email.html.erb file in views
so create sample_email.html.erb to app/views/example_mailer/sample_email.html.erb
and write following code.
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Hi <%= @user.name %> </h1>
<p> Sample mail sent using smtp. </p>
</body>
</html>
Step-5:-
We also need create text part for this email.
So create
sample_email.text.erb
in your app/views/example_mailer and add following code:
Hi <%= @user.name %>
Sample mail sent using smtp.
Step-6:-
By default rails tries to send emails via SMTP. We will provide SMTP configuration in environment settings/config/environments/production.rb. Add following code using your any mailtrap address
config.action_mailer.smtp_settings = {
:user_name => ‘<username>,
:password => '<pwd>',
:address => 'smtp.mailtrap.io',
:domain => 'smtp.mailtrap.io',
:port => '2525',
:authentication => :cram_md5
}
Step-7 :-
Now edit the UsersController to trigger the event that will send an email to a user.
We just need to add “ExampleMailer.sample_email(@user).deliver”
line to the create method in app/controllers/users_controller.rb.
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
ExampleMailer.sample_email(@user).deliver
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
After doing all this step restart your server and create any new user. User will receive welcome mail in mail account.