1

メールを送信するレールコードがあります。以下は私のコントローラーにあります:

def create
    @users = Users.find(:all)
    @sub = params[:sub]
    @body = params[:body]
    @index = 0
    @users.each {|i| index++; Notifier.deliver_notification(@users.email_address, @sub, @body, @users.unsubscribe_link);}
    flash[:notice] = "Mail was sent to " + @index + " people"   
end

私のモデルには次のものがあります

class Notifier < ActionMailer::Base
   def notification(email, sub, content, link)
     recipients email 
     from       "my_email@example.com"
     subject    sub
     body       :content => recipient, :link => link
   end
end

これはすべてうまくいきます。私の質問は:

たとえば、ポプルの 1 つにメールを送信する際にエラーが発生した場合でも、私のフラッシュ メッセージには次のように表示されます。Mail was sent to X people

@indexメールが正常に送信された場合にのみ増加するようにするにはどうすればよいですか?

4

2 に答える 2

1

メソッドは、成功または失敗に関係なく、deliver_notification常にオブジェクトを返す必要があります。問題が発生した場合にメーラーが例外を発生させることを許可する設定がTMailありますが、これらをブロックでレスキューし、成功した場合にのみインクリメントする必要があります。raise_delivery_errors

ActionMailer によるメールの配信方法が原因で、メッセージが成功したかどうかわからないことがよくあります。通常、電子メールはキューに入れられ、メソッド呼び出しをはるかに超えた時点で配信されます。ほとんどのエラーは、配信でのさまざまな問題により、この時点で発生します。事前に拒否される、またはメール配信メカニズムが機能していない場合は、非常に不正な形式の電子メール アドレスのみが拒否されます。

編集:例外追跡を追加

count = 0
@users.each do |user|
  begin
    Notifier.deliver_notification(
      user.email_address,
      @sub,
      @body,
      user.unsubscribe_link
    )

    count += 1
  rescue => e
    # Something went wrong, should probably store these and examine them, or
    # at the very least use Rails.logger
  end
end

flash[:notice] = "Mail was sent to #{count} people"

index++Rubyでサポートされていない使用例。おそらく欲しいのはindex += 1. @usersまた、個々の要素の代わりに配列を直接使用していました。

于 2010-08-06T18:01:32.193 に答える
1

ActionMailer に例外をスローするように依頼し、例外にならなかった配信のみをカウントすることができます。

ActionMailer::Base.raise_delivery_errors = true
@users.each do |i| 
  begin
    Notifier.deliver_notification(@users.email_address, @sub, @body, @users.unsubscribe_link)
    index++
  rescue Exception => e
    # Do whatever you want with the failed deliveries here
  end
end
于 2010-08-06T18:02:35.377 に答える