Ruby on Rails has built-in Action Mailer library that can be used to send emails from a Rails application. Here are the steps to set up email sending and receiving in Ruby on Rails:
Sending emails:
-
Configure the email settings in
config/application.rbfile. For example:config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'smtp.gmail.com', port: 587, user_name: '[email protected]', password: 'your_password', authentication: 'plain', enable_starttls_auto: true } - This example configures email delivery using Gmail's SMTP server. Create a mailer class that inherits from ActionMailer::Base:
class ExampleMailer < ActionMailer::Base default from: '[email protected]' def sample_email(user) @user = user @url = 'http://example.com/login' mail(to: @user.email, subject: 'Sample Email') end end
- This example defines a mailer class that contains a sample_email method that sends an email to a user. Create a view for the email in app/views/example_mailer/sample_email.html.erb:
<h1>Sample Email</h1>
<p>Hello <%= @user.name %>,</p>
<p>This is a sample email.</p>
<p><%= link_to 'Login', @url %></p> - Call the mailer method from a controller or another part of the application:
ExampleMailer.sample_email(@user).deliver_now
This example calls the sample_email method of the ExampleMailer class and sends the email to a user.
Receiving emails:
-
Configure the email settings in
config/application.rbfile. For example:config.action_mailbox.receivers = { 'example.com' => { 'user1' => { 'password' => 'secret', 'delivery_options' => { 'folder' => 'inbox' } } } } - This example configures an email receiver that listens for emails sent to [email protected] and delivers them to the inbox folder.
Create a mailbox class that inherits from ActionMailbox::Base:
class ExampleMailbox < ActionMailbox::Base def receive(mail) # Process the email here end end - This example defines a mailbox class that contains a receive method that processes incoming emails.
Create an email processor class that inherits from ActionMailbox::Base:
class ExampleProcessor < ActionMailbox::Base def process # Process the email here end end - This example defines an email processor class that contains a process method that processes the email payload.
Configure the mailbox routing in config/routes.rb file:
Rails.application.routes.draw do post 'rails/action_mailbox/example' => 'action_mailbox/ingresses/exmaple#create' end
- This example configures the mailbox routing to the ExampleMailbox class.
Start the email server to listen for incoming emails:
rails action_mailbox:ingress:exmaple
This example starts the email server to listen for incoming emails and routes them to the ExampleMailbox