Rails 3 send emails in development to a single address - ruby-on-rails-3

In my Rails 2 apps I always used sanitize email to send all emails in development to my personal account to avoid accidentally sending out emails or to use just for testing.
This doesn't seem to have a Rails 3 version and wondered if there was anything for Rails 3 that does this.

Take a look at How to intercept ActionMailer's messages on rails 3?. You'll only have to add message.to = my#email and the mail will be sent to your email address instead of the original destination.
This is what I ended up doing from the post linked to above:
if Rails.env.development?
class Hook
def self.delivering_email(message)
message.to = "\"#{message.to.first}\" <my#email.com>"
message.cc = nil if !message.cc.nil?
message.bcc = nil if !message.bcc.nil?
end
end
ActionMailer::Base.register_interceptor(Hook)
end

Ryan Bates(Railscasts) has just released a gem for handling dev emails.
Letter_opener
Haven't used it but probably worth a look.

Related

in omnicontacts, request.env['omnicontacts.contacts'] is empty in my callback when inviting hotmail contacts

I have the gem working for gmail. I can see the list of contacts in
#contacts = request.env['omnicontacts.contacts']
However, when importing via hotmail, the list is empty. I made sure that I do have hotmail contacts. I double checked every settings in my live application (secret key, domain...)
Has anyone had a similar issue ? What can I try to diagnose further ?
My callback controller:
class Oauth::HotmailController < ApplicationController
def callback_token
#this is called.
#This is empty. When using gmail, contacts are retrieved. But not with hotmail
#contacts = request.env['omnicontacts.contacts']
end
end
In your response from hotmail you have encoded emails.
For example: "email_hashes":["243c01e30cfdbc8c46b8dddb68a685bb8f86016096fd3398919ed6845fde6b7b"]
This patch should help:
https://gist.github.com/clouw/5871254

rails actionmailer multiple recepients

