【问题标题】:How can I call my rails mailer functionality from a different app?如何从不同的应用程序调用我的 Rails 邮件功能?
【发布时间】:2016-07-07 19:15:39
【问题描述】:

我最近创建了一个 Rails 应用程序,以便我可以使用 ActionMailer 和 Gmail 发送电子邮件,通过 SMTP。创建新用户时,该应用程序将向该用户发送一封电子邮件。一切都很成功。

现在我想知道如何将这个“Mailer App”用作网络服务? 我将如何从不同的应用程序调用我的邮件应用程序,从而消除在其他应用程序中设置所有 ActionMailer 代码但传递电子邮件的需要。

另一个应用程序可以像使用姓名和电子邮件注册一个新用户一样简单,就像我在 Mailer 应用程序中所做的那样。

这是我的代码:

users_controller.rb

class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]

# POST /users
# POST /users.json
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

private
  # Use callbacks to share common setup or constraints between actions.
  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.require(:user).permit(:name, :email)
  end
end

config/env/development.rb

Rails.application.configure do
....
config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
 config.action_mailer.smtp_settings = {
 :address              => "smtp.gmail.com",
 :port                 => 587,
 :domain               => 'gmail.com',
 :user_name            => ENV['gmail_username'],
 :password             => ENV['gmail_password'],
 :authentication       => "plain",
 :enable_starttls_auto => true
}

# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end

sample_email.html.erb

<!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>

example.mailer.rb

class ExampleMailer < ApplicationMailer
default from: "t@@@@@@@gmail.com"

def sample_email(user)
   @user = user
   mail(to: @user.email, subject: 'Sample Email')
end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 actionmailer


    【解决方案1】:

    您可能正在构想微服务架构。这方面有很多资源,一个例子是this blog post。

    简而言之,当您将功能组件移动到隔离块时,您必须为它们提供相互通信的方法。实现这一点的方法有很多种,最流行的是 HTTP API 或使用专用消息代理。

    【讨论】:

    • 感谢您的链接。我认为对于我正在努力学习和完成的事情来说,这可能有点矫枉过正。我正在寻找如何使用 HTTParty 之类的东西来调用 Mailer 应用程序并使用新应用程序的 @name 和 @email 变量发送电子邮件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多