Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inline images with ruby mail gem

Sorry if I'm missing a good article, but I can't find a good example on how to use inline images using ruby with the mail gem (I'm not using RoR) The best example I could find is here, but I don't understand where the .cid method comes from.

here's an excerpt from the above mentioned post where the .cid method is used.

html_part do
    content_type 'text/html; charset=UTF-8'
    body "<img width=597 height=162 id='Banner0' src='cid:#{pic.cid}'>"
end

I have the mail gem working and it can send images as attachments but I need them to be displayed inside the email, without having the need to open attachments.

like image 534
sylvian Avatar asked Feb 13 '23 17:02

sylvian


2 Answers

The Mail gem is quite well maintained, so it really helps to look into the documentation. Your provided snipped misses an integral part: the definition of pic:

pic = attachments['banner.png']

With this information, you can easily find the documentation on attachments, which will yield this bit:

You can also search for specific attachments:

# By Filename
mail.attachments['filename.jpg']   #=> Mail::Part object or nil

In the documentation to Mail::Part, you will then find the definition of the cid method:

def cid
  add_content_id unless has_content_id?
  uri_escape(unbracket(content_id))
end

(sadly, this method is not documented, but it's easy to infer that "cid" stands for "content id").

Finally, RFC2557 defines the usage of CID URIs to identify and reference encapsulated documents (such as images) within emails. This is where

body "<img ... src='cid:...'>"

comes from.

like image 86
DMKE Avatar answered Feb 15 '23 06:02

DMKE


You can also call url:

> mail.attachments[0].url
=> "cid:5eac50cfe27e2_373f3fed9e82e044326c3@Samuels-MacBook-Pro.local.mail"

> mail.attachments[0].cid
=> "5eac50cfe27e2_373f3fed9e82e044326c3@Samuels-MacBook-Pro.local.mail"
like image 35
Sam Stickland Avatar answered Feb 15 '23 08:02

Sam Stickland