development

Rails에서 이메일을 미리 보려면 어떻게해야합니까?

big-blog 2020. 7. 27. 07:16
반응형

Rails에서 이메일을 미리 보려면 어떻게해야합니까?


이것은 바보 같은 질문 일 수 있지만 Rails에서 HTML 전자 메일을 만들 때 브라우저에서 템플릿을 미리 볼 수있는 특히 쉬운 내장 방법이 있습니까? 아니면 가져 오는 일종의 사용자 정의 컨트롤러를 작성해야합니까 그 관점에서?


Action Mailer는 이제 Rails 4.1 에서 이메일미리 보는 방법을 내장했습니다 . 예를 들어 다음을 확인하십시오.

# located in test/mailers/previews/notifier_mailer_preview.rb

class NotifierPreview < ActionMailer::Preview
  # Accessible from http://localhost:3000/rails/mailers/notifier/welcome
  def welcome
    Notifier.welcome(User.first)
  end
end

Daniel의 대답 은 좋은 시작이지만 전자 메일 템플릿에 동적 데이터가 포함되어 있으면 작동하지 않습니다. 예를 들어, 이메일이 주문 영수증이고 그 안에서 인쇄한다고 가정합니다 @order.total_price. 이전 방법을 사용하면 @order변수가 0이됩니다.

여기 내가 사용하는 약간의 요리법이 있습니다.

먼저,이 이메일 미리보기 기능은 내부 용으로 만 사용되므로 관리 네임 스페이스에 몇 가지 일반적인 경로를 설정했습니다.

#routes.rb

MySite::Application.routes.draw do
  namespace :admin do
    match 'mailer(/:action(/:id(.:format)))' => 'mailer#:action'
  end
end

다음으로 컨트롤러를 만듭니다. 이 컨트롤러에서는 전자 메일 템플릿 당 하나의 방법을 만듭니다. 대부분의 이메일에는 동적 데이터가 포함되어 있으므로 템플릿에 필요한 멤버 변수를 채워야합니다.

이것은 조명기를 사용하여 수행 할 수 있지만 일반적으로 의사 랜덤 실제 데이터를 가져 오는 것을 선호합니다. 기억하십시오-이것은 단위 테스트가 아닙니다-이것은 순전히 개발 지원입니다. 매번 같은 결과를 낼 필요는 없습니다. 사실 그렇지 않으면 더 좋습니다.

#app/controllers/admin/mailer_controller.rb
class Admin::MailerController < Admin::ApplicationController

  def preview_welcome()
    @user = User.last
    render :file => 'mailer/welcome.html.erb', :layout => 'mailer'
  end

end

템플릿을 렌더링 할 때는을 사용 layout=>:mailer합니다. 이렇게하면 이메일 본문이 일반적인 웹 애플리케이션 레이아웃 대신 (예 :) HTML 이메일 레이아웃에 포함 application.html.erb됩니다.

그리고 그것은 거의 다입니다. 이제 http://example.com/admin/mailer/preview_welcome방문 하여 환영 이메일 템플릿의 변경 사항을 미리 볼 수 있습니다 .


37Signals에는 mail_view 라는 자체 메일 테스트 gem도 있습니다 . 꽤 환상적입니다.


내가 본 가장 쉬운 설정은 MailCatcher 입니다. 설치하는 데 2 ​​분이 걸렸으며 새 메일러가 즉시 사용할 수 있습니다.


email_preview를 사용 합니다 . 시도 해봐.


최근에는 Maily 라는 gem을 작성 하여 브라우저를 통해 응용 프로그램 전자 메일을 미리보고 편집 (템플릿 파일)하고 전달했습니다. 또한 데이터, 유연한 인증 시스템 및 미니멀리즘 UI를 연결하는 친숙한 방법을 제공합니다.

가까운 시일 내에 다음과 같은 새로운 기능을 추가 할 계획입니다.

  • 이메일 당 여러 후크
  • Parametrize emails via UI (arguments of mailer method)
  • Play with translations keys (list, highlight, ...)

I hope it can help you.


You can use Rails Email Preview

rails-email-preview screenshot

REP is a rails engine to preview and test send emails, with I18n support, easy premailer integration, and optional CMS editing with comfortable_mexican_sofa.


Rails Email Preview helps us to quickly view the email in web browser in development mode.

1) Add “gem ‘rails_email_preview’, ‘~> 0.2.29’ “ to gem file and bundle install.

2) Run “rails g rails_email_preview:install” this creates initializer in config folder and add routes.

3) Run “rails g rails_email_preview:update_previews” this crates mailer_previews folder in app directory.

Generator will add a stub to each of your emails, then u populate the stub with mock data.

Ex:

class UserMailerPreview
def invitation
UserMailer.invitation mock_user(‘Alice’), mock_user(‘Bob’)
end
def welcome
UserMailer.welcome mock_user
end
private
def mock_user(name = ‘Bill Gates’)
fake_id User.new(name: name, email: “user#{rand 100}@test.com”)
end
def fake_id(obj)
obj.define_singleton_method(:id) { 123 + rand(100) }
obj
end
end

4) Parameters in search query will be available as an instance variable to preview class. Ex: if we have a URL like “/emails/user_mailer_preview-welcome?user_id=1” @user_id is defined in welcome method of UserMailerPreview it helps us to send mail to specific user.

class UserMailerPreview
def welcome
user = @user_id ? User.find(@user_id) : mock_user
UserMailer.welcome(user)
end
end

5) To access REP url’s like this

rails_email_preview.rep_root_url
rails_email_preview.rep_emails_url
rails_email_preview.rep_email_url(‘user_mailer-welcome’)

6) We can send emails via REP, this will use environment mailer settings. Uncomment this line in the initializer to disable sending mail in test environment.

config.enable_send_email = false

Source : RailsCarma Blog : Previewing Emails in Rails Applications With the Mail_View Gem


I'm surprised no one's mentioned letter_opener. It's a gem that will render and open emails as a browser page whenever an email is delivered in dev.


rails generates a mail preview if you use rails g mailer CustomMailer. You will get a file CustomMailerPreview inside spec/mailers/previews folder.

Here you can write your method that will call the mailer and it'll generate a preview.

For ex -

class CustomMailerPreview < ActionMailer::Preview
  def contact_us_mail_preview
    CustomMailer.my_mail(user: User.first)
  end
end

Preview all emails at http://localhost:3000/rails/mailers/custom_mailer


There is no way to preview it directly out of the Mailer. But as you wrote, you can write a controller, which looks something like this.

class EmailPreviewsControllers < ActionController::Base
  def show
    render "#{params[:mailer]}_mailer/#{params[:method]}"
  end
end

But I think, that's not the best way to test emails, if they look correctly.


I prefer mails_viewer gem. This gem is quite useful as it save the HTML template into tmp folder.

참고URL : https://stackoverflow.com/questions/7165064/how-do-i-preview-emails-in-rails

반응형