Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get full URL to an image in a Rails asynchronous mailer?

Tags:

I want to have emails I send out with ActionMailer contain images that link back to my app. In my development environment, for example:

<img src="http://myfullappurl.dev/assets/myimage.png"> 

I have this in my development.rb

config.action_controller.asset_host = 'myfullappurl.dev' config.action_mailer.asset_host = config.action_controller.asset_host config.action_mailer.default_url_options = { host: 'myfullappurl.dev', only_path: false } 

But I can not get my mail templates to render a full URL in any of these way:

asset_path('myimage.png') asset_path('myimage.png', only_path: false) image_url('myimage.png') 

A lot of similar questions on this topic are answered by doing something like this:

"#{request.protocol}#{request.host_with_port}#{asset_path('image.png')}" 

But because my mails are sent asynchronously with Sidekiq, there is no request object like there would be if they were sent synchronously in a controller.

Is there an obvious thing I am missing, or do I have to fight against Rails to do this? I am using Rails 4, but I am sure that anything that works in 3.1/3.2 should do just fine.

like image 967
Chris Aitchison Avatar asked Mar 19 '13 02:03

Chris Aitchison


2 Answers

Well this is odd behaviour, but I've resolved this issue. It turns out that unless the action_mailer.asset_host starts with http:// then it will be ignored. There is a Regex in actionpack/lib/action_view/helpers/asset_url_helper.rb that defines a valid ActionMailer URI:

URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//} 

However, if you put a http:// in front of the action_controller.asset_host then you will end up with links to http://http://myfullappurl.dev

So to resolve it I had to add the following to my development.rb

 config.action_controller.asset_host = 'myfullappurl.dev'  config.action_mailer.asset_host = 'http://myfullappurl.dev' 

Just to be clear, this is Rails 4.0.0beta1 with the emails being sent asynchronously with Sidekiq, I am not sure if this affects Rails 3.

like image 58
Chris Aitchison Avatar answered Oct 14 '22 19:10

Chris Aitchison


I believe you need to set these in your config

config.action_controller.asset_host = 'http://localhost:3000' #Or your domain config.action_mailer.asset_host = config.action_controller.asset_host 
like image 22
Josh Wilson Avatar answered Oct 14 '22 20:10

Josh Wilson