In my Rails app I want to use ActionMailer to send emails to multiple recipients. Below is the code I've written that works with a single attribute:
def new_call(medic, call)
#call = call
#medic = medic
mail to: #medic.medic_email, subject: "New Call: #{#call.incident_number}"
end
I want to include #medic.medic_sms to send the message to their phones. I tried the following code but it doesn't work.
def new_call(medic, call)
#call = call
#medic = medic
mail to: #medic.medic_email, #medic.medic_sms, subject: "New Call: #{#call.incident_number}"
end
Can someone suggest how to add the second attribute cleanly so it works?
Thanks in advance.
Putting the two attributes into an array solved the problem.
[#medic.medic_email, #medic.medic_sms]
You have a syntax error. If you want to pass an array to to:, you need to explicitly wrap it in []:
mail to: [#medic.medic_email, #medic.medic_sms], subject: ...
See ActionMailer Basics section 2.3.4: Sending Email To Multiple Recipients.

Rails 3/Devise - Change Error Message for Password Reset

I am working with a Rails 3 App and am needing to adjust the error message on the password resent view. If a user types in an email address and submits it, currently, the app will display this error message:
Email not found
I am needing to change this error message to this:
We don't have an account with that e-mail address. Maybe you used another address?
I know that you can adjust this in the Devise YML file, but am not sure how to do this... any suggestions?
Working Code
class PasswordsController < Devise::PasswordsController
def create
user = User.find_by_email(params[:user][:email])
if user.nil?
flash.now[:notice] = "We don't have an account with that e-mail address. Maybe you used another address?"
end
super
end
end
You could try using a before_filter that checks if the email exists in the datbase and if not the it redirects you to the password reset form with a flash notice

how to process incoming mails using mailman and update them into the database

am developing ruby on rails3 application where i am sending an email to user and if user replies that email then that reply content, date should be updated to the database. For this i have ProductComment model. when admin sends comment to the user it will be stored in the database. if user replies to that then database should be updated accordingly. I am trying to use mailman. I have installed the gem. But am not getting how to get the comment id, what should i write in replyto address, where to write the mailman code and from which mail i should read.
Am sending email like this:
mail(:to => #user.email, :subject => "Edit Your Product", :reply_to=>"abc#syz.com)
I am handling it in products controller like this:
require 'mailman'
Mailman::Application.run do
to 'abc#xyz.com' do
ProductComment.create(message)
end
end
Please help me to come out from this problem
Please tell me how to use mailman gem in ruby on rails3 application
there is a recent pro-episode on receiving emails with mailman on railscasts: http://railscasts.com/episodes/313-receiving-email-with-mailman
chmod +x script/mailman_server
cat mailman_test.eml | script/mailman_server
script/mailman_server
-
# script/mailman_server
#!/usr/bin/env ruby
require "rubygems"
require "bundler/setup"
require "mailman"
Mailman.config.logger = Logger.new("log/mailman.log")
Mailman.config.pop3 = {
server: 'pop.gmail.com', port: 995, ssl: true,
username: ENV["GMAIL_USERNAME"],
password: ENV["GMAIL_PASSWORD"]
}
Mailman::Application.run do
default do
begin
Ticket.receive_mail(message)
rescue Exception => e
Mailman.logger.error "Exception occurred while receiving message:\n#{message}"
Mailman.logger.error [e, *e.backtrace].join("\n")
end
end
end
-
def self.receive_mail(message)
ticket_id = message.subject[/^Update (\d+)$/, 1]
if ticket_id.present? && Ticket.exists?(ticket_id)
Ticket.update(ticket_id, body: message.body.decoded)
else
Ticket.create subject: message.subject, body: message.body.decoded, from: message.from.first
end
end
Postmark Inbound is a good choice. Setup like so:
Sign up for Postmark, they will give you an email which Postmark will assign to your account.
Sign up for Google Apps branded Gmail for your domain. Set up forwarding from an account to the Postmark email address. People can now email reply#yourdamin.com, and it will be forwarded to Postmark.
Create a callback URL. When Postmark receives an email it will package it up and post it to your callback. You can then access the email attributes via the params hash.
To implement replying to messages, simply add a reply to field to your outgoing message which contains a unique hash for the message, e.g.
reply+uniquehash#yourdomain.com.
This is a legal email address, and will be sent to reply#yourdomain.com. You can then parse out the hash in your callback and use it to match the reply to the original message.
Simple :)

How to test with RSpec if an email is delivered

I'd like to test if an email is delivered if I call a controller method with :post. I'll use email_spec so I tried this snipped here: http://rubydoc.info/gems/email_spec/1.2.1/file/README.rdoc#Testing_In_Isolation
But it doesn't work, because I pass an instance of the model-object to the delivery-method and the instance is saved before the delivery.
I tried to create an other instance of the model-object, but then the id isn't the same.
My controller-method looks like this:
def create
#params = params[:reservation]
#reservation = Reservation.new(#params)
if #reservation.save
ReservationMailer.confirm_email(#reservation).deliver
redirect_to success_path
else
#title = "Reservation"
render 'new'
end
end
Do you have any idea to solve this?
Assuming your test environment is set up in the usual fashion (that is, you have config.action_mailer.delivery_method = :test), then delivered emails are inserted into the global array ActionMailer::Base.deliveries as Mail::Message instances. You can read that from your test case and ensure the email is as expected. See here.
Configure your test environment to accumulate sent mails in ActionMailer::Base.deliveries.
# config/environments/test.rb
config.action_mailer.delivery_method = :test
Then something like this should allow you to test that the mail was sent.
# Sample parameters you would expect for POST #create.
def reservation_params
{ "reservation" => "Drinks for two at 8pm" }
end
describe MyController do
describe "#create" do
context "when a reservation is saved" do
it "sends a confirmation email" do
expect { post :create, reservation_params }.to change { ActionMailer::Base.deliveries.count }.by(1)
end
end
end
end
Note that my example uses RSpec 3 syntax.
I know I'm late to the party with this one, but for future Googlers...
I think a better solution to this problem is answered here
The previously accepted answer is testing the Mailer itself (inside the controller spec). All you should be testing for here is that the Mailer gets told to deliver something with the right parameters.
You can then test the Mailer elsewhere to make sure it responds to those parameters correctly.
ReservationMailer.should_receive(:confirm_email).with(an_instance_of(Reservation))
This is way how to test that Mailer is called with right arguments. You can use this code in feature, controller or mailer spec:
delivery = double
expect(delivery).to receive(:deliver_now).with(no_args)
expect(ReservationMailer).to receive(:confirm_email)
.with('reservation')
.and_return(delivery)
Anyone using rspec +3.4 and ActiveJob to send async emails, try with:
expect {
post :create, params
}.to have_enqueued_job.on_queue('mailers')
To add a little more, make sure if you're going to stub out a call using should_receive that you have an integration test elsewhere testing that you're actually calling the method correctly.
I've been bit a few times by changing a method that was tested elsewhere with should_receive and having tests still pass when the method call was broken.
If you prefer to test the outcome rather than using should_receive, shoulda has a nice matcher that works like the following:
it { should have_sent_email.with_subject(/is spam$/) }
Shoulda documentation
More information on using Shoulda Matchers with rSpec
If you're using Capybara with Capybara Email and you sent an email to test#example.com, you can also use this method:
email = open_email('test#example.com')
And then you can test it like this:
expect(email.subject).to eq('SUBJECT')
expect(email.to).to eq(['test#example.com'])
Try email-spec
describe "POST /signup (#signup)" do
it "should deliver the signup email" do
# expect
expect(UserMailer).to(receive(:deliver_signup).with("email#example.com", "Jimmy Bean"))
# when
post :signup, "Email" => "email#example.com", "Name" => "Jimmy Bean"
end
end
more examples here: https://github.com/email-spec/email-spec#testing-in-isolation