Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed images in email

I need to embed an image in e-mail. How do I do it?

I do not want to use third party tool, nor am I interested in language specific answer (but it is PHP, in case you are wondering).

I am merely interested in format of resulting e-mail body.

like image 375
Josef Sábl Avatar asked Nov 30 '10 10:11

Josef Sábl


2 Answers

As you are aware, everything passed as email message has to be textualized.

  • You must create an email with a multipart/mime message.
  • If you're adding a physical image, the image must be base 64 encoded and assigned a Content-ID (cid). If it's an URL, then the <img /> tag is sufficient (the url of the image must be linked to a Source ID).

A Typical email example will look like this:

From: foo1atbar.net To: foo2atbar.net Subject: A simple example Mime-Version: 1.0 Content-Type: multipart/related; boundary="boundary-example"; type="text/html"  --boundary-example Content-Type: text/html; charset="US-ASCII"  ... text of the HTML document, which might contain a URI referencing a resource in another body part, for example through a statement such as: <IMG SRC="cid:foo4atfoo1atbar.net" ALT="IETF logo">  --boundary-example Content-Location: CID:somethingatelse ; this header is disregarded Content-ID: <foo4atfoo1atbar.net> Content-Type: IMAGE/GIF Content-Transfer-Encoding: BASE64  R0lGODlhGAGgAPEAAP/////ZRaCgoAAAACH+PUNv cHlyaWdodCAoQykgMTk5LiBVbmF1dGhvcml6ZWQgZHV wbGljYXRpb24gcHJvaGliaXRlZC4A etc...  --boundary-example-- 

As you can see, the Content-ID: <foo4atfoo1atbar.net> ID is matched to the <IMG> at SRC="cid:foo4atfoo1atbar.net". That way, the client browser will render your image as a content and not as an attachement.

Hope this helps.

like image 108
Buhake Sindi Avatar answered Sep 27 '22 21:09

Buhake Sindi


the third way is to base64 encode the image and place it in a data: url

example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACR0lEQVRYha1XvU4bQRD+bF/JjzEnpUDwCPROywPgB4h0PUWkFEkLposUIYyEU4N5AEpewnkDCiQcjBQpWLiLjk3DrnZnZ3buTv4ae25mZ+Z2Zr7daxljDGpg++Mv978Y5Nhc6+Di5tk9u7/bR3cjY9eOJnMUh3mg5y0roBjk+PF1F+1WCwCCJKTgpz9/ozjMg+ftVQQ/PtrB508f1OAcau8ADW5xfLRTOzgAZMPxTNy+YpDj6vaPGtxPgvpL7QwAtKXts8GqBveT8P1p5YF5x8nlo+n1p6bXn5ov3x9M+fZmjDGRXBXWH5X/Lv4FdqCLaLAmwX1/VKYJtIwJeYDO+dm3PSePJnO8vJbJhqN62hOUJ8QpoD1Au5kmIentr9TobAK04RyJEOazzjV9KokogVRwjvm6652kniYRJUBrTkft5bUEAGyuddzz7noHALBYls5O09skaE+4HdAYruobUz1FVI6qcy7xRFW95A915pzjiTp6zj7za6fB1lay1/Ssfa8/jRiLw/n1k9tizl7TS/aZ3xDakdqUByR/gDcF0qJV8QAXHACy+7v9wGA4ngWLVskDo8kcg4Ot8FpGa8PV0I7MyeWjq53f7Zrer3nyOLYJpJJowgN+g9IExNNQ4vLFskwyJtVrd8JoB7g3b4rz66dIpv7UHqg611xw/0om8QT7XXBx84zheCbKGui2U9n3p/YAlSVyqRqc+kt+mCyWJTSeoMGjOQciOQDXA6kjVTsL6JhpYHtA+wihPaGOWgLqnVACPQua4j8NK7bPLP4+qQAAAABJRU5ErkJggg==" width="32" height="32"> 
like image 38
Dan D. Avatar answered Sep 27 '22 22:09

Dan D.