Skip to content

Instantly share code, notes, and snippets.

@ondrejbartas
Created July 18, 2012 15:34
Show Gist options
  • Save ondrejbartas/3136958 to your computer and use it in GitHub Desktop.
Save ondrejbartas/3136958 to your computer and use it in GitHub Desktop.
Send mail with inline image html and text optionally wit Amazon SES
# add to Gemfile
# gem "mail"
#
# or do in terminal
# 'gem install mail'
# send_mail_with_inline_image.rb
require 'mail'
# prepare normal mail with text body
mail = Mail.new do
from "email_from@domain.com"
to "email_to@domain.com"
bcc "email_bcc@domain.com" #optional
subject "email subject"
text_part do
content_type 'text/plain; charset=UTF-8'
body "Testing mail with inline image :-)"
end
end
# prepare new alternative body (html + inline images)
part = Mail::Part.new()
# add image to alternative part
part.attachments['image_file.png'] = { :content => File.read('image_file.png'), :content_type => "image/png" }
# change content type to 'inline'
part.attachments['image_file.png'].content_disposition("inline; name=\"image_file.png\"")
# get cid (uniq identificator of image part)
# you can use <img src="cid:#######" /> to show image
cid = part.attachments['image_file.png'].cid
# build html part
part.html_part do
content_type 'text/html; charset=UTF-8'
# change image src to cid
body "<html><body>Testing mail <img src=\"cid:#{cid}\" /> with inline image :-)</body></html>"
end
# add alternative part to mail
mail.add_part(part)
# set related to alternative part
mail.parts.last.content_type "multipart/related; type=\"text/html\";"
# set multipart/alternative to whole mail
mail.content_type "multipart/alternative; boundary=\"#{mail.boundary}\";charset=UTF-8;"
# using sendmail
mail.delivery_method :sendmail
# using Amazon SES
# you can get credentials:
# http://docs.amazonwebservices.com/ses/latest/DeveloperGuide/SMTP.Credentials.html
#
# mail.delivery_method :smtp, { :address => "email-smtp.us-east-1.amazonaws.com",
# :port => 587,
# :user_name => 'USERNAMEfromAMAZONE',
# :password => 'PASSWORDfromAMAZONE',
# :authentication => 'login',
# :enable_starttls_auto => true
# }
mail.deliver
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment