11/21/2013

Build WordPress Email Wrapper (With Attachments)

WordPress default email sending function wp_mail is way too basic. It uses "Wordpress" as sender name and doesn't allow you send HTML and plain text mail at the same time. If you are writing a plugin that sends emails this is going to be a problem.

In this quick tutorial I will show you how plugins like BroadFast for Wordpress manage to overwrite the default sender and to send emails with plain text and HTML versions. You simply need a small wrapper function. See the full code first and I will explain it below:

  1. function send($sender$receiver$subject$message$ctype = 'text/html'$attachments = NULL) {  
  2.     $plain_text = strip_tags(str_replace("<br>""\n"$message));  
  3.       
  4.     // handle text-only and "both" mail types  
  5.     if($ctype=='text/plain'$message = $plain_text;  
  6.     else $message=wpautop($message);  
  7.               
  8.     if($ctype=='both') {  
  9.         // thanks to http://www.tek-tips.com/faqs.cfm?fid=2681                    
  10.         $semi_rand = md5(time());  
  11.         $mime_boundary = "==MULTIPART_BOUNDARY_$semi_rand";  
  12.         $mime_boundary_header = chr(34) . $mime_boundary . chr(34);  
  13.           
  14.         // construct the body  
  15.         $body = "This is a multi-part message in MIME format. 
  16.  
  17.         --$mime_boundary 
  18.         Content-Type: text/plain; charset=\"UTF-8\" 
  19.         Content-Transfer-Encoding: 8bit 
  20.          
  21.         $plain_text 
  22.          
  23.         --$mime_boundary 
  24.         Content-Type: text/html; charset=utf8 
  25.         Content-Transfer-Encoding: 8bit 
  26.          
  27.         $message 
  28.          
  29.         --$mime_boundary--";  
  30.           
  31.         $body = str_replace("\t""" ,$body);  
  32.           
  33.         // now replace the vars  
  34.         $message = $body;  
  35.         $ctype = "multipart/alternative;\n" .   
  36.    "     boundary=" . $mime_boundary_header;              
  37.     }  
  38.       
  39.     $headers=array();  
  40.     $headers[] = "Content-Type: $ctype";  
  41.     $headers[] = 'From: '.$sender;  
  42.     $headers[] = 'sendmail_from: '.$sender;  
  43.       
  44.     // prepare attachments if any     
  45.     if($attachments and is_array($attachments)) {  
  46.         $atts = array();  
  47.         foreach($attachments as $attachment$atts[] = $attachment->file_path;  
  48.         $attachments = $atts;  
  49.     }  
  50.        
  51.     $message = do_shortcode($message);        
  52.     $result = wp_mail($receiver$subject$message$headers$attachments);                 
  53.     return $result;  
  54. }  

Now, let's have a look at this code:

Line 1. The function definition: The function accepts sender's email address that can contain just email address or a string like My Name <myemail@dot.com>. This allows you to send emails with different name than "Wordpress" (how exactly this happens is explained later below. Then $receiver is the receiver email address and $subject and $message are obvious parameters.

The parameter $ctype is the email content type - it can be either "text/html", "text/plain" or "both". Using "both" will generate email with two alternative parts so the email client program can choose the best one. Note that "both" doesn't work together with attachments. This is currently unsolvable - so if you want to send attachments, choose text/html or text/plain.

Now, let's go on with the code.

Line 2. Create a plain text version of the message to be used when sending the email as plain text.

Lines 4 - 5 take care to further prepare the message depending on the selected content type.


We have more work to do when sending both HTML and plain text version. It starts after line 8. First we generate the mime boundary by preparing a pseudo random number. Then from line 15 we start constructing the body of the message. First add the intro text, then the boundary, and then the two headers:

Content-Type: text/plain; charset=\"UTF-8\"
Content-Transfer-Encoding: 8bit


before the plain text version (lines 17 - 21) and:

Content-Type: text/html; charset=utf8
Content-Transfer-Encoding: 8bit


Before the HTML version (lines 23 - 27). Then closing the mime boundary.

Please pay attention to all the formatting and new lines, they are very important.

Then we have to remove any tabulators which come from our code indentation so we do it on line 31.

Lines 34 - 36 replace the proper content type for the email header.

Then we need to construct the headers to pass to wp_mail() function in WordPress.

The headers "from" and "sendmail_from" (lines 41 and 42) are very important. They are the lines that ensure when you set "John <email@dot.com>" as email sender, the email will be sent from "John" and not from "WordPress".

The next lines simply add the attachments (assuming you have the object coming from database or so).

Process shortcodes. I prefer to do this (line 51) because this enables the email author to include shortcodes from other plugins in the email contents. Be careful with this if you are letting end users send emails.

Then line 52 calls wp_mail and the function returns the result. Simple, isn't it?

83 comments:

  1. Very good tutorial, it helps the PHP coder a lot to make their site more user friendly using this mail wrapper.
    Web development in India

    ReplyDelete
  2. Its really helpful for me to understand. Thanks.
    If anyone wants to Learn Web Designing in Chennai go to the Besant Technologies which is No.1 Training Institute in Chennai.

    ReplyDelete
  3. This is an informative blog by which I have got that info which I really wanted to get.
    website designers hyderabad Pakistan

    ReplyDelete
  4. This is definitely one of the best articles I have read in this website! Thanks Mate.

    Salesforce Course in Chennai

    ReplyDelete
  5. Salesforce is a cloud based CRM product that allows users to create dynamic application and service over the cloud technology. This virtual technology has huge potential to offer for online community. Salesforce Training institutes in Chennai

    ReplyDelete
  6. Really nice article, and now web design services are depends upon responsive site as well, we need to concentrate on both web and mobile sites.

    ReplyDelete
  7. Article drafted very nicely with great information. It is really helpful. Thanks.
    Manager,
    http://www.pixelcrayons.com/

    ReplyDelete
  8. Thanks for sharing such informative post. Salesforce is a cloud based CRM product that allows users to create dynamic application and service over the cloud technology. This virtual technology has huge potential to offer for online community. Salesforce Training in Chennai

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. i read your blog from the first line and you have posted the solution very clearly thanks for sharing this niche info's
    Web design course in Chennai

    ReplyDelete
  11. Hadoop Course Chennai

    Hi, I am Jack lives in Chennai. I am technology freak. I did Hadoop Training in Chennai at FITA which offers best Big Data Training in Chennai. This is useful for me to make a bright career in IT field.

    Big Data Course Chennai


    ReplyDelete
  12. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. if anyone looking best DOT NET Training in Chennai just get here...

    ReplyDelete
  13. i have read your post, it was good to read & i am getting some useful info's through your blog keep sharing...
    Salesforce training in Chennai|Salesforce courses in Chennai

    ReplyDelete
  14. The information you have given here is truly helpful to me. CCNA- It’s a certification program based on routing & switching for starting level network engineers that helps improve your investment in knowledge of networking & increase the value of employer’s network, if you want to take ccna course in Chennai get into FITA, thanks for sharing…
    ccna training in Chennai | ccna training institute in Chennai

    ReplyDelete
  15. This article is very interesting to learn.All the features are very helpful.Now i clearly know about PHPwith the help of this article.
    PHP Training in chennai | PHP Training chennai | PHP course in chennai | PHP course chennai

    ReplyDelete
  16. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    Mysql Training in chennai | Mysql Training chennai | Mysql course in chennai | Mysql course chennai

    ReplyDelete
  17. Your blog is really awesome and I got some useful information from your blog. This is really useful for me. Thanks for sharing such a informative blog. Keep posting.

    Regards..
    Cloud Computing Training in Chennai

    ReplyDelete
  18. The information you posted here is useful to make my career better. Thanks for sharing such a informative post. keep updates...

    Regards..
    Salesforce Administrator Training in Chennai

    ReplyDelete
  19. Hi, Thanks for sharing this valuable blog.I was really impressed by reading this blog. I did HTML5 Training in Chennai at reputed HTML5 Training Institutes in Chennai. This is really useful for me to make a bright future in designing field.

    ReplyDelete
  20. Well post in recent day’s customer relationship play vital role to get good platform in business industry, Salesforce crm tool helps you to maintain your customer relationship enhancement.
    Regards,
    Salesforce training institute in Chennai

    ReplyDelete
  21. Salesforce is a cloud based CRM software. Today's most of the IT industry use this software for customer relationship management. To get more details about salesforce please refer this site.

    Regards..

    Salesforce Training in Chennai

    ReplyDelete
  22. Nice blog...Very useful information is providing by ur blog. find Great beginning php tutorials Very clear and helpful for beginners.

    ReplyDelete
  23. Thanks for posting this, i am looking for this..... and it gives me a lot to learn. I have seen a website, which provides an ease to learn : http://www.apextgi.in/PHP/PHPOverView.aspx

    ReplyDelete
  24. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    Regards,
    Salesforce training |Salesforce course in Chennai

    ReplyDelete
  25. There are lots of information about latest technology and how to get trained in them, like Hadoop Training Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies(Hadoop Training in Chennai). By the way you are running a great blog. Thanks for sharing this.

    ReplyDelete
  26. Thanks for sharing informative article on cloud computing technology. Your article helped me a lot in understand the future of cloud technology. Having strong expertise in leading cloud based CRM like Salesforce will ensure better career prospects for aspiring professionals. Salesforce Training in Chennai | Hadoop Training in Chennai

    ReplyDelete
  27. Thanks for sharing this valuable post to my knowledge; SAS has great scope in IT industry. It’s an application suite that can change, manage & retrieve data from the variety of origin & perform statistical analytic on it...
    Regards,
    sas training in Chennai|sas course in Chennai|sas training chennai|sas training institute in Chennai

    ReplyDelete
  28. Mangaining customers and thereby increasing the company's revenue is the toughest thing to handle. But companies like Salesforce are dedicated to it by offering most useful and efficient tools. Your content is stating the same. Thanks for offering a worth able article to read. Keep up the activity of posting valuable posts.

    Salesforce.com training in chennai | Saesforce Admin Training in Chennai | Salesforce admin training in chennai

    ReplyDelete
  29. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…
    Regards,
    Informatica training in chennai|Informatica training chennai

    ReplyDelete
  30. Data processing is the biggest challenge to veterans since last decade. With the invention of cloud solution the burden about data handling become zero percent(Cloud computing training in chennai). Thanks for providing such an useful content here. The information is explicit and clear(Cloud computing training institutes in chennai). Keep blogging like this.(Cloud computing training chennai)

    ReplyDelete
  31. Cloud servers are the best in safe guarding one's information thorugh online. Without this dedicated methodology many companies would have not existed at all. The same though has been furnished above. Thanks for sharing this worth while content in here. Keep writing article like this.

    Salesforce Training | Salesforce training institutes in chennai | Salesforce crm training in chennai

    ReplyDelete
  32. Thanks you for the awesome information in your blog on  PHP

    ReplyDelete
  33. Thanks for sharing great information in your blog. Got to learn new things from your Blog . It was very nice blog to learn about php

    ReplyDelete
  34. Thanks for writing in such an encouraging post. I had a glimpse of it and couldn’t stop reading till I finished. I have already bookmarked you.Java training jalandhar

    ReplyDelete
  35. IVM is a powerful IVR Plugin software for interactive voice response, voicemail & call attendant phone systems; supporting caller ID logging and multi-line support.

    ReplyDelete
  36. Have you been thinking about the power sources and the tiles whom use blocks I wanted to thank you for this great read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out the new stuff you post. web designing course in jalandhar

    ReplyDelete
  37. Thanks for the good words! Really appreciated. Great post. I ve been commenting a lot on a few blogs recently, but I had nt thought about my approach until you brought it up.

    SAP training in Chennai

    ReplyDelete
  38. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    Digital marketing company in Chennai

    ReplyDelete
  39. There are lots of information about latest technology and how to get trained in them, like this have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies. By the way you are running a great blog. Thanks for sharing this.
    SAS training in chennai

    ReplyDelete
  40. Great and useful article. Creating content regularly is very tough. Your points are motivated me to move on.


    SEO Company in Chennai

    ReplyDelete
  41. A nice article here, i think that people who have grown up with the idea of using computers are showing more responsibility towards writing posts that are thoughtful, do not have grammar mistakes and pertinent to the post..

    Corporate Training in Chennai

    ReplyDelete
  42. Excellent and very cool idea and the subject at the top of magnificence and I am happy to this post..Interesting post! Thanks for writing it. What's wrong with this kind of post exactly? It follows your previous guideline for post length as well as clarity..

    Corporate Training in Chennai

    ReplyDelete
  43. This blog explains the details about changing the ways of doing that business. That is understand well and doing some different process. Provides he best output of others. Thanks for this blog.
    PPC Services Chennai

    ReplyDelete
  44. This blog explains the details about changing the ways of doing that business. That is understand well and doing some different process. Provides he best output of others. Thanks for this blog.
    PPC Services Chennai

    ReplyDelete
  45. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.


    Digital Marketing Company in Chennai

    ReplyDelete
  46. Wowwww... really great information. Having interesting topic. The pictorial representation helps me to easy understanding of this. Have a great idea. Thank you.
    PPC Services Chennai

    ReplyDelete
  47. Really, these quotes are the holistic approach towards mindfulness. In fact, all of your posts are. Proudly saying I’m getting fruitfulness out of it what you write and share. Thank you so much to both of you.

    App store optimization services

    ReplyDelete
  48. My friend Suggest me this blog and I can say this is the best blog to get the basic knowledge.Thank you so much for this Selenium Training in Chennai

    ReplyDelete
  49. I got knowledge about this topic through your informative post.
    datamodeling training in chennai

    ReplyDelete
  50. THANKS for sharing this great content to my vision..
    webshere training inchennai

    ReplyDelete
  51. for preparing bank exam and group exam , we are providing an online test model questions papers

    Group Exam Questions and Answers
    Bank Exam Questions and Answers

    ReplyDelete
  52. Well explained. Got to learn new things from your Blog on Appium.Appium training in chennai

    ReplyDelete
  53. Thank you for sharing such a nice and interesting blog with us. Hope it might be much useful for us. keep on updating...!!
    seo company in india
    digital marketing company in india
    seo company in chennai
    digital marketing company in chennai

    ReplyDelete
  54. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your.
    seo company in india

    ReplyDelete
  55. I have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle. please keep on updates. Hope it might be much useful for us. keep on updating.
    PHP Training in Chennai

    ReplyDelete
  56. Thanks for sharing the valuable information here. So i think i got some useful information with this content. Thank you and please keep update like this informative details.

    Web Design Company in Chennai

    ReplyDelete
  57. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Isoft Innovations Facebook

    ReplyDelete
  58. Truly a very good article on how to handle the future technology. After reading your post,thanks for taking the time to discuss this, I feel happy about and I love learning more about this topic
    Isoft Innovations Facebook
    Isoft Innovation Chennai

    ReplyDelete
  59. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.


    MSBI Training in Chennai

    ReplyDelete
  60. Great post! I am actually getting ready to across this information, is very helpful my friend. Also great blog here with all of the valuable information you have Keep up the good work you are doing here.Well, got a good knowledge.

    Best Laser Clinic In Chennai

    Best Implant Clinic In Chennai

    ReplyDelete
  61. Thanks for sharing this information and keep updating us regularly. This content is really helped me to know about the Web Designing.
    Web Designing Course in Chennai |Web Designing Training in Chennai | Web Design Course in Chennai

    ReplyDelete
  62. Great post! I am see the great contents and step by step read really nice information.I am gather this concepts and more information. It's helpful for me my friend. Also great blog here with all of the valuable information you have.
    House Cleaning Service in Chennai


    ReplyDelete

  63. Excellent Post, This is the initial work everyone should do before start SEO work for website, without indexing we didn't get ranking in future.
    Regards,
    SEO Training in Chennai|SEO Training Center in Chennai|

    ReplyDelete
  64. Nice one. Thanks for your valuable time and information through this article, it helps me to understand and clear the doubts for web designing.
    Web Designing Training in chenani

    ReplyDelete
  65. website design and website development. Search engine optimisation|(SEO),
    custom software development and reseller web hosting solutions.
    Visit To know more: urmwebsolutions

    ReplyDelete