Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Images in Email With Rails 3

I'm trying to send out an email with Rails 3 and Action Mailer. The email goes out fine, but I want it to be HTML formatted with some basic styling which includes background images. I understand that the images might get blocked until the user allows them to be shown, but I still think it would be best to link to the images on my web server.

The email template called registration_confirmation.html.erb starts out like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    background: url(/images/mainbg_repeat.jpg) top repeat-x #cfcfcf;
    margin: 0px 0px 0px 0px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #565656;
}

What is the best way to get the url link for the background image to have the full host included so that the background will show up in the email?

like image 253
Kevin Avatar asked Sep 22 '11 20:09

Kevin


1 Answers

Pass your request host as a parameter to the mailer method, and then pass it from the method to the view. So, for example, your mailer method might look like this (example lifted from rails docs and modified here):

class UserMailer < ActionMailer::Base
  default :from => "[email protected]"

  def registration_confirmation(user, host)
    @user = user
    @host = host
    mail(:to => user.email, :subject => "Welcome to My Awesome Site")
  end
end

You would call it like this:

def some_action
    UserMailer.registration_confirmation(@user, request.host).deliver
end

Then in your view, you would just use the @host:

<style type="text/css">
body {
    background: url(http://<%= @host %>/images/mainbg_repeat.jpg) top repeat-x #cfcfcf;
}
</style>

This is all assuming the image server is the same as the server running the request. If the image server is hosted elsewhere, you have to output a constant here. You could put something like this in lib/settings.rb:

module Settings
  IMAGE_HOST = 'superawesome.images.com'
end

Then in your view, you'd just output the constant there, like this:

<style type="text/css">
body {
    background: url(http://<%= Settings::IMAGE_HOST %>/images/mainbg_repeat.jpg) top repeat-x #cfcfcf;
}
</style>
like image 68
Ben Lee Avatar answered Oct 04 '22 15:10

Ben Lee