I have a rails code that sends emails. Following is in my controller:
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
I have the following in my Model
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
This all works fine. My Question is:
For example if there is an error in sending mail to one of the pople, even then my flash message will say. Mail was sent to X people
What can I do to ensure that @index gets incremented ONLY when mail is successfully sent?
The
deliver_notificationmethod should always return aTMailobject regardless of success or failure. There is araise_delivery_errorssetting which will allow the mailer to raise exceptions if there’s trouble, but you’ll have to rescue these in your block and only increment on success.Due to the way mail is delivered by ActionMailer, it’s often the case you won’t know if the message is successful or not. Email is usually queued and delivered at a point in time well beyond your method call, and most errors occur at this point due to any number of difficulties in delivery. It’s only wildly malformed email addresses that will be rejected up front, or if the mail delivery mechanism is non-functional.
Edit: Added Exception Tracking
Your example used
index++which is not supported by Ruby. What you probably want isindex += 1. You were also using the@usersarray directly instead of the individual elements.