Action mailer gmail
To set up an Action Mailer to send emails using Gmail, you'll need to follow these steps:
Step 1: Set up your Gmail account
- Create a new Gmail account or use an existing one.
- Enable "Less secure app access" in your Google Account settings. This is required for Action Mailer to work with Gmail.
Step 2: Create an Action Mailer
- In your Rails application, create a new file called
application_mailer.rb
in theapp/mailers
directory. - Add the following code to the file:
class ApplicationMailer < ActionMailer::Base default from: '[email protected]' default to: '[email protected]' default subject: 'Your Subject' end
Replace
[email protected]
with your Gmail address,[email protected]
with the recipient's email address, andYour Subject
with the subject of the email.
Step 3: Configure Action Mailer to use Gmail
- In your
config/environments/production.rb
file, add the following code:config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'smtp.gmail.com', port: 587, domain: 'smtp.gmail.com', user_name: '[email protected]', password: 'your_password', authentication: 'plain', enable_starttls_auto: true }
Replace
[email protected]
with your Gmail address andyour_password
with your Gmail password.
Step 4: Send an email using Action Mailer
- Create a new file called
user_mailer.rb
in theapp/mailers
directory. - Add the following code to the file:
class UserMailer < ApplicationMailer def welcome_email(user) @user = user mail to: user.email, subject: 'Welcome to our application!' end end
This code defines a
welcome_email
method that sends an email to the user with a welcome message.
Step 5: Test your Action Mailer
- Run the following command in your terminal:
rails c
This will open a Rails console.
- Run the following code to send an email:
UserMailer.welcome_email(User.first).deliver_now
This will send an email to the first user in your database.
That's it! You should now have an Action Mailer set up to send emails using Gmail.