How to create email using css and images from Rails?

How do you create and send emails from a Rails application containing images and proper formatting? like the ones you get from facebook etc.

+23
css email ruby-on-rails actionmailer
Jan 23 '09 at 10:20
source share
3 answers

Assuming that you know how to send regular text emails from Rails using ActionMailer in order to get working HTML messages, you need to set the content type for your email.

For example, your notifer might look like this:

 class MyMailer < ActionMailer::Base def signup_notification(recipient) recipients recipient.email_address_with_name subject "New account information" from "system@example.com" body :user => recipient content_type "text/html" end end 

Pay attention to the line content_type "text/html" . This tells ActionMailer to send an email with the content type text/html instead of the standard text/plain .

Then you should output your HTML mail. For example, your file of the form app/views/my_mailer/signup_notification.html.erb might look like this:

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css" media="screen"> h3 { color: #f00; } ul { list-style: none; } </style> </head> <body> <h3>Your account signup details are below</h3> <ul> <li>Name: <%= @user.name %></li> <li>Login: <%= @user.login %></li> <li>E-mail: <%= @user.email_address %></li> </ul> </body> </html> 

As you can see, the HTML view may include a <style> to define basic styles. Not all HTML and CSS supported, especially for all email clients, but you definitely need to have an adequate text style management format.

Attaching images is a bit more complicated if you plan on displaying attached emails. If you simply include emails from external sites, you can use the <img /> , as usual, in HTML . However, many email clients will block the display of these images until the user allows them. If you need to display attached images, you might want to pay attention to the Rails Inline Attachments plugin.

For more information on Rails mailing list support, ActionMailer documentation is a great resource.

+31
Jan 23 '09 at 13:38
source share

Read How to create great HTML emails using CSS , this is a good start. All emails must comply with HTML 3.0!

+1
Jan 23 '09 at 11:24
source share

For images, you can simply use the usual image_tag helper after you define ActionMailer::Base.asset_host = 'http://www.your-domain.com'

I use Paperclip to store images, so in my case I can add an image to email using this.

 image_tag result.photo.url(:small) 
+1
Aug 17 '12 at 22:37
source share



All Articles