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?

88 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. 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
  5. 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
  6. Article drafted very nicely with great information. It is really helpful. Thanks.
    Manager,
    http://www.pixelcrayons.com/

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

    ReplyDelete
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. Thanks you for the awesome information in your blog on  PHP

    ReplyDelete
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. I got knowledge about this topic through your informative post.
    datamodeling training in chennai

    ReplyDelete
  28. Thanks for sharing great information in your blog.
    tib co training in chennai

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

    ReplyDelete
  30. 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
  31. 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
  32. 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
  33. 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
  34. 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

  35. 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
  36. 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
  37. website design and website development. Search engine optimisation|(SEO),
    custom software development and reseller web hosting solutions.
    Visit To know more: urmwebsolutions

    ReplyDelete
  38. Hi Wow what a article i really enjoyed reading this i will come again to read, And you are looking for Hosting Services in india Please visit us We are Best Hosting Service Provider Thanks

    ReplyDelete
  39. very nice post I really enjoyed reading this article we are open cart developers company if you are looking for any web development pls visit us.

    ReplyDelete
  40. "Thanks for sharing this information I really enjoyed reading this article if you are looking for
    Daclatasvir 60mg please visit us."

    ReplyDelete
  41. This is great and really informative.. I’ll keep following your web and your article, thanks for sharing :Daclatasvir 60mg from the million health pharmaceuticals.

    ReplyDelete
  42. non specific daklinza.com requires either the User or Customer or the Caregiver to affirm he/she is totally mindful of the signs, symptoms, medicate cooperations, impacts of missed dosage or overdose of the drugs he/she arranges from us. It is basic to look for proficient guidance from your doctor before obtaining or devouring any drug from bland daklinza.com
    Generic Daklinza
    Daclatasvir 60mg
    Natdac 60mg
    Mydekla 60mg
    Daclahep 60mg
    Dacihep 60mg

    ReplyDelete
  43. I would like to thank you for the efforts you have made in writing this article. Find an amazing selection of the the designer luggage & travel handbags from the world.

    ReplyDelete
  44. Undoubtedly gainful article published by you. This was truly helpful for me and I can merely say that it might be considerable for many other seekers as well. Keep sharing this valuable articles.
    Website Design Agency | Website design company

    ReplyDelete
  45. Thank you for sharing this Blog, It has very useful information. keep sharing!
    DevOps Online Training

    ReplyDelete
  46. Thank you so much for your information,its very useful and helful to me.Keep updating and sharing. Thank you.
    rpa training in chennai | rpa course fee in chennai | trending technologies list 2018

    ReplyDelete
  47. Thanks for useful information.
    Need a Microsoft office support(http://www.officesecurity365.com/)

    ReplyDelete
  48. Thanks for nice article sir ,you post nice thought.if you are looking for Best lightwight stroller please visit us.

    ReplyDelete
  49. This blog is full of Innovative ideas.surely i will look into this insight.please add more information's like this soon.
    AWS Training in Mogappair
    AWS Training in Thirumangalam
    AWS Training in Nungambakkam
    AWS Training in Vadapalani

    ReplyDelete
  50. Great Article… I love to read your articles because your writing style is too good, its is very very helpful. I truly appreciate the article post thanks for sharing... WE are WYOXSPORTS contact us for all weightlifting accessories

    ReplyDelete
  51. Hi DEAR.. obligation of appreciation is all together to pick a chance to discuss this, I feel staggering about it and Thanks for sharing this post. We Are Dolphin Automation and Technology get in touch with us for Mobile Signal Booster
    mobile network solution

    ReplyDelete
  52. Nice post. By reading your blog, i get inspired and this provides some useful information. Thank you for posting this exclusive post for our vision.
    Mobile phone Battery replacement | Mobile phone unlocking service | 100% genuine mobile parts | Tab service center in chennai | 100% genuine mobile parts | Mobile phone glass replacement

    ReplyDelete
  53. Extraordinary Article… I want to peruse your articles in light of the fact that your composition style is excessively great, its is extremely useful for us all and I never get exhausted while perusing your article since, they are turns into an increasingly intriguing from the beginning lines until the end. clark area detainment focus 24 hour safeguard bonds.

    Adopt Pets
    Adopt dogs near me
    Adopt dogs near me
    Adopt pet online in india
    Pets For Sale

    ReplyDelete
  54. Zehra Global Services provides the best services Graphic Design, Software Development, Digital marketing and Mobile app development. It provides the best services to our customer.
    Web Development
    UI-UX Design
    Mobile App Development

    ReplyDelete
  55. hello my dear friend thanks for sharing this i really love your post and your post are to informative and knowledgeable . thanks and please visit this for To test your luck satta matka fix jodi , Mumbai matka Jodi
    satta fix jodi

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

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

    ReplyDelete
  58. Situs QQ Terbaru dan Terpercaya yang ada di Indonesia. Mungkin banyak sekali orang yang ingin mencoba bermain pada situs terbaru yang ada diantara banyaknya situs yang beredar saat ini
    asikqq
    dewaqq
    sumoqq
    interqq
    pionpoker
    bandar ceme terbaik
    hobiqq
    paito warna terlengkap
    syair sgp

    ReplyDelete
  59. Good explanation by the author
    Sanjary Academy provides excellent training for Piping design course. Best Piping Design Training Institute in Hyderabad, Telangana. We have offer professional Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course, Welding Inspector Course, Quality Management Course, #Safety officer course.
    Piping Design Course in Hyderabad ­

    ReplyDelete
  60. Thanks for provide great information and looking beautiful blog. If you wish to learn get connected with Advanced Cyber Security Course. I hope below information will help you.
    Ethical Hacking Training in chennai
    Best Training Institute in Chennai

    ReplyDelete
  61. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page! lookup email

    ReplyDelete
  62. top social media influencers in chennai - Devoted to publishing the most recent search news, the simplest guides and how-to's for the SEO and Online advertising community

    ReplyDelete
  63. If you want to download Diwali images, you can download from here.happy diwali 2019

    ReplyDelete
  64. Good information
    Best QA / QC Course in India, Hyderabad. sanjaryacademy is a well-known institute. We have offer professional Engineering Course like Piping Design Course, QA / QC Course,document Controller course,pressure Vessel Design Course, Welding Inspector Course, Quality Management Course, #Safety officer course.
    QA / QC Course
    QA / QC Course in india
    QA / QC Course in hyderabad

    ReplyDelete
  65. Thanks for sharing this informative information in you want to BUY AVIPATTIKAR CHURNA ONLINE than please contect us

    ReplyDelete
  66. thanks for information if u want to know more about Drone Reviews kindly visit us here. List of best drone in 2020.

    ReplyDelete
  67. Thanks for sharing this informative information in you want to BUY DRONE in 2020. than please contect us Here.

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

    ReplyDelete
  69. this is really an awesome article, which you gave, all the best.
    basics of python

    ReplyDelete
  70. "Thanks for sharing your post. It always heps to improve my knowledge most of the times.
    I have been associtaed with 'Top frozen food brand' which serves frozen and boneless chicken, frozen turkey meat, frozen and boneless pork meat, frozen beef meat, frozen rabbit meat, and frozen lamb meat."
    halal frozen meat supplier malaysia

    ReplyDelete