{"id":209,"date":"2017-11-10T11:25:51","date_gmt":"2017-11-10T10:25:51","guid":{"rendered":"http:\/\/www.em-company.fr\/blog\/?p=209"},"modified":"2017-11-10T11:27:00","modified_gmt":"2017-11-10T10:27:00","slug":"creating-multipart-email-php","status":"publish","type":"post","link":"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/","title":{"rendered":"Creating multipart email in PHP"},"content":{"rendered":"<p>Sending a simple and short email in PHP is an easy task. The following lines do just that ( <a href=\"http:\/\/php.net\/manual\/en\/function.mail.php\">http:\/\/php.net\/manual\/en\/function.mail.php )<\/a><\/p>\n<div class=\"example-contents\">\n<div class=\"phpcode\">\n<pre>\/\/\u00a0The\u00a0message\r\n$message\u00a0=\u00a0\"Line\u00a01\\r\\nLine\u00a02\\r\\nLine\u00a03\";\r\n\r\n\/\/\u00a0In\u00a0case\u00a0any\u00a0of\u00a0our\u00a0lines\u00a0are\u00a0larger\u00a0than\u00a070\u00a0characters,\u00a0we\u00a0should\u00a0use\u00a0wordwrap()\r\n$message\u00a0=\u00a0wordwrap($message,\u00a070,\u00a0\"\\r\\n\");\r\n\r\n\/\/\u00a0Send\r\nmail('caffeinated@example.com',\u00a0'My\u00a0Subject',\u00a0$message);\r\n<\/pre>\n<\/div>\n<\/div>\n<p>However, sending a more involved email, including attachment and several MIME parts require some more code. Fortunately, this is not very complicated. <!--more-->But, as the email RFC relies on very specific text layout of the message body, you can very easily screw up your entire email. Sometimes nothing at all will be sent. This always results in very poor User experience, and in the case of an advertising email, this has to be avoided.<\/p>\n<p>The following code will send a Multipart MIME email which includes one attachment. It contains one HTML section and one TXT section, so that the message will be correctly displayed whatever the remote part client settings are.<\/p>\n<p>First some global variables definition. This is a mixture of french and english naming, but this should not be an obstacle \ud83d\ude09<\/p>\n<pre>global $destinataire;\r\nglobal $email_expediteur; \r\nglobal $email_reply; \r\nglobal $sujet; \r\nglobal $name; \r\nglobal $locale;<\/pre>\n<p>Then we generate the crucially important frontier pattern. This is used to separate the various message parts &#8230; and should have a very low priority of being found in the message text or attachment.<\/p>\n<pre> $frontiere = '-----=' . md5(uniqid(mt_rand()));<\/pre>\n<p>Note the bizarre formatting of this pattern. Strictly speaking, we just need to make sure this pattern cannot be found in the message body. So, hyphens and other signs are commonly used, combined with whatever you might think of (still part of ASCII character set). Here we use a combination of random number, MD5 hash and some uniqueness pattern.<\/p>\n<p>Then we compose the email header:<\/p>\n<pre> $headers = \"From: \".$name.' &lt;'.$email_expediteur.'&gt;'.\"\\n\";\r\n $headers .= 'Return-Path: &lt;'.$email_reply.'&gt;'.\"\\n\";\r\n $headers .= 'MIME-Version: 1.0'.\"\\n\";\r\n $headers .= 'Content-Type: multipart\/mixed;boundary=\"'.$frontiere.'\"';<\/pre>\n<p>Again, the formatting is strict and upper\/lowercase should be followed. White spaces and new lines as well. The message header ends by the &#8220;frontiere&#8221; pattern defined above.<\/p>\n<p>Now we create the message body itself.<\/p>\n<h6><span style=\"text-decoration: underline;\"><strong>Regular text part<\/strong><\/span><\/h6>\n<pre> $message = '--'.$frontiere.\"\\n\";\r\n $message .= 'Content-Type: text\/plain; charset=\"iso-8859-1\"'.\"\\n\";\r\n $message .= 'Content-Transfer-Encoding: 8bit'.\"\\n\\n\";\r\n $message .= $message_texte.\"\\n\\n\";<\/pre>\n<p>See the first line ? This is using our &#8220;frontiere&#8221; and adds two hyphens at the beginning, as stated in the <a href=\"https:\/\/tools.ietf.org\/html\/rfc2046#section-5.1.1\">RFC2046, paragraph 5.1.1 <\/a>. We specify the Content Type, so text\/plain for our regular text part, then the character set. This is important for using (and let the recipient display correctly) accented characters. A very nice a pragmatic article on character sets can be found <a href=\"https:\/\/www.joelonsoftware.com\/2003\/10\/08\/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses\/\">here<\/a> .<\/p>\n<p>Now following the same principle, we can add the other message parts<\/p>\n<h6><span style=\"text-decoration: underline;\"><strong>HTML part<\/strong><\/span><\/h6>\n<pre>$message = '--'.$frontiere.\"\\n\"; \r\n$message .= 'Content-Type: text\/html; charset=\"iso-8859-1\"'.\"\\n\";\r\n$message .= 'Content-Transfer-Encoding: 8bit'.\"\\n\\n\";\r\n$message .= $message_html.\"\\n\\n\";<\/pre>\n<p>Basically, only the <em>Content-Type <\/em>has changed, to reflect the fact this is HTML.<\/p>\n<h6><span style=\"text-decoration: underline;\"><strong>Attachment part:<\/strong><\/span><\/h6>\n<p>in this case, we add a previously generated pdf file which is converted to base64, and split in chunk of 76 bytes, as per <a href=\"https:\/\/tools.ietf.org\/html\/rfc2045#section-6.8\">RFC2045 par. 6.8<\/a> .<\/p>\n<pre>$attached_file = file_get_contents($file2send);\r\n$attached_file = chunk_split(base64_encode($attached_file));\r\n$picname = basename($file2send);\r\n \r\n$attached = \"\\n\\n\". \"--\" .$frontiere . \"\\nContent-Type: application\/pdf; name=\\\"$picname\\\"\\r\\nContent-Transfer-Encoding: base64\\r\\nContent-Disposition: attachment;\"\r\n\r\n$attached .= \" filename=\\\". $picname\\\"\\r\\n\\n\";\r\n$attached .= $attached_file . \"--\" . $frontiere . \"--\";<\/pre>\n<p>Then we compose the message and send it<\/p>\n<pre>\/\/ $destinataire (recipent) and $sujet (subject) were defined before\r\n $message .= $attached;\r\n \r\n if(mail($destinataire,$sujet,$message,$headers)) {\r\n      return true;\r\n else\r\n      return false;\r\n<\/pre>\n<p>As the email message formatting is very strict, all this code should be bundled together into a function and utilized wherever needed.<\/p>\n<p>For further and detailed reference, one can also look at the <a href=\"https:\/\/tools.ietf.org\/html\/rfc2046\">RFC2046<\/a> which details all the various fields and elements found in a Multipart Email, but the reading is less pleasant \ud83d\ude09<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sending a simple and short email in PHP is an easy task. The following lines do just that ( http:\/\/php.net\/manual\/en\/function.mail.php ) \/\/\u00a0The\u00a0message $message\u00a0=\u00a0&#8220;Line\u00a01\\r\\nLine\u00a02\\r\\nLine\u00a03&#8221;; \/\/\u00a0In\u00a0case\u00a0any\u00a0of\u00a0our\u00a0lines\u00a0are\u00a0larger\u00a0than\u00a070\u00a0characters,\u00a0we\u00a0should\u00a0use\u00a0wordwrap() $message\u00a0=\u00a0wordwrap($message,\u00a070,\u00a0&#8220;\\r\\n&#8221;); \/\/\u00a0Send mail(&#8216;caffeinated@example.com&#8217;,\u00a0&#8216;My\u00a0Subject&#8217;,\u00a0$message); However, sending a more involved email, including attachment and several MIME parts require some more code. Fortunately, this is not very complicated.<\/p>\n","protected":false},"author":4,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[14],"tags":[35,36,34],"class_list":["post-209","post","type-post","status-publish","format-standard","hentry","category-programming","tag-email","tag-mime","tag-php"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Creating multipart email in PHP - Embedded<\/title>\n<meta name=\"description\" content=\"detailed explanations on how to send multipart email in php including several MIME parts and one file attachment base64 encoded\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Creating multipart email in PHP - Embedded\" \/>\n<meta property=\"og:description\" content=\"detailed explanations on how to send multipart email in php including several MIME parts and one file attachment base64 encoded\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/\" \/>\n<meta property=\"og:site_name\" content=\"Embedded\" \/>\n<meta property=\"article:published_time\" content=\"2017-11-10T10:25:51+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2017-11-10T10:27:00+00:00\" \/>\n<meta name=\"author\" content=\"kriko\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"kriko\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/index.php\\\/2017\\\/11\\\/10\\\/creating-multipart-email-php\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/index.php\\\/2017\\\/11\\\/10\\\/creating-multipart-email-php\\\/\"},\"author\":{\"name\":\"kriko\",\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/#\\\/schema\\\/person\\\/fcb297f759038f0e8cb969c4c29742df\"},\"headline\":\"Creating multipart email in PHP\",\"datePublished\":\"2017-11-10T10:25:51+00:00\",\"dateModified\":\"2017-11-10T10:27:00+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/index.php\\\/2017\\\/11\\\/10\\\/creating-multipart-email-php\\\/\"},\"wordCount\":479,\"commentCount\":0,\"keywords\":[\"email\",\"MIME\",\"PHP\"],\"articleSection\":[\"programming\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/index.php\\\/2017\\\/11\\\/10\\\/creating-multipart-email-php\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/index.php\\\/2017\\\/11\\\/10\\\/creating-multipart-email-php\\\/\",\"url\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/index.php\\\/2017\\\/11\\\/10\\\/creating-multipart-email-php\\\/\",\"name\":\"Creating multipart email in PHP - Embedded\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/#website\"},\"datePublished\":\"2017-11-10T10:25:51+00:00\",\"dateModified\":\"2017-11-10T10:27:00+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/#\\\/schema\\\/person\\\/fcb297f759038f0e8cb969c4c29742df\"},\"description\":\"detailed explanations on how to send multipart email in php including several MIME parts and one file attachment base64 encoded\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/index.php\\\/2017\\\/11\\\/10\\\/creating-multipart-email-php\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/index.php\\\/2017\\\/11\\\/10\\\/creating-multipart-email-php\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/index.php\\\/2017\\\/11\\\/10\\\/creating-multipart-email-php\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Accueil\",\"item\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Creating multipart email in PHP\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/\",\"name\":\"Embedded\",\"description\":\"(...but not only)\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.em-company.fr\\\/blog\\\/#\\\/schema\\\/person\\\/fcb297f759038f0e8cb969c4c29742df\",\"name\":\"kriko\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Creating multipart email in PHP - Embedded","description":"detailed explanations on how to send multipart email in php including several MIME parts and one file attachment base64 encoded","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/","og_locale":"en_US","og_type":"article","og_title":"Creating multipart email in PHP - Embedded","og_description":"detailed explanations on how to send multipart email in php including several MIME parts and one file attachment base64 encoded","og_url":"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/","og_site_name":"Embedded","article_published_time":"2017-11-10T10:25:51+00:00","article_modified_time":"2017-11-10T10:27:00+00:00","author":"kriko","twitter_card":"summary_large_image","twitter_misc":{"Written by":"kriko","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/#article","isPartOf":{"@id":"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/"},"author":{"name":"kriko","@id":"https:\/\/www.em-company.fr\/blog\/#\/schema\/person\/fcb297f759038f0e8cb969c4c29742df"},"headline":"Creating multipart email in PHP","datePublished":"2017-11-10T10:25:51+00:00","dateModified":"2017-11-10T10:27:00+00:00","mainEntityOfPage":{"@id":"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/"},"wordCount":479,"commentCount":0,"keywords":["email","MIME","PHP"],"articleSection":["programming"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/","url":"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/","name":"Creating multipart email in PHP - Embedded","isPartOf":{"@id":"https:\/\/www.em-company.fr\/blog\/#website"},"datePublished":"2017-11-10T10:25:51+00:00","dateModified":"2017-11-10T10:27:00+00:00","author":{"@id":"https:\/\/www.em-company.fr\/blog\/#\/schema\/person\/fcb297f759038f0e8cb969c4c29742df"},"description":"detailed explanations on how to send multipart email in php including several MIME parts and one file attachment base64 encoded","breadcrumb":{"@id":"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.em-company.fr\/blog\/index.php\/2017\/11\/10\/creating-multipart-email-php\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Accueil","item":"https:\/\/www.em-company.fr\/blog\/"},{"@type":"ListItem","position":2,"name":"Creating multipart email in PHP"}]},{"@type":"WebSite","@id":"https:\/\/www.em-company.fr\/blog\/#website","url":"https:\/\/www.em-company.fr\/blog\/","name":"Embedded","description":"(...but not only)","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.em-company.fr\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.em-company.fr\/blog\/#\/schema\/person\/fcb297f759038f0e8cb969c4c29742df","name":"kriko"}]}},"_links":{"self":[{"href":"https:\/\/www.em-company.fr\/blog\/index.php\/wp-json\/wp\/v2\/posts\/209","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.em-company.fr\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.em-company.fr\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.em-company.fr\/blog\/index.php\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.em-company.fr\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=209"}],"version-history":[{"count":10,"href":"https:\/\/www.em-company.fr\/blog\/index.php\/wp-json\/wp\/v2\/posts\/209\/revisions"}],"predecessor-version":[{"id":237,"href":"https:\/\/www.em-company.fr\/blog\/index.php\/wp-json\/wp\/v2\/posts\/209\/revisions\/237"}],"wp:attachment":[{"href":"https:\/\/www.em-company.fr\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=209"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.em-company.fr\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=209"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.em-company.fr\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=209"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}