├── .gitignore ├── LICENSE ├── README-en.md ├── README.md ├── composer.json ├── example └── mailer.php └── src ├── Mailer.php ├── MailerService.php ├── Message.php └── helpers.php /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | vendor/ 3 | composer.lock 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README-en.md: -------------------------------------------------------------------------------- 1 | **english** | [русский](./README.md) 2 | - - - 3 | 4 | Phalcon Mailer 5 | ============== 6 | Convenient library for sending your mail to [Phalcon 2.0](http://phalconphp.com/). 7 | 8 | The code is borrowed from Laravel 4 and adapted for Phalcon. 9 | 10 | Installation 11 | --------- 12 | With the help of `composer`: 13 | 14 | Add the following line to the `composer.json` file in the `require` section: 15 | 16 | ``` 17 | "vanchelo/phalcon-mailer": "~2.0" 18 | ``` 19 | or run on the command line: 20 | 21 | ``` 22 | composer require vanchelo/phalcon-mailer 23 | ``` 24 | It should look something like this: 25 | 26 | ```json 27 | { 28 | "require": { 29 | "vanchelo/phalcon-mailer": "~2.0" 30 | } 31 | } 32 | ``` 33 | After that, run the command in the terminal: 34 | 35 | ```bash 36 | composer update 37 | ``` 38 | Service initialization 39 | --------- 40 | ```php 41 | /** 42 | * Register Mailer Service 43 | */ 44 | $this->di['mailer'] = function() { 45 | $service = new MailerService(); 46 | return $service->mailer(); 47 | }; 48 | ``` 49 | or with passing parameters at the stage of service initialization 50 | 51 | ```php 52 | /** 53 | * Register Mailer Service 54 | */ 55 | $this->di['mailer'] = function() { 56 | $service = new MailerService([ 57 | 'driver' => 'smtp', // mail, sendmail, smtp 58 | 'host' => 'smtp.email.com', 59 | 'port' => 587, 60 | 'from' => [ 61 | 'address' => 'no-reply@my-domain.com', 62 | 'name' => 'My Cool Company', 63 | ], 64 | 'encryption' => 'tls', 65 | 'username' => 'no-reply@my-domain.com', 66 | 'password' => 'some-strong-password', 67 | 'sendmail' => '/usr/sbin/sendmail -bs', 68 | // The path used to find email templates 69 | 'viewsDir' => __DIR__ . '/../app/views/', // optional 70 | ]); 71 | return $service->mailer(); 72 | }; 73 | ``` 74 | 75 | Sending letter 76 | --------- 77 | Example for a controller, but will work not only in controllers 78 | 79 | ```php 80 | $this->mailer->send('emails/xxx', [ 81 | 'test' => 'test' // Template variables 82 | ], function($message) { 83 | $message->to('some_email@email.com'); 84 | $message->subject('Test Email'); 85 | }); 86 | ``` 87 | where, emails / xxx is a letter template located in the views directory, (app/views/emails/xxx.[phtml|volt]) 88 | 89 | By default, if the `view` service is registered in the container, the library will use it, so you can use any convenient available template engine (phtml, volt, etc.) 90 | 91 | Settings 92 | --------- 93 | The default settings must be written in the configuration file of your application config / config.php 94 | ```php 95 | [ 98 | 'driver' => 'smtp', // mail, sendmail, smtp 99 | 'host' => 'smtp.email.com', 100 | 'port' => 587, 101 | 'from' => [ 102 | 'address' => 'no-reply@my-domain.com', 103 | 'name' => 'My Cool Company' 104 | ], 105 | 'encryption' => 'tls', 106 | 'username' => 'no-reply@my-domain.com', 107 | 'password' => 'some-strong-password', 108 | 'sendmail' => '/usr/sbin/sendmail -bs', 109 | // The path used to find email templates 110 | 'viewsDir' => __DIR__ . '/../app/views/', // optional 111 | ], 112 | ]); 113 | ``` 114 | 115 | If necessary, mail settings can be moved to a separate configuration file 116 | 117 | ** UPD **. Implemented the ability to use queues for delayed mail sending via the Beanstalk queue service implemented in Phalcon 118 | 119 | Queues (delayed mail sending) 120 | --------- 121 | 122 | For delayed sending of mail, you must have registered the `queue` service in the container, for example: 123 | 124 | ```php 125 | use Phalcon\Queue\Beanstalk; 126 | $this->di['queue'] = function () { 127 | $queue = new Beanstalk(); 128 | $queue->connect(); // ? 129 | return $queue; 130 | }; 131 | ``` 132 | 133 | Example of delayed mail sending 134 | 135 | ```php 136 | $this->mailer->queue('emails/xxx', [ 137 | 'test' => 'test' // Template variables 138 | ], function($message) { 139 | $message->to('some_email@email.com'); 140 | $message->subject('Test Email'); 141 | }); 142 | ``` 143 | 144 | All postponed mail is placed in the `mailer` queue (I don't know if this is correct) 145 | 146 | Queue handler example https://github.com/vanchelo/phalcon-mailer/blob/master/example/mailer.php 147 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [english](./README-en.md) | **русский** 2 | - - - 3 | 4 | Phalcon Mailer 5 | ============== 6 | Удобная библиотека для отправки Вашей почты в [Phalcon 2.0](http://phalconphp.com/). 7 | 8 | Код заимствован из Laravel 4 и адаптирован под Phalcon. 9 | 10 | Установка 11 | --------- 12 | C помощью `composer`: 13 | 14 | Добавить в файл `composer.json` в секцию `require` следующую строку: 15 | ``` 16 | "vanchelo/phalcon-mailer": "~2.0" 17 | ``` 18 | или выполнить в командной строке: 19 | ``` 20 | composer require vanchelo/phalcon-mailer 21 | ``` 22 | Должно получится примерно так: 23 | ```json 24 | { 25 | "require": { 26 | "vanchelo/phalcon-mailer": "~2.0" 27 | } 28 | } 29 | ``` 30 | После этого выполните в терминале команду: 31 | ```bash 32 | composer update 33 | ``` 34 | 35 | Инициализация сервиса 36 | --------- 37 | ```php 38 | /** 39 | * Register Mailer Service 40 | */ 41 | $this->di['mailer'] = function() { 42 | $service = new MailerService(); 43 | 44 | return $service->mailer(); 45 | }; 46 | ``` 47 | или с передачей параметров на этапе инициализации сервиса 48 | 49 | ```php 50 | /** 51 | * Register Mailer Service 52 | */ 53 | $this->di['mailer'] = function() { 54 | $service = new MailerService([ 55 | 'driver' => 'smtp', // mail, sendmail, smtp 56 | 'host' => 'smtp.email.com', 57 | 'port' => 587, 58 | 'from' => [ 59 | 'address' => 'no-reply@my-domain.com', 60 | 'name' => 'My Cool Company', 61 | ], 62 | 'encryption' => 'tls', 63 | 'username' => 'no-reply@my-domain.com', 64 | 'password' => 'some-strong-password', 65 | 'sendmail' => '/usr/sbin/sendmail -bs', 66 | // Путь используемый для поиска шаблонов писем 67 | 'viewsDir' => __DIR__ . '/../app/views/', // optional 68 | ]); 69 | 70 | return $service->mailer(); 71 | }; 72 | ``` 73 | 74 | Отправка письма 75 | --------- 76 | Пример для контроллера, но работать будет не только в контроллерах 77 | ```php 78 | $this->mailer->send('emails/xxx', [ 79 | 'test' => 'test' // Переменные для передачи в шаблон 80 | ], function($message) { 81 | $message->to('some_email@email.com'); 82 | $message->subject('Test Email'); 83 | }); 84 | ``` 85 | где, emails/xxx - шаблон письма расположенный в каталоге views, (app/views/emails/xxx.[phtml|volt]) 86 | 87 | По умолчанию, если в контейнере зарегистрирован сервис `view` библиотека будет использовать его, соответственно можно использовать любой удобный доступный шаблонизатор (phtml, volt и т.д.) 88 | 89 | Настройки 90 | --------- 91 | Настройки по умолчанию необходимо прописать в конфигурационном файле вашего приложения config/config.php 92 | ```php 93 | [ 96 | 'driver' => 'smtp', // mail, sendmail, smtp 97 | 'host' => 'smtp.email.com', 98 | 'port' => 587, 99 | 'from' => [ 100 | 'address' => 'no-reply@my-domain.com', 101 | 'name' => 'My Cool Company' 102 | ], 103 | 'encryption' => 'tls', 104 | 'username' => 'no-reply@my-domain.com', 105 | 'password' => 'some-strong-password', 106 | 'sendmail' => '/usr/sbin/sendmail -bs', 107 | // Путь используемый для поиска шаблонов писем 108 | 'viewsDir' => __DIR__ . '/../app/views/', // optional 109 | ], 110 | ]); 111 | ``` 112 | 113 | Если будет необходимость, настройки почты можно вынести в отдельный конфигурационный файл 114 | 115 | **UPD**. Реализована возможность использования очередей для отложенной отправки почты через реализованный в Phalcon сервис очередей Beanstalk 116 | 117 | Очереди (отложенная отправка почты) 118 | --------- 119 | 120 | Для отложенной отправки почты у вас должен быть зарегистрирован сервис `queue` в контейнере, например: 121 | 122 | ```php 123 | use Phalcon\Queue\Beanstalk; 124 | 125 | $this->di['queue'] = function () { 126 | $queue = new Beanstalk(); 127 | $queue->connect(); // ? 128 | 129 | return $queue; 130 | }; 131 | ``` 132 | 133 | Пример отложенной отправки почты 134 | 135 | ```php 136 | $this->mailer->queue('emails/xxx', [ 137 | 'test' => 'test' // Переменные для передачи в шаблон 138 | ], function($message) { 139 | $message->to('some_email@email.com'); 140 | $message->subject('Test Email'); 141 | }); 142 | ``` 143 | 144 | Вся отложенная почта помещается в очередь `mailer` (не знаю насколько это правильно) 145 | 146 | Пример обработчика очереди https://github.com/vanchelo/phalcon-mailer/blob/master/example/mailer.php 147 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vanchelo/phalcon-mailer", 3 | "type": "library", 4 | "description": "Phalcon Mailer Service", 5 | "keywords": ["mail","mailer","phalcon"], 6 | "homepage": "https://github.com/vanchelo/phalcon-mailer", 7 | "license": "GPL-2.0-or-later", 8 | "authors": [ 9 | { 10 | "name": "Brezhnev Ivan" 11 | } 12 | ], 13 | "require": { 14 | "php": ">=5.4.0", 15 | "swiftmailer/swiftmailer": "~5.3", 16 | "jeremeamia/superclosure": "~1.0.1" 17 | }, 18 | "require-dev": { 19 | "phalcon/devtools": "~2.0" 20 | }, 21 | "autoload": { 22 | "psr-4": { 23 | "Vanchelo\\Mailer\\": "src/" 24 | }, 25 | "files": [ 26 | "src/helpers.php" 27 | ] 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /example/mailer.php: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | set('config', $config); 13 | 14 | $queue = new Beanstalk(); 15 | $queue->choose('mailer'); 16 | $di['queue'] = $queue; 17 | 18 | /** 19 | * Register Mailer Service 20 | */ 21 | $di['mailer'] = function () 22 | { 23 | $service = new MailerService(); 24 | 25 | return $service->mailer(); 26 | }; 27 | 28 | /** @var Job $job */ 29 | while (($job = $queue->peekReady()) !== false) 30 | { 31 | $data = json_decode($job->getBody(), true); 32 | 33 | $segments = explode(':', $data['job']); 34 | 35 | if (count($segments) !== 2) 36 | { 37 | continue; 38 | } 39 | 40 | call_user_func_array([$di[$segments[0]], $segments[1]], [$job, $data['data']]); 41 | } 42 | -------------------------------------------------------------------------------- /src/Mailer.php: -------------------------------------------------------------------------------- 1 | view = $view; 69 | $this->swift = $swift; 70 | } 71 | 72 | /** 73 | * Set the global from address and name 74 | * 75 | * @param string $address 76 | * @param string $name 77 | */ 78 | public function alwaysFrom($address, $name = null) 79 | { 80 | $this->from = compact('address', 'name'); 81 | } 82 | 83 | /** 84 | * Send a new message when only a plain part 85 | * 86 | * @param string $view 87 | * @param array $data 88 | * @param mixed $callback 89 | * 90 | * @return int 91 | */ 92 | public function plain($view, array $data, $callback) 93 | { 94 | return $this->send(['text' => $view], $data, $callback); 95 | } 96 | 97 | /** 98 | * Send a new message using a view 99 | * 100 | * @param string|array $view 101 | * @param array $data 102 | * @param Closure|string $callback 103 | * 104 | * @return int 105 | */ 106 | public function send($view, array $data, $callback) 107 | { 108 | // First we need to parse the view, which could either be a string or an array 109 | // containing both an HTML and plain text versions of the view which should 110 | // be used when sending an e-mail. We will extract both of them out here. 111 | list($view, $plain) = $this->parseView($view); 112 | 113 | $data['message'] = $message = $this->createMessage(); 114 | 115 | $this->callMessageBuilder($callback, $message); 116 | 117 | // Once we have retrieved the view content for the e-mail we will set the body 118 | // of this message using the HTML type, which will provide a simple wrapper 119 | // to creating view based emails that are able to receive arrays of data. 120 | $this->addContent($message, $view, $plain, $data); 121 | 122 | $message = $message->getSwiftMessage(); 123 | 124 | return $this->sendSwiftMessage($message); 125 | } 126 | 127 | /** 128 | * Add the content to a given message 129 | * 130 | * @param Message $message 131 | * @param string $view 132 | * @param string $plain 133 | * @param array $data 134 | */ 135 | protected function addContent(Message $message, $view, $plain, $data) 136 | { 137 | if (isset($view)) { 138 | $message->setBody($this->render($view, $data), 'text/html'); 139 | } 140 | 141 | if (isset($plain)) { 142 | $message->addPart($this->render($plain, $data), 'text/plain'); 143 | } 144 | } 145 | 146 | /** 147 | * Parse the given view name or array 148 | * 149 | * @param string|array $view 150 | * 151 | * @return array 152 | */ 153 | protected function parseView($view) 154 | { 155 | if (is_string($view)) return [$view, null]; 156 | 157 | // If the given view is an array with numeric keys, we will just assume that 158 | // both a "pretty" and "plain" view were provided, so we will return this 159 | // array as is, since must should contain both views with numeric keys. 160 | if (is_array($view) && isset($view[0])) { 161 | return $view; 162 | } 163 | 164 | // If the view is an array, but doesn't contain numeric keys, we will assume 165 | // the the views are being explicitly specified and will extract them via 166 | // named keys instead, allowing the developers to use one or the other. 167 | elseif (is_array($view)) { 168 | return [ 169 | array_get($view, 'html'), 170 | array_get($view, 'text'), 171 | ]; 172 | } 173 | 174 | throw new \InvalidArgumentException("Invalid view."); 175 | } 176 | 177 | /** 178 | * Send a Swift Message instance 179 | * 180 | * @param Swift_Message $message 181 | * 182 | * @return int 183 | */ 184 | public function sendSwiftMessage(Swift_Message $message) 185 | { 186 | return $this->swift->send($message); 187 | } 188 | 189 | /** 190 | * Call the provided message builder 191 | * 192 | * @param $callback 193 | * @param $message 194 | * 195 | * @return mixed 196 | * @throws \InvalidArgumentException 197 | */ 198 | protected function callMessageBuilder($callback, $message) 199 | { 200 | if ($callback instanceof Closure) { 201 | return call_user_func($callback, $message); 202 | } 203 | 204 | throw new \InvalidArgumentException("Callback is not valid."); 205 | } 206 | 207 | /** 208 | * Create a new message instance 209 | * 210 | * @return Message 211 | */ 212 | protected function createMessage() 213 | { 214 | $message = new Message(new Swift_Message); 215 | 216 | // If a global from address has been specified we will set it on every message 217 | // instances so the developer does not have to repeat themselves every time 218 | // they create a new message. We will just go ahead and push the address. 219 | if (isset($this->from['address'])) { 220 | $message->from($this->from['address'], $this->from['name']); 221 | } 222 | 223 | return $message; 224 | } 225 | 226 | /** 227 | * Render the given view 228 | * 229 | * @param string $view 230 | * @param array $data 231 | * 232 | * @return string 233 | */ 234 | protected function render($view, $data) 235 | { 236 | ob_start(); 237 | $this->view->partial($view, $data); 238 | $content = ob_get_clean(); 239 | 240 | return $content; 241 | } 242 | 243 | /** 244 | * Get the view environment instance 245 | * 246 | * @return \Phalcon\Mvc\View 247 | */ 248 | public function getViewEnvironment() 249 | { 250 | return $this->view; 251 | } 252 | 253 | /** 254 | * Get the Swift Mailer instance 255 | * 256 | * @return Swift_Mailer 257 | */ 258 | public function getSwiftMailer() 259 | { 260 | return $this->swift; 261 | } 262 | 263 | /** 264 | * Set the Swift Mailer instance 265 | * 266 | * @param Swift_Mailer $swift 267 | */ 268 | public function setSwiftMailer($swift) 269 | { 270 | $this->swift = $swift; 271 | } 272 | 273 | /** 274 | * Build the callable for a queued e-mail job 275 | * 276 | * @param mixed $callback 277 | * 278 | * @return mixed 279 | */ 280 | protected function buildQueueCallable($callback) 281 | { 282 | if (!$callback instanceof Closure) return $callback; 283 | 284 | return serialize(new SerializableClosure($callback)); 285 | } 286 | 287 | /** 288 | * Handle a queued e-mail message job 289 | * 290 | * @param \Phalcon\Queue\Beanstalk\Job $job 291 | * @param array $data 292 | */ 293 | public function handleQueuedMessage($job, $data) 294 | { 295 | $this->send($data['view'], $data['data'], $this->getQueuedCallable($data)); 296 | 297 | $job->delete(); 298 | } 299 | 300 | /** 301 | * Get the true callable for a queued e-mail message 302 | * 303 | * @param array $data 304 | * 305 | * @return mixed 306 | */ 307 | protected function getQueuedCallable(array $data) 308 | { 309 | if (str_contains($data['callback'], 'SerializableClosure')) { 310 | return with(unserialize($data['callback']))->getClosure(); 311 | } 312 | 313 | return $data['callback']; 314 | } 315 | 316 | /** 317 | * Queue a new e-mail message for sending 318 | * 319 | * @param string|array $view 320 | * @param array $data 321 | * @param \Closure|string $callback 322 | * 323 | * @return mixed 324 | */ 325 | public function queue($view, array $data, $callback) 326 | { 327 | $callback = $this->buildQueueCallable($callback); 328 | 329 | $this->queue->choose('mailer'); 330 | 331 | return $this->queue->put(json_encode([ 332 | 'job' => 'mailer:handleQueuedMessage', 333 | 'data' => [ 334 | 'view' => $view, 335 | 'data' => $data, 336 | 'callback' => $callback, 337 | ], 338 | ])); 339 | } 340 | 341 | /** 342 | * Get the array of failed recipients 343 | * 344 | * @return array 345 | */ 346 | public function failures() 347 | { 348 | return $this->failedRecipients; 349 | } 350 | 351 | /** 352 | * Set the Beanstalk queue instance 353 | * 354 | * @param \Phalcon\Queue\Beanstalk $queue 355 | * 356 | * @return self 357 | */ 358 | public function setQueue(Beanstalk $queue) 359 | { 360 | $this->queue = $queue; 361 | 362 | return $this; 363 | } 364 | 365 | /** 366 | * Sets the dependency injector 367 | * 368 | * @param mixed $dependencyInjector 369 | */ 370 | public function setDI(DiInterface $dependencyInjector) 371 | { 372 | $this->di = $dependencyInjector; 373 | } 374 | 375 | /** 376 | * Returns the internal dependency injector 377 | * 378 | * @return DiInterface 379 | */ 380 | public function getDI() 381 | { 382 | return $this->di; 383 | } 384 | } 385 | -------------------------------------------------------------------------------- /src/MailerService.php: -------------------------------------------------------------------------------- 1 | di->has('config')) { 32 | throw new \RuntimeException('Correct config for Mailer is not provided!'); 33 | } 34 | 35 | $this->config = $config ?: $this->di['config']->mail->toArray(); 36 | 37 | $this->registerSwiftMailer(); 38 | $this->registerView(); 39 | } 40 | 41 | /** 42 | * Register the Mailer instance 43 | * 44 | * @return Mailer $mailer 45 | */ 46 | public function mailer() 47 | { 48 | // Once we have create the mailer instance, we will set a container instance 49 | // on the mailer. This allows us to resolve mailer classes via containers 50 | // for maximum testability on said classes instead of passing Closures. 51 | $mailer = new Mailer($this->di['mailer.view'], $this->di['swift.mailer']); 52 | 53 | $this->setMailerDependencies($mailer); 54 | 55 | $from = $this->config['from']; 56 | 57 | if (is_array($from) && isset($from['address'])) { 58 | $mailer->alwaysFrom($from['address'], $from['name']); 59 | } 60 | 61 | return $mailer; 62 | } 63 | 64 | /** 65 | * Register the Swift Mailer instance. 66 | */ 67 | protected function registerSwiftMailer() 68 | { 69 | $this->registerSwiftTransport($this->config); 70 | 71 | // Once we have the transporter registered, we will register the actual Swift 72 | // mailer instance, passing in the transport instances, which allows us to 73 | // override this transporter instances during app start-up if necessary. 74 | $this->di['swift.mailer'] = function () { 75 | return new Swift_Mailer($this->di['swift.transport']); 76 | }; 77 | } 78 | 79 | /** 80 | * Register the Swift Transport instance. 81 | * 82 | * @param array $config 83 | */ 84 | protected function registerSwiftTransport(array $config) 85 | { 86 | if (!isset($config['driver'])) { 87 | throw new \InvalidArgumentException('Please set "driver" for Mailer!'); 88 | } 89 | 90 | switch ($config['driver']) { 91 | case 'smtp': 92 | return $this->registerSmtpTransport($config); 93 | 94 | case 'sendmail': 95 | return $this->registerSendmailTransport($config); 96 | 97 | case 'mail': 98 | return $this->registerMailTransport($config); 99 | 100 | default: 101 | throw new \InvalidArgumentException('Invalid mail driver.'); 102 | } 103 | } 104 | 105 | /** 106 | * Register the SMTP Swift Transport instance. 107 | * 108 | * @param array $config 109 | * 110 | * return null 111 | */ 112 | protected function registerSmtpTransport(array $config) 113 | { 114 | $this->di['swift.transport'] = function () use ($config) { 115 | extract($config); 116 | 117 | if (!isset($host, $port)) { 118 | throw new \InvalidArgumentException('Please set "host" and "port" for Mailer!'); 119 | } 120 | 121 | // The Swift SMTP transport instance will allow us to use any SMTP backend 122 | // for delivering mail such as Sendgrid, Amazon SMS, or a custom server 123 | // a developer has available. We will just pass this configured host. 124 | $transport = SmtpTransport::newInstance($host, $port); 125 | 126 | if (isset($encryption)) { 127 | $transport->setEncryption($encryption); 128 | } 129 | 130 | // Once we have the transport we will check for the presence of a username 131 | // and password. If we have it we will set the credentials on the Swift 132 | // transporter instance so that we'll properly authenticate delivery. 133 | if (isset($username, $password)) { 134 | $transport->setUsername($username); 135 | 136 | $transport->setPassword($password); 137 | } 138 | 139 | return $transport; 140 | }; 141 | } 142 | 143 | /** 144 | * Register the Sendmail Swift Transport instance. 145 | * 146 | * @param array $config 147 | */ 148 | protected function registerSendmailTransport(array $config) 149 | { 150 | $this->di['swift.transport'] = function () use ($config) { 151 | return SendmailTransport::newInstance($config['sendmail']); 152 | }; 153 | } 154 | 155 | /** 156 | * Register the Mail Swift Transport instance. 157 | */ 158 | protected function registerMailTransport() 159 | { 160 | $this->di['swift.transport'] = function () { 161 | return MailTransport::newInstance(); 162 | }; 163 | } 164 | 165 | /** 166 | * Register the Simple View instance 167 | */ 168 | protected function registerView() 169 | { 170 | if ($this->di->has('view')) { 171 | $this->di['mailer.view'] = function () { 172 | return $this->di->get('view'); 173 | }; 174 | } else { 175 | $this->di['mailer.view'] = function () { 176 | if (!isset($this->config['viewsDir'])) { 177 | throw new \InvalidArgumentException('Invalid views dir!'); 178 | } 179 | 180 | $view = new SimpleView; 181 | 182 | $view->setViewsDir($this->config['viewsDir']); 183 | 184 | return $view; 185 | }; 186 | } 187 | } 188 | 189 | /** 190 | * Set a few dependencies on the mailer instance. 191 | * 192 | * @param Mailer $mailer 193 | */ 194 | protected function setMailerDependencies(Mailer $mailer) 195 | { 196 | $mailer->setDI($this->di); 197 | 198 | if ($this->di->has('queue')) { 199 | $mailer->setQueue($this->di['queue']); 200 | } 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /src/Message.php: -------------------------------------------------------------------------------- 1 | swift = $swift; 35 | } 36 | 37 | /** 38 | * Add a "from" address to the message. 39 | * 40 | * @param string $address 41 | * @param string $name 42 | * 43 | * @return Message 44 | */ 45 | public function from($address, $name = null) 46 | { 47 | $this->swift->setFrom($address, $name); 48 | 49 | return $this; 50 | } 51 | 52 | /** 53 | * Set the "sender" of the message. 54 | * 55 | * @param string $address 56 | * @param string $name 57 | * 58 | * @return Message 59 | */ 60 | public function sender($address, $name = null) 61 | { 62 | $this->swift->setSender($address, $name); 63 | 64 | return $this; 65 | } 66 | 67 | /** 68 | * Set the "return path" of the message. 69 | * 70 | * @param string $address 71 | * 72 | * @return Message 73 | */ 74 | public function returnPath($address) 75 | { 76 | $this->swift->setReturnPath($address); 77 | 78 | return $this; 79 | } 80 | 81 | /** 82 | * Add a recipient to the message. 83 | * 84 | * @param string|array $address 85 | * @param string $name 86 | * 87 | * @return Message 88 | */ 89 | public function to($address, $name = null) 90 | { 91 | return $this->addAddresses($address, $name, 'To'); 92 | } 93 | 94 | /** 95 | * Add a carbon copy to the message. 96 | * 97 | * @param string $address 98 | * @param string $name 99 | * 100 | * @return Message 101 | */ 102 | public function cc($address, $name = null) 103 | { 104 | return $this->addAddresses($address, $name, 'Cc'); 105 | } 106 | 107 | /** 108 | * Add a blind carbon copy to the message. 109 | * 110 | * @param string $address 111 | * @param string $name 112 | * 113 | * @return Message 114 | */ 115 | public function bcc($address, $name = null) 116 | { 117 | return $this->addAddresses($address, $name, 'Bcc'); 118 | } 119 | 120 | /** 121 | * Add a reply to address to the message. 122 | * 123 | * @param string $address 124 | * @param string $name 125 | * 126 | * @return Message 127 | */ 128 | public function replyTo($address, $name = null) 129 | { 130 | return $this->addAddresses($address, $name, 'ReplyTo'); 131 | } 132 | 133 | /** 134 | * Add a recipient to the message. 135 | * 136 | * @param string|array $address 137 | * @param string $name 138 | * @param string $type 139 | * 140 | * @return Message 141 | */ 142 | protected function addAddresses($address, $name, $type) 143 | { 144 | if (is_array($address)) { 145 | $this->swift->{"set{$type}"}($address, $name); 146 | } else { 147 | $this->swift->{"add{$type}"}($address, $name); 148 | } 149 | 150 | return $this; 151 | } 152 | 153 | /** 154 | * Set the subject of the message. 155 | * 156 | * @param string $subject 157 | * 158 | * @return Message 159 | */ 160 | public function subject($subject) 161 | { 162 | $this->swift->setSubject($subject); 163 | 164 | return $this; 165 | } 166 | 167 | /** 168 | * Set the message priority level. 169 | * 170 | * @param int $level 171 | * 172 | * @return Message 173 | */ 174 | public function priority($level) 175 | { 176 | $this->swift->setPriority($level); 177 | 178 | return $this; 179 | } 180 | 181 | /** 182 | * Attach a file to the message. 183 | * 184 | * @param string $file 185 | * @param array $options 186 | * 187 | * @return Message 188 | */ 189 | public function attach($file, array $options = []) 190 | { 191 | $attachment = $this->createAttachmentFromPath($file); 192 | 193 | return $this->prepAttachment($attachment, $options); 194 | } 195 | 196 | /** 197 | * Create a Swift Attachment instance. 198 | * 199 | * @param string $file 200 | * 201 | * @return Swift_Attachment 202 | */ 203 | protected function createAttachmentFromPath($file) 204 | { 205 | return Swift_Attachment::fromPath($file); 206 | } 207 | 208 | /** 209 | * Attach in-memory data as an attachment. 210 | * 211 | * @param string $data 212 | * @param string $name 213 | * @param array $options 214 | * 215 | * @return Message 216 | */ 217 | public function attachData($data, $name, array $options = []) 218 | { 219 | $attachment = $this->createAttachmentFromData($data, $name); 220 | 221 | return $this->prepAttachment($attachment, $options); 222 | } 223 | 224 | /** 225 | * Create a Swift Attachment instance from data. 226 | * 227 | * @param string $data 228 | * @param string $name 229 | * 230 | * @return Swift_Attachment 231 | */ 232 | protected function createAttachmentFromData($data, $name) 233 | { 234 | return Swift_Attachment::newInstance($data, $name); 235 | } 236 | 237 | /** 238 | * Embed a file in the message and get the CID. 239 | * 240 | * @param string $file 241 | * 242 | * @return string 243 | */ 244 | public function embed($file) 245 | { 246 | return $this->swift->embed(Swift_Image::fromPath($file)); 247 | } 248 | 249 | /** 250 | * Embed in-memory data in the message and get the CID. 251 | * 252 | * @param string $data 253 | * @param string $name 254 | * @param string $contentType 255 | * 256 | * @return string 257 | */ 258 | public function embedData($data, $name, $contentType = null) 259 | { 260 | $image = Swift_Image::newInstance($data, $name, $contentType); 261 | 262 | return $this->swift->embed($image); 263 | } 264 | 265 | /** 266 | * Prepare and attach the given attachment. 267 | * 268 | * @param Swift_Attachment $attachment 269 | * @param array $options 270 | * 271 | * @return Message 272 | */ 273 | protected function prepAttachment(Swift_Attachment $attachment, array $options = []) 274 | { 275 | // First we will check for a MIME type on the message, which instructs the 276 | // mail client on what type of attachment the file is so that it may be 277 | // downloaded correctly by the user. The MIME option is not required. 278 | if (isset($options['mime'])) { 279 | $attachment->setContentType($options['mime']); 280 | } 281 | 282 | // If an alternative name was given as an option, we will set that on this 283 | // attachment so that it will be downloaded with the desired names from 284 | // the developer, otherwise the default file names will get assigned. 285 | if (isset($options['as'])) { 286 | $attachment->setFilename($options['as']); 287 | } 288 | 289 | $this->swift->attach($attachment); 290 | 291 | return $this; 292 | } 293 | 294 | /** 295 | * Get the underlying Swift Message instance. 296 | * 297 | * @return Swift_Message 298 | */ 299 | public function getSwiftMessage() 300 | { 301 | return $this->swift; 302 | } 303 | 304 | /** 305 | * Dynamically pass missing methods to the Swift instance. 306 | * 307 | * @param string $method 308 | * @param array $parameters 309 | * 310 | * @return mixed 311 | */ 312 | public function __call($method, array $parameters) 313 | { 314 | return call_user_func_array([$this->swift, $method], $parameters); 315 | } 316 | } 317 | -------------------------------------------------------------------------------- /src/helpers.php: -------------------------------------------------------------------------------- 1 |