Created
July 18, 2012 15:34
-
-
Save ondrejbartas/3136958 to your computer and use it in GitHub Desktop.
Send mail with inline image html and text optionally wit Amazon SES
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 protected]" | |
to "[email protected]" | |
bcc "[email protected]" #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