· 6 years ago · Jan 22, 2020, 02:26 AM
1/////error_reporting(0);
2set_time_limit(0);
3//INIT VARS
4$message_base="";$action="";$message="";$emaillist="";$from="";$reconnect="0";$epriority="";$my_smtp="";$ssl_port="25";$encodety="";$replyto="";$subject="";$realname="";$subject_base="";$realname_base="";$contenttype="";$isbcc="";$nbcc="100";$default_system="";$from_base="";$debg="0";$pause=0;$pemails=0;$nm=0;$nopose=true;$nrotat=0;$curentsmtp=0;$canrotat=false;$allsmtps="";$lase="";$reading=false;$repaslog=false;$uploadfile="";
5
6if(!empty($_POST))
7{
8 $debg=lrtrim($_POST['dbg']);
9 if(!empty($_POST['from']))
10 {
11 $from=lrtrim($_POST['from']);
12 $from_base =$from;
13 }
14 $action=lrtrim($_POST['action']);
15 $message=lrtrim($_POST['message']);
16 $message_base=lrtrim($_POST['message']);
17 $emaillist=lrtrim($_POST['emaillist']);
18 $reconnect=lrtrim($_POST['reconnect']);
19 $epriority=lrtrim($_POST['epriority']);
20 $my_smtp=lrtrim($_POST['my_smtp']);
21 $subject=lrtrim($_POST['subject']);
22 $realname=lrtrim($_POST['realname']);
23 $subject_base=lrtrim($_POST['subject']);
24 $realname_base=lrtrim($_POST['realname']);
25 $contenttype=lrtrim($_POST['contenttype']);
26 $encodety=$_POST['encodety'];
27 if(!empty($_POST['pause']))
28 $pause=$_POST['pause'];
29 if(!empty($_POST['replyto']))
30 $replyto=lrtrim($_POST['replyto']);
31 if(!empty($_POST['nrotat']))
32 $nrotat=$_POST['nrotat'];
33 if(!empty($_POST['pemails']))
34 $pemails=$_POST['pemails'];
35 if(!empty($_POST['lase']))
36 $lase=true;
37 if(!empty($_POST['nbcc']))
38 $nbcc=lrtrim($_POST['nbcc']);
39 $allsmtps = preg_split("/\\r\\n|\\r|\\n/", $my_smtp);
40 if(!empty($_POST['readingconf']))
41 $reading=true;
42 if(!empty($_POST['repaslog']))
43 $repaslog=true;
44}
45?>
46<html>
47
48<head>
49<title>PHP Mailer</title>
50<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
51<script
52 src="https://code.jquery.com/jquery-3.1.1.min.js"
53 integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
54 crossorigin="anonymous"></script>
55<style type="text/css">
56<!--
57.style1 {
58 font-family: Geneva, Arial, Helvetica, sans-serif;
59 font-size: 12px;
60}
61-->
62</style>
63<style type="text/css">
64<!--
65.style1 {
66 font-size: 10px;
67 font-family: Geneva, Arial, Helvetica, sans-serif;
68}
69-->
70.td1 {
71 width:150px;
72}
73</style>
74</head>
75<body text="#000000">
76<script>
77$(document).ready(function(){
78 $("#patb").click(function(){
79 if($("#az").prop( "checked" ) || $("#AZ").prop( "checked" ) || $("#09").prop( "checked" ) && $("#len").val() != "")
80 {
81 $("#patval").val("");
82 $("#patval").val($("#patval").val() + "##");
83 if($("#az").prop( "checked" ))
84 {
85 $("#patval").val($("#patval").val() + "az-");
86 }
87 if($("#AZ").prop( "checked" ))
88 {
89 $("#patval").val($("#patval").val() + "AZ-");
90 }
91 if($("#09").prop( "checked" ))
92 {
93 $("#patval").val($("#patval").val() + "09-");
94 }
95 if($("#len").val() != "")
96 {
97 $("#patval").val($("#patval").val() + "{"+$("#len").val()+ "}");
98 }
99 $("#patval").val($("#patval").val() + "##");
100
101 }
102 else $("#patval").val("");
103 });
104 $("#add").click(function(){
105 if($('#my_smtp').html()=="")
106 $('#my_smtp').html($('#ip').val()+':'+$('#ssl_port').val()+':'+$('#user').val()+':'+$('#pass').val()+":"+$('input[name=SSLTLS]:checked').val());
107 else
108 $('#my_smtp').html($('#my_smtp').html()+$('#ip').val()+':'+$('#ssl_port').val()+':'+$('#user').val()+':'+$('#pass').val()+":"+$('input[name=SSLTLS]:checked').val());
109 if($('input[name=isbcc]').prop('checked')) $('#my_smtp').html($('#my_smtp').html()+':BCC');
110 else $('#my_smtp').html($('#my_smtp').html()+':NOBCC');
111 $('#my_smtp').html($('#my_smtp').html()+'\n');
112 $('#user').val("");
113 $('#pass').val("");
114 $('input[name=SSLTLS]').prop('checked', false);
115 });
116 $("#reset").click(function(){
117 $('#my_smtp').html('');
118 });
119 $("input[name=lase]").click(function(){
120 if($('input[name=lase]').prop('checked'))
121 {
122 $('input[name=from]').attr('disabled','disabled');
123 $('input[name=from]').val('');
124 }
125 else
126 $('input[name=from]').removeAttr('disabled');
127 });
128 $("input[name=repaslog]").click(function(){
129 if($('input[name=repaslog]').prop('checked'))
130 {
131 $('input[name=replyto]').attr('disabled','disabled');
132 $('input[name=replyto]').val('');
133 }
134 else
135 $('input[name=replyto]').removeAttr('disabled');
136 });
137});
138</script>
139<p align="center"><font size="5" face="Bauhaus 93">MAILER INBOX SENDING</font><font color="#FFFFFF" size="5" face="Bauhaus 93">RFX</font></p>
140<form name="form1" method="post" action="" enctype="multipart/form-data">
141
142 <br>
143
144 <table width="100%" border="0" height="407">
145
146 <tr>
147
148 <td width="100%" colspan="4" bgcolor="#666666" height="36">
149
150 <b>
151
152 <font face="Arial" size="2" color="#FFFFFF"> SERVER SETUP</font> <font face="Arial" size="2" color="red">DEBUG LVL</font>
153 <select name="dbg">
154 <option value="0" <?php echo ($debg == "0") ? 'selected=selected':''; ?>>OFF</option>
155 <option value="1" <?php echo ($debg == "1") ? 'selected=selected':''; ?>>1</option>
156 <option value="2" <?php echo ($debg == "2") ? 'selected=selected':''; ?>>2</option>
157 <option value="3" <?php echo ($debg == "3") ? 'selected=selected':''; ?>>3</option>
158 <option value="4" <?php echo ($debg == "4") ? 'selected=selected':''; ?>>4</option>
159 </select></b></td>
160
161 </tr>
162
163 <tr>
164
165 <td height="22" bgcolor="#E8E8E8" class="td1">
166
167 <div align="right"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
168 SMTP IP:</font></div>
169
170 </td>
171
172 <td height="22" bgcolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
173
174 <input type="text" id="ip" name="ip" value="" size="30">
175
176 </font></td>
177
178 <td height="22" bgcolor="#E8E8E8" rowspan="2">
179
180 <div align="right">
181 <font face="Verdana, Arial, Helvetica, sans-serif" size="-3">SMTP CONFIG:</font></div>
182 </td>
183
184 <td height="22" bgcolor="#E8E8E8" rowspan="2">
185
186 <textarea readonly type="text" id="my_smtp" name="my_smtp" cols="45" rows="3" style="float:left;"><?php echo $my_smtp;?></textarea><font size="-3" face="Verdana, Arial, Helvetica, sans-serif"><SPAN style="display:block;float:left;"> Every </span><input name="nrotat" type="text" style="width:50px;float:left;" value="<?php echo $nrotat;?>"> EMAIL'S
187
188 </font><br><br><br><input type="button" name="reset" id="reset" value="reset"></td>
189
190 </tr>
191 <tr>
192
193 <td class="td1" height="22" bgcolor="#E8E8E8">
194
195 <div align="right"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
196 SMTP LOGIN:</font></div>
197
198 </td>
199
200 <td height="22" bgcolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
201
202 <input type="text" id="user" name="user" value="" size="30"><br>
203 <input type="password" id="pass" name="pass" value="" size="30"><BR>
204
205
206 </font></td>
207 <td height="22" bgcolor="#E8E8E8">
208
209 </td>
210
211 </tr>
212 <tr>
213
214 <td class="td1" height="22" bgcolor="#E8E8E8">
215
216 <div align="right">
217 <font face="Verdana, Arial, Helvetica, sans-serif" size="-3">Port :</font></div>
218
219 </td>
220
221 <td height="22" bgcolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
222
223 <input type="text" name="ssl_port" id="ssl_port" value="<?php echo $ssl_port;?>" size="5"> <input type="button" name="add" id="add" value="add smtp"></font></td>
224
225 <td height="22" bgcolor="#E8E8E8">
226
227 <div align="right">
228 <font face="Verdana, Arial, Helvetica, sans-serif" size="-3">SEND PAUSE:</font></div>
229
230 </td>
231 <td width="41%" height="22" bgcolor="#E8E8E8" ><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
232
233 <input type="text" name="pause" value="<?php echo $pause;?>" style="width:50px;"/> sec evrey <input type="text" name="pemails" value="<?php echo $pemails;?>" style="width:50px;"/> email's <span style="color:red;">(1 bcc = 1 email)<span>
234
235 </font></td>
236
237 </tr>
238 <tr>
239
240 <td class="td1" height="22" bgcolor="#E8E8E8">
241
242 <p align="right">
243 <font face="Verdana, Arial, Helvetica, sans-serif" size="-3">SSL Server:</font></td>
244
245 <td height="22" bgcolor="#E8E8E8">
246 <input type="radio" name="SSLTLS" value="SSL"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">(SSL)</font>
247 <input type="radio" name="SSLTLS" value="TLS"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">(TLS)</font>
248 <input type="radio" name="SSLTLS" value="NON"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">(NON)</font>
249 </td>
250
251 <td height="22" bgcolor="#E8E8E8">
252
253 <p align="right">
254 <font face="Verdana, Arial, Helvetica, sans-serif" size="-3">RECONNECT
255 AFTER:</font></td>
256
257 <td height="22" bgcolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
258
259 <input type="text" name="reconnect" value="<?php echo $reconnect;?>" size="5">
260 EMAILS</font></td>
261
262 </tr>
263 <tr>
264
265 <td class="td1" height="22" bgcolor="#E8E8E8">
266
267 <p align="right">
268 <font face="Verdana, Arial, Helvetica, sans-serif" size="-3">IS BCC:</font>
269 </td>
270
271 <td height="22" bgcolor="#E8E8E8">
272 <input type="checkbox" name="isbcc" value="true" <?php if($isbcc=="true") echo "checked"; ?> ><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">(yes)</font></td>
273
274 <td height="22" bgcolor="#E8E8E8">
275
276 <p align="right">
277 <font face="Verdana, Arial, Helvetica, sans-serif" size="-3">NUM OF EMAIL IN BCC :</font></td>
278
279 <td height="22" bgcolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
280
281 <input type="text" name="nbcc" value="<?php echo $nbcc;?>" size="5">
282 EMAIL'S</font></td>
283
284 </tr>
285 <tr>
286
287 <td width="100%" height="39" bgcolor="#E8E8E8" colspan="4">
288
289 <p align="center">
290 <font face="Arial" style="font-size: 9pt" color="#800000"><b>"</b> IF
291 YOU DON'T HAVE SMTP LOGIN INFORMATION'S, LEAVE BLANK TO SEND WITH LOCALHOST <b>"</b></font></td>
292
293 </tr>
294
295 <tr>
296
297 <td class="td1" height="19">
298
299 </td>
300
301 <td height="19"> </td>
302
303 <td width="31%" height="19">
304
305 </td>
306
307 <td width="41%" height="19"> </td>
308
309 </tr>
310
311 <tr>
312
313 <td width="100%" colspan="4" bgcolor="#666666" height="36">
314
315 <b>
316
317 <font face="Arial" size="2" color="#FFFFFF"> MESSAGE SETUP</font></b></td>
318
319 </tr>
320
321 <tr>
322
323 <td class="td1" height="22" bordercolor="#E8E8E8" bgcolor="#E8E8E8">
324
325 <div align="right"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
326 Your Email:</font></div>
327
328 </td>
329
330 <td height="22" bordercolor="#E8E8E8" bgcolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
331
332 <input type="text" name="from" value="<?php if(!$lase) echo $from_base;?>" size="30" <?php if($lase) echo "disabled"?> >
333 <input type="checkbox" name="lase" value="true" <?php if($lase) echo "checked"; ?> >EMAIL as LOGIN
334 </font></td>
335
336 <td width="31%" height="22" bordercolor="#E8E8E8" bgcolor="#E8E8E8">
337
338 <div align="right"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
339 Your Name:</font></div>
340
341 </td>
342
343 <td width="41%" height="22" bordercolor="#E8E8E8" bgcolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
344
345 <input type="text" name="realname" value="<?php echo $realname_base;?>" size="30">
346
347 </font></td>
348
349 </tr>
350 <tr>
351
352 <td class="td1" height="22" bgcolor="#E8E8E8" bordercolor="#E8E8E8">
353
354 <div align="right"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
355 Reply-To:</font></div>
356
357 </td>
358
359 <td height="22" bgcolor="#E8E8E8" bordercolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
360
361 <input type="text" name="replyto" value="<?php if(!$repaslog) echo $replyto;?>" size="30" <?php if($repaslog) echo "disabled";?>><input type="checkbox" name="repaslog" value="true" <?php if($repaslog) echo "checked"; ?> >REPLY as LOGIN
362 <input type="checkbox" name="readingconf" value="true" <?php if($reading) echo "checked"; ?> >CONFIRM READING
363 </font></td>
364
365 <td width="31%" height="22" bgcolor="#E8E8E8" bordercolor="#E8E8E8">
366
367 <p align="right"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
368 Email Priority:</font></td>
369
370 <td width="41%" height="22" bgcolor="#E8E8E8" bordercolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
371
372 </font><select name="epriority" id="listMethod" onchange="showHideListConfig()">
373 <option value="" <?php if(strlen($epriority)< 1){print "selected";} ?> >
374 NO PRIORITY</option>
375 <option value="1" <?php if($epriority == "1"){print "selected";} ?> >HIGH</option>
376 <option value="3" <?php if($epriority == "3"){print "selected";} ?> >NORMAL</option>
377 <option value="5" <?php if($epriority == "5"){print "selected";} ?> >LOW</option>
378 </select></td>
379
380 </tr>
381
382 <tr>
383
384 <td class="td1" height="22" bordercolor="#E8E8E8" bgcolor="#E8E8E8">
385
386 <div align="right"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
387 Subject:</font></div>
388
389 </td>
390
391 <td height="22" bordercolor="#E8E8E8" bgcolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
392
393 <input type="text" name="subject" value="<?php echo $subject_base;?>" size="90">
394
395 </font></td><td width="31%" height="22" bgcolor="#E8E8E8" bordercolor="#E8E8E8">
396
397 <p align="right"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
398 <font size="-3" face="Verdana, Arial, Helvetica, sans-serif" color="#FF0000">
399 ENCODE SENDING </font>/ CHARSET :</font></td><td width="41%" height="22" bgcolor="#E8E8E8" bordercolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
400
401 </font><select size="1" name="encodety">
402 <option value="no" <?php if($encodety == "no"){print "selected";} ?>>NO</option>
403 <option value="8bit" <?php if($encodety == "8bit"){print "selected";} ?>>8bit</option>
404 <option value="7bit" <?php if($encodety == "7bit"){print "selected";} ?>>7bit</option>
405 <option value="binary" <?php if($encodety == "binary"){print "selected";} ?>>binary</option>
406 <option value="base64" <?php if($encodety == "base64"){print "selected";} ?>>base64</option>
407 <option value="quoted-printable" <?php if($encodety == "quoted-printable"){print "selected";} ?>>quoted-printable</option>
408 </select><select name="epriority" id="listMethod" onchange="showHideListConfig()">
409 <option value="" selected="">NO CHARSET</option>
410 <option value="us-ascii">Unicode -> us-ascii</option>
411 <option value="utf-7">Unicode -> utf-7</option>
412 <option value="utf-8">Unicode -> utf-8</option>
413 <option value="iso-10646-ucs-2">Unicode -> iso-10646-ucs-2</option>
414 <option value="iso-8859-6">Arabic -> iso-8859-6</option>
415 <option value="x-mac-arabic">Arabic -> x-mac-arabic</option>
416 <option value="windows-1256">Arabic -> windows-1256</option>
417 <option value="iso-8859-4">Baltic -> iso-8859-4</option>
418 <option value="windows-1257">Baltic -> windows-1257</option>
419 <option value="iso-8859-2">Central European -> iso-8859-2</option>
420 <option value="x-mac-ce">Central European -> x-mac-ce</option>
421 <option value="windows-1250">Central European -> windows-1250</option>
422 <option value="euc-cn">Chinese -> euc-cn</option>
423 <option value="gb2312">Chinese -> gb2312</option>
424 <option value="hz-gb-2312">Chinese -> hz-gb-2312 </option>
425 <option value="x-mac-chinesesimp">Chinese -> x-mac-chinesesimp</option>
426 <option value="cp-936">Chinese -> cp-936</option>
427 <option value="big5">Chinese -> big5</option>
428 <option value="x-mac-chinesetrad">Chinese -> x-mac-chinesetrad</option>
429 <option value="cp-950">Chinese -> cp-950</option>
430 <option value="cp-932">Chinese -> cp-932</option>
431 <option value="euc-tw">Chinese -> euc-tw</option>
432 </select></td>
433
434 </tr>
435
436 <tr>
437
438 <td class="td1" height="22" bordercolor="#E8E8E8" bgcolor="#E8E8E8">
439
440 <div align="right"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
441 Generateur:</font></div></td>
442
443 <td width="35%" colspan="" height="22" bordercolor="#E8E8E8" bgcolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
444 (a-z)<input type="checkbox" name="az" id="az">
445 (A-Z)<input type="checkbox" name="AZ" id="AZ">
446 (0-9)<input type="checkbox" name="09" id="09">
447 (LENHGT)<input type="text" maxlength=2 size=1 name="len" id="len">
448 (#PATTERN)<input type="text" name="patval" id="patval">
449 <input type="button" value="GET PATTERN" id="patb" name="patb">
450 </td>
451 <td width="31%" height="22" bgcolor="#E8E8E8" bordercolor="#E8E8E8">
452
453 <p align="right"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
454 <font size="-3" face="Verdana, Arial, Helvetica, sans-serif" >
455 ATTACH :</font>
456 </td>
457 <td width="41%" height="22" bgcolor="#E8E8E8" bordercolor="#E8E8E8"></font><input name="userfile" type="file"></td>
458 </tr>
459
460 <tr valign="top">
461
462<td colspan="3" height="190" bordercolor="#E8E8E8" bgcolor="#E8E8E8"><font size="-1" face="Verdana, Arial, Helvetica, sans-serif">
463
464 <textarea name="message" value=""cols="60" rows="10"><?php echo $message_base;?></textarea>
465
466 <br>
467
468 <input type="radio" name="contenttype" value="plain" >
469
470 TEXT
471
472 <input type="radio" name="contenttype" value="html" checked>
473
474 HTML
475
476 <input type="hidden" name="action" value="send">
477
478 <input type="submit" value="Send Message">
479
480 </font></td>
481
482 <td width="41%" height="190" bordercolor="#E8E8E8" bgcolor="#E8E8E8"><font size="-3" face="Verdana, Arial, Helvetica, sans-serif">
483
484 <textarea name="emaillist" value="" cols="30" rows="10"><?php echo $emaillist;?></textarea>
485
486 </font></td>
487
488 </tr>
489
490 </table>
491
492</form>
493
494<?php print "<p class=\"style1\">PHP Mailer © 2017, <b><font color=\"#800000\">BY RFX</font><span style=\"color:red\"> SKYPE: KIMONO238<br></span></b></p>"; ?>
495 </body>
496</html>
497
498
499<?php
500
501
502
503class SMTP
504{
505 /**
506 * The PHPMailer SMTP version number.
507 * @var string
508 */
509 const VERSION = '5.2.17';
510 /**
511 * SMTP line break constant.
512 * @var string
513 */
514 const CRLF = "\r\n";
515 /**
516 * The SMTP port to use if one is not specified.
517 * @var integer
518 */
519 const DEFAULT_SMTP_PORT = 25;
520 /**
521 * The maximum line length allowed by RFC 2822 section 2.1.1
522 * @var integer
523 */
524 const MAX_LINE_LENGTH = 998;
525 /**
526 * Debug level for no output
527 */
528 const DEBUG_OFF = 0;
529 /**
530 * Debug level to show client -> server messages
531 */
532 const DEBUG_CLIENT = 1;
533 /**
534 * Debug level to show client -> server and server -> client messages
535 */
536 const DEBUG_SERVER = 2;
537 /**
538 * Debug level to show connection status, client -> server and server -> client messages
539 */
540 const DEBUG_CONNECTION = 3;
541 /**
542 * Debug level to show all messages
543 */
544 const DEBUG_LOWLEVEL = 4;
545 /**
546 * The PHPMailer SMTP Version number.
547 * @var string
548 * @deprecated Use the `VERSION` constant instead
549 * @see SMTP::VERSION
550 */
551 public $Version = '5.2.17';
552 /**
553 * SMTP server port number.
554 * @var integer
555 * @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead
556 * @see SMTP::DEFAULT_SMTP_PORT
557 */
558 public $SMTP_PORT = 25;
559 /**
560 * SMTP reply line ending.
561 * @var string
562 * @deprecated Use the `CRLF` constant instead
563 * @see SMTP::CRLF
564 */
565 public $CRLF = "\r\n";
566 /**
567 * Debug output level.
568 * Options:
569 * * self::DEBUG_OFF (`0`) No debug output, default
570 * * self::DEBUG_CLIENT (`1`) Client commands
571 * * self::DEBUG_SERVER (`2`) Client commands and server responses
572 * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
573 * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages
574 * @var integer
575 */
576 public $do_debug = self::DEBUG_OFF;
577 /**
578 * How to handle debug output.
579 * Options:
580 * * `echo` Output plain-text as-is, appropriate for CLI
581 * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
582 * * `error_log` Output to error log as configured in php.ini
583 *
584 * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
585 * <code>
586 * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
587 * </code>
588 * @var string|callable
589 */
590 public $Debugoutput = 'echo';
591 /**
592 * Whether to use VERP.
593 * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
594 * @link http://www.postfix.org/VERP_README.html Info on VERP
595 * @var boolean
596 */
597 public $do_verp = false;
598 /**
599 * The timeout value for connection, in seconds.
600 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
601 * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
602 * @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2
603 * @var integer
604 */
605 public $Timeout = 300;
606 /**
607 * How long to wait for commands to complete, in seconds.
608 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
609 * @var integer
610 */
611 public $Timelimit = 300;
612 /**
613 * @var array patterns to extract smtp transaction id from smtp reply
614 * Only first capture group will be use, use non-capturing group to deal with it
615 * Extend this class to override this property to fulfil your needs.
616 */
617 protected $smtp_transaction_id_patterns = array(
618 'exim' => '/[0-9]{3} OK id=(.*)/',
619 'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/',
620 'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/'
621 );
622 /**
623 * The socket for the server connection.
624 * @var resource
625 */
626 protected $smtp_conn;
627 /**
628 * Error information, if any, for the last SMTP command.
629 * @var array
630 */
631 protected $error = array(
632 'error' => '',
633 'detail' => '',
634 'smtp_code' => '',
635 'smtp_code_ex' => ''
636 );
637 /**
638 * The reply the server sent to us for HELO.
639 * If null, no HELO string has yet been received.
640 * @var string|null
641 */
642 protected $helo_rply = null;
643 /**
644 * The set of SMTP extensions sent in reply to EHLO command.
645 * Indexes of the array are extension names.
646 * Value at index 'HELO' or 'EHLO' (according to command that was sent)
647 * represents the server name. In case of HELO it is the only element of the array.
648 * Other values can be boolean TRUE or an array containing extension options.
649 * If null, no HELO/EHLO string has yet been received.
650 * @var array|null
651 */
652 protected $server_caps = null;
653 /**
654 * The most recent reply received from the server.
655 * @var string
656 */
657 protected $last_reply = '';
658 /**
659 * Output debugging info via a user-selected method.
660 * @see SMTP::$Debugoutput
661 * @see SMTP::$do_debug
662 * @param string $str Debug string to output
663 * @param integer $level The debug level of this message; see DEBUG_* constants
664 * @return void
665 */
666 protected function edebug($str, $level = 0)
667 {
668 if ($level > $this->do_debug) {
669 return;
670 }
671 //Avoid clash with built-in function names
672 if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
673 call_user_func($this->Debugoutput, $str, $level);
674 return;
675 }
676 switch ($this->Debugoutput) {
677 case 'error_log':
678 //Don't output, just log
679 error_log($str);
680 break;
681 case 'html':
682 //Cleans up output a bit for a better looking, HTML-safe output
683 echo htmlentities(
684 preg_replace('/[\r\n]+/', '', $str),
685 ENT_QUOTES,
686 'UTF-8'
687 )
688 . "<br>\n";
689 break;
690 case 'echo':
691 default:
692 //Normalize line breaks
693 $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
694 echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
695 "\n",
696 "\n \t ",
697 trim($str)
698 )."\n";
699 }
700 }
701 /**
702 * Connect to an SMTP server.
703 * @param string $host SMTP server IP or host name
704 * @param integer $port The port number to connect to
705 * @param integer $timeout How long to wait for the connection to open
706 * @param array $options An array of options for stream_context_create()
707 * @access public
708 * @return boolean
709 */
710 public function connect($host, $port = null, $timeout = 30, $options = array())
711 {
712 if(count($options)==0)
713 {
714 $options["ssl"]=array("verify_peer"=>false,"verify_peer_name"=>false,"allow_self_signed"=>true);
715 }
716 static $streamok;
717 //This is enabled by default since 5.0.0 but some providers disable it
718 //Check this once and cache the result
719 if (is_null($streamok)) {
720 $streamok = function_exists('stream_socket_client');
721 }
722 // Clear errors to avoid confusion
723 $this->setError('');
724 // Make sure we are __not__ connected
725 if ($this->connected()) {
726 // Already connected, generate error
727 $this->setError('Already connected to a server');
728 return false;
729 }
730 if (empty($port)) {
731 $port = self::DEFAULT_SMTP_PORT;
732 }
733 // Connect to the SMTP server
734 $this->edebug(
735 "Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true),
736 self::DEBUG_CONNECTION
737 );
738 $errno = 0;
739 $errstr = '';
740 if ($streamok) {
741 $socket_context = stream_context_create($options);
742 set_error_handler(array($this, 'errorHandler'));
743 $this->smtp_conn = stream_socket_client(
744 $host . ":" . $port,
745 $errno,
746 $errstr,
747 $timeout,
748 STREAM_CLIENT_CONNECT,
749 $socket_context
750 );
751 restore_error_handler();
752 } else {
753 //Fall back to fsockopen which should work in more places, but is missing some features
754 $this->edebug(
755 "Connection: stream_socket_client not available, falling back to fsockopen",
756 self::DEBUG_CONNECTION
757 );
758 set_error_handler(array($this, 'errorHandler'));
759 $this->smtp_conn = fsockopen(
760 $host,
761 $port,
762 $errno,
763 $errstr,
764 $timeout
765 );
766 restore_error_handler();
767 }
768 // Verify we connected properly
769 if (!is_resource($this->smtp_conn)) {
770 $this->setError(
771 'Failed to connect to server',
772 $errno,
773 $errstr
774 );
775 $this->edebug(
776 'SMTP ERROR: ' . $this->error['error']
777 . ": $errstr ($errno)",
778 self::DEBUG_CLIENT
779 );
780 return false;
781 }
782 $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
783 // SMTP server can take longer to respond, give longer timeout for first read
784 // Windows does not have support for this timeout function
785 if (substr(PHP_OS, 0, 3) != 'WIN') {
786 $max = ini_get('max_execution_time');
787 // Don't bother if unlimited
788 if ($max != 0 && $timeout > $max) {
789 @set_time_limit($timeout);
790 }
791 stream_set_timeout($this->smtp_conn, $timeout, 0);
792 }
793 // Get any announcement
794 $announce = $this->get_lines();
795 $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
796 return true;
797 }
798 /**
799 * Initiate a TLS (encrypted) session.
800 * @access public
801 * @return boolean
802 */
803 public function startTLS()
804 {
805 if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
806 return false;
807 }
808 //Allow the best TLS version(s) we can
809 $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
810 //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
811 //so add them back in manually if we can
812 if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
813 $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
814 $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
815 }
816 // Begin encrypted connection
817 if (!stream_socket_enable_crypto(
818 $this->smtp_conn,
819 true,
820 $crypto_method
821 )) {
822 return false;
823 }
824 return true;
825 }
826 /**
827 * Perform SMTP authentication.
828 * Must be run after hello().
829 * @see hello()
830 * @param string $username The user name
831 * @param string $password The password
832 * @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5, XOAUTH2)
833 * @param string $realm The auth realm for NTLM
834 * @param string $workstation The auth workstation for NTLM
835 * @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth)
836 * @return bool True if successfully authenticated.* @access public
837 */
838 public function authenticate(
839 $username,
840 $password,
841 $authtype = null,
842 $realm = '',
843 $workstation = '',
844 $OAuth = null
845 ) {
846 if (!$this->server_caps) {
847 $this->setError('Authentication is not allowed before HELO/EHLO');
848 return false;
849 }
850 if (array_key_exists('EHLO', $this->server_caps)) {
851 // SMTP extensions are available. Let's try to find a proper authentication method
852 if (!array_key_exists('AUTH', $this->server_caps)) {
853 $this->setError('Authentication is not allowed at this stage');
854 // 'at this stage' means that auth may be allowed after the stage changes
855 // e.g. after STARTTLS
856 return false;
857 }
858 self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL);
859 self::edebug(
860 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
861 self::DEBUG_LOWLEVEL
862 );
863 if (empty($authtype)) {
864 foreach (array('CRAM-MD5', 'LOGIN', 'PLAIN', 'NTLM', 'XOAUTH2') as $method) {
865 if (in_array($method, $this->server_caps['AUTH'])) {
866 $authtype = $method;
867 break;
868 }
869 }
870 if (empty($authtype)) {
871 $this->setError('No supported authentication methods found');
872 return false;
873 }
874 self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL);
875 }
876 if (!in_array($authtype, $this->server_caps['AUTH'])) {
877 $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
878 return false;
879 }
880 } elseif (empty($authtype)) {
881 $authtype = 'LOGIN';
882 }
883 switch ($authtype) {
884 case 'PLAIN':
885 // Start authentication
886 if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
887 return false;
888 }
889 // Send encoded username and password
890 if (!$this->sendCommand(
891 'User & Password',
892 base64_encode("\0" . $username . "\0" . $password),
893 235
894 )
895 ) {
896 return false;
897 }
898 break;
899 case 'LOGIN':
900 // Start authentication
901 if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
902 return false;
903 }
904 if (!$this->sendCommand("Username", base64_encode($username), 334)) {
905 return false;
906 }
907 if (!$this->sendCommand("Password", base64_encode($password), 235)) {
908 return false;
909 }
910 break;
911 case 'XOAUTH2':
912 //If the OAuth Instance is not set. Can be a case when PHPMailer is used
913 //instead of PHPMailerOAuth
914 if (is_null($OAuth)) {
915 return false;
916 }
917 $oauth = $OAuth->getOauth64();
918 // Start authentication
919 if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
920 return false;
921 }
922 break;
923 case 'NTLM':
924 /*
925 * ntlm_sasl_client.php
926 * Bundled with Permission
927 *
928 * How to telnet in windows:
929 * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
930 * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
931 */
932 require_once 'extras/ntlm_sasl_client.php';
933 $temp = new stdClass;
934 $ntlm_client = new ntlm_sasl_client_class;
935 //Check that functions are available
936 if (!$ntlm_client->initialize($temp)) {
937 $this->setError($temp->error);
938 $this->edebug(
939 'You need to enable some modules in your php.ini file: '
940 . $this->error['error'],
941 self::DEBUG_CLIENT
942 );
943 return false;
944 }
945 //msg1
946 $msg1 = $ntlm_client->typeMsg1($realm, $workstation); //msg1
947 if (!$this->sendCommand(
948 'AUTH NTLM',
949 'AUTH NTLM ' . base64_encode($msg1),
950 334
951 )
952 ) {
953 return false;
954 }
955 //Though 0 based, there is a white space after the 3 digit number
956 //msg2
957 $challenge = substr($this->last_reply, 3);
958 $challenge = base64_decode($challenge);
959 $ntlm_res = $ntlm_client->NTLMResponse(
960 substr($challenge, 24, 8),
961 $password
962 );
963 //msg3
964 $msg3 = $ntlm_client->typeMsg3(
965 $ntlm_res,
966 $username,
967 $realm,
968 $workstation
969 );
970 // send encoded username
971 return $this->sendCommand('Username', base64_encode($msg3), 235);
972 case 'CRAM-MD5':
973 // Start authentication
974 if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
975 return false;
976 }
977 // Get the challenge
978 $challenge = base64_decode(substr($this->last_reply, 4));
979 // Build the response
980 $response = $username . ' ' . $this->hmac($challenge, $password);
981 // send encoded credentials
982 return $this->sendCommand('Username', base64_encode($response), 235);
983 default:
984 $this->setError("Authentication method \"$authtype\" is not supported");
985 return false;
986 }
987 return true;
988 }
989 /**
990 * Calculate an MD5 HMAC hash.
991 * Works like hash_hmac('md5', $data, $key)
992 * in case that function is not available
993 * @param string $data The data to hash
994 * @param string $key The key to hash with
995 * @access protected
996 * @return string
997 */
998 protected function hmac($data, $key)
999 {
1000 if (function_exists('hash_hmac')) {
1001 return hash_hmac('md5', $data, $key);
1002 }
1003 // The following borrowed from
1004 // http://php.net/manual/en/function.mhash.php#27225
1005 // RFC 2104 HMAC implementation for php.
1006 // Creates an md5 HMAC.
1007 // Eliminates the need to install mhash to compute a HMAC
1008 // by Lance Rushing
1009 $bytelen = 64; // byte length for md5
1010 if (strlen($key) > $bytelen) {
1011 $key = pack('H*', md5($key));
1012 }
1013 $key = str_pad($key, $bytelen, chr(0x00));
1014 $ipad = str_pad('', $bytelen, chr(0x36));
1015 $opad = str_pad('', $bytelen, chr(0x5c));
1016 $k_ipad = $key ^ $ipad;
1017 $k_opad = $key ^ $opad;
1018 return md5($k_opad . pack('H*', md5($k_ipad . $data)));
1019 }
1020 /**
1021 * Check connection state.
1022 * @access public
1023 * @return boolean True if connected.
1024 */
1025 public function connected()
1026 {
1027 if (is_resource($this->smtp_conn)) {
1028 $sock_status = stream_get_meta_data($this->smtp_conn);
1029 if ($sock_status['eof']) {
1030 // The socket is valid but we are not connected
1031 $this->edebug(
1032 'SMTP NOTICE: EOF caught while checking if connected',
1033 self::DEBUG_CLIENT
1034 );
1035 $this->close();
1036 return false;
1037 }
1038 return true; // everything looks good
1039 }
1040 return false;
1041 }
1042 /**
1043 * Close the socket and clean up the state of the class.
1044 * Don't use this function without first trying to use QUIT.
1045 * @see quit()
1046 * @access public
1047 * @return void
1048 */
1049 public function close()
1050 {
1051 $this->setError('');
1052 $this->server_caps = null;
1053 $this->helo_rply = null;
1054 if (is_resource($this->smtp_conn)) {
1055 // close the connection and cleanup
1056 fclose($this->smtp_conn);
1057 $this->smtp_conn = null; //Makes for cleaner serialization
1058 $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
1059 }
1060 }
1061 /**
1062 * Send an SMTP DATA command.
1063 * Issues a data command and sends the msg_data to the server,
1064 * finializing the mail transaction. $msg_data is the message
1065 * that is to be send with the headers. Each header needs to be
1066 * on a single line followed by a <CRLF> with the message headers
1067 * and the message body being separated by and additional <CRLF>.
1068 * Implements rfc 821: DATA <CRLF>
1069 * @param string $msg_data Message data to send
1070 * @access public
1071 * @return boolean
1072 */
1073 public function data($msg_data)
1074 {
1075 //This will use the standard timelimit
1076 if (!$this->sendCommand('DATA', 'DATA', 354)) {
1077 return false;
1078 }
1079 /* The server is ready to accept data!
1080 * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
1081 * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
1082 * smaller lines to fit within the limit.
1083 * We will also look for lines that start with a '.' and prepend an additional '.'.
1084 * NOTE: this does not count towards line-length limit.
1085 */
1086 // Normalize line breaks before exploding
1087 $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
1088 /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
1089 * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
1090 * process all lines before a blank line as headers.
1091 */
1092 $field = substr($lines[0], 0, strpos($lines[0], ':'));
1093 $in_headers = false;
1094 if (!empty($field) && strpos($field, ' ') === false) {
1095 $in_headers = true;
1096 }
1097 foreach ($lines as $line) {
1098 $lines_out = array();
1099 if ($in_headers and $line == '') {
1100 $in_headers = false;
1101 }
1102 //Break this line up into several smaller lines if it's too long
1103 //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
1104 while (isset($line[self::MAX_LINE_LENGTH])) {
1105 //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
1106 //so as to avoid breaking in the middle of a word
1107 $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
1108 //Deliberately matches both false and 0
1109 if (!$pos) {
1110 //No nice break found, add a hard break
1111 $pos = self::MAX_LINE_LENGTH - 1;
1112 $lines_out[] = substr($line, 0, $pos);
1113 $line = substr($line, $pos);
1114 } else {
1115 //Break at the found point
1116 $lines_out[] = substr($line, 0, $pos);
1117 //Move along by the amount we dealt with
1118 $line = substr($line, $pos + 1);
1119 }
1120 //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
1121 if ($in_headers) {
1122 $line = "\t" . $line;
1123 }
1124 }
1125 $lines_out[] = $line;
1126 //Send the lines to the server
1127 foreach ($lines_out as $line_out) {
1128 //RFC2821 section 4.5.2
1129 if (!empty($line_out) and $line_out[0] == '.') {
1130 $line_out = '.' . $line_out;
1131 }
1132 $this->client_send($line_out . self::CRLF);
1133 }
1134 }
1135 //Message data has been sent, complete the command
1136 //Increase timelimit for end of DATA command
1137 $savetimelimit = $this->Timelimit;
1138 $this->Timelimit = $this->Timelimit * 2;
1139 $result = $this->sendCommand('DATA END', '.', 250);
1140 //Restore timelimit
1141 $this->Timelimit = $savetimelimit;
1142 return $result;
1143 }
1144 /**
1145 * Send an SMTP HELO or EHLO command.
1146 * Used to identify the sending server to the receiving server.
1147 * This makes sure that client and server are in a known state.
1148 * Implements RFC 821: HELO <SP> <domain> <CRLF>
1149 * and RFC 2821 EHLO.
1150 * @param string $host The host name or IP to connect to
1151 * @access public
1152 * @return boolean
1153 */
1154 public function hello($host = '')
1155 {
1156 //Try extended hello first (RFC 2821)
1157 return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
1158 }
1159 /**
1160 * Send an SMTP HELO or EHLO command.
1161 * Low-level implementation used by hello()
1162 * @see hello()
1163 * @param string $hello The HELO string
1164 * @param string $host The hostname to say we are
1165 * @access protected
1166 * @return boolean
1167 */
1168 protected function sendHello($hello, $host)
1169 {
1170 $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
1171 $this->helo_rply = $this->last_reply;
1172 if ($noerror) {
1173 $this->parseHelloFields($hello);
1174 } else {
1175 $this->server_caps = null;
1176 }
1177 return $noerror;
1178 }
1179 /**
1180 * Parse a reply to HELO/EHLO command to discover server extensions.
1181 * In case of HELO, the only parameter that can be discovered is a server name.
1182 * @access protected
1183 * @param string $type - 'HELO' or 'EHLO'
1184 */
1185 protected function parseHelloFields($type)
1186 {
1187 $this->server_caps = array();
1188 $lines = explode("\n", $this->helo_rply);
1189 foreach ($lines as $n => $s) {
1190 //First 4 chars contain response code followed by - or space
1191 $s = trim(substr($s, 4));
1192 if (empty($s)) {
1193 continue;
1194 }
1195 $fields = explode(' ', $s);
1196 if (!empty($fields)) {
1197 if (!$n) {
1198 $name = $type;
1199 $fields = $fields[0];
1200 } else {
1201 $name = array_shift($fields);
1202 switch ($name) {
1203 case 'SIZE':
1204 $fields = ($fields ? $fields[0] : 0);
1205 break;
1206 case 'AUTH':
1207 if (!is_array($fields)) {
1208 $fields = array();
1209 }
1210 break;
1211 default:
1212 $fields = true;
1213 }
1214 }
1215 $this->server_caps[$name] = $fields;
1216 }
1217 }
1218 }
1219 /**
1220 * Send an SMTP MAIL command.
1221 * Starts a mail transaction from the email address specified in
1222 * $from. Returns true if successful or false otherwise. If True
1223 * the mail transaction is started and then one or more recipient
1224 * commands may be called followed by a data command.
1225 * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
1226 * @param string $from Source address of this message
1227 * @access public
1228 * @return boolean
1229 */
1230 public function mail($from)
1231 {
1232 $useVerp = ($this->do_verp ? ' XVERP' : '');
1233 return $this->sendCommand(
1234 'MAIL FROM',
1235 'MAIL FROM:<' . $from . '>' . $useVerp,
1236 250
1237 );
1238 }
1239 /**
1240 * Send an SMTP QUIT command.
1241 * Closes the socket if there is no error or the $close_on_error argument is true.
1242 * Implements from rfc 821: QUIT <CRLF>
1243 * @param boolean $close_on_error Should the connection close if an error occurs?
1244 * @access public
1245 * @return boolean
1246 */
1247 public function quit($close_on_error = true)
1248 {
1249 $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
1250 $err = $this->error; //Save any error
1251 if ($noerror or $close_on_error) {
1252 $this->close();
1253 $this->error = $err; //Restore any error from the quit command
1254 }
1255 return $noerror;
1256 }
1257 /**
1258 * Send an SMTP RCPT command.
1259 * Sets the TO argument to $toaddr.
1260 * Returns true if the recipient was accepted false if it was rejected.
1261 * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
1262 * @param string $address The address the message is being sent to
1263 * @access public
1264 * @return boolean
1265 */
1266 public function recipient($address)
1267 {
1268 return $this->sendCommand(
1269 'RCPT TO',
1270 'RCPT TO:<' . $address . '>',
1271 array(250, 251)
1272 );
1273 }
1274 /**
1275 * Send an SMTP RSET command.
1276 * Abort any transaction that is currently in progress.
1277 * Implements rfc 821: RSET <CRLF>
1278 * @access public
1279 * @return boolean True on success.
1280 */
1281 public function reset()
1282 {
1283 return $this->sendCommand('RSET', 'RSET', 250);
1284 }
1285 /**
1286 * Send a command to an SMTP server and check its return code.
1287 * @param string $command The command name - not sent to the server
1288 * @param string $commandstring The actual command to send
1289 * @param integer|array $expect One or more expected integer success codes
1290 * @access protected
1291 * @return boolean True on success.
1292 */
1293 protected function sendCommand($command, $commandstring, $expect)
1294 {
1295 if (!$this->connected()) {
1296 $this->setError("Called $command without being connected");
1297 return false;
1298 }
1299 //Reject line breaks in all commands
1300 if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) {
1301 $this->setError("Command '$command' contained line breaks");
1302 return false;
1303 }
1304 $this->client_send($commandstring . self::CRLF);
1305 $this->last_reply = $this->get_lines();
1306 // Fetch SMTP code and possible error code explanation
1307 $matches = array();
1308 if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) {
1309 $code = $matches[1];
1310 $code_ex = (count($matches) > 2 ? $matches[2] : null);
1311 // Cut off error code from each response line
1312 $detail = preg_replace(
1313 "/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m",
1314 '',
1315 $this->last_reply
1316 );
1317 } else {
1318 // Fall back to simple parsing if regex fails
1319 $code = substr($this->last_reply, 0, 3);
1320 $code_ex = null;
1321 $detail = substr($this->last_reply, 4);
1322 }
1323 $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
1324 if (!in_array($code, (array)$expect)) {
1325 $this->setError(
1326 "$command command failed",
1327 $detail,
1328 $code,
1329 $code_ex
1330 );
1331 $this->edebug(
1332 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
1333 self::DEBUG_CLIENT
1334 );
1335 return false;
1336 }
1337 $this->setError('');
1338 return true;
1339 }
1340 /**
1341 * Send an SMTP SAML command.
1342 * Starts a mail transaction from the email address specified in $from.
1343 * Returns true if successful or false otherwise. If True
1344 * the mail transaction is started and then one or more recipient
1345 * commands may be called followed by a data command. This command
1346 * will send the message to the users terminal if they are logged
1347 * in and send them an email.
1348 * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
1349 * @param string $from The address the message is from
1350 * @access public
1351 * @return boolean
1352 */
1353 public function sendAndMail($from)
1354 {
1355 return $this->sendCommand('SAML', "SAML FROM:$from", 250);
1356 }
1357 /**
1358 * Send an SMTP VRFY command.
1359 * @param string $name The name to verify
1360 * @access public
1361 * @return boolean
1362 */
1363 public function verify($name)
1364 {
1365 return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
1366 }
1367 /**
1368 * Send an SMTP NOOP command.
1369 * Used to keep keep-alives alive, doesn't actually do anything
1370 * @access public
1371 * @return boolean
1372 */
1373 public function noop()
1374 {
1375 return $this->sendCommand('NOOP', 'NOOP', 250);
1376 }
1377 /**
1378 * Send an SMTP TURN command.
1379 * This is an optional command for SMTP that this class does not support.
1380 * This method is here to make the RFC821 Definition complete for this class
1381 * and _may_ be implemented in future
1382 * Implements from rfc 821: TURN <CRLF>
1383 * @access public
1384 * @return boolean
1385 */
1386 public function turn()
1387 {
1388 $this->setError('The SMTP TURN command is not implemented');
1389 $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
1390 return false;
1391 }
1392 /**
1393 * Send raw data to the server.
1394 * @param string $data The data to send
1395 * @access public
1396 * @return integer|boolean The number of bytes sent to the server or false on error
1397 */
1398 public function client_send($data)
1399 {
1400 $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
1401 set_error_handler(array($this, 'errorHandler'));
1402 $result = fwrite($this->smtp_conn, $data);
1403 restore_error_handler();
1404 return $result;
1405 }
1406 /**
1407 * Get the latest error.
1408 * @access public
1409 * @return array
1410 */
1411 public function getError()
1412 {
1413 return $this->error;
1414 }
1415 /**
1416 * Get SMTP extensions available on the server
1417 * @access public
1418 * @return array|null
1419 */
1420 public function getServerExtList()
1421 {
1422 return $this->server_caps;
1423 }
1424 /**
1425 * A multipurpose method
1426 * The method works in three ways, dependent on argument value and current state
1427 * 1. HELO/EHLO was not sent - returns null and set up $this->error
1428 * 2. HELO was sent
1429 * $name = 'HELO': returns server name
1430 * $name = 'EHLO': returns boolean false
1431 * $name = any string: returns null and set up $this->error
1432 * 3. EHLO was sent
1433 * $name = 'HELO'|'EHLO': returns server name
1434 * $name = any string: if extension $name exists, returns boolean True
1435 * or its options. Otherwise returns boolean False
1436 * In other words, one can use this method to detect 3 conditions:
1437 * - null returned: handshake was not or we don't know about ext (refer to $this->error)
1438 * - false returned: the requested feature exactly not exists
1439 * - positive value returned: the requested feature exists
1440 * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
1441 * @return mixed
1442 */
1443 public function getServerExt($name)
1444 {
1445 if (!$this->server_caps) {
1446 $this->setError('No HELO/EHLO was sent');
1447 return null;
1448 }
1449 // the tight logic knot ;)
1450 if (!array_key_exists($name, $this->server_caps)) {
1451 if ($name == 'HELO') {
1452 return $this->server_caps['EHLO'];
1453 }
1454 if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) {
1455 return false;
1456 }
1457 $this->setError('HELO handshake was used. Client knows nothing about server extensions');
1458 return null;
1459 }
1460 return $this->server_caps[$name];
1461 }
1462 /**
1463 * Get the last reply from the server.
1464 * @access public
1465 * @return string
1466 */
1467 public function getLastReply()
1468 {
1469 return $this->last_reply;
1470 }
1471 /**
1472 * Read the SMTP server's response.
1473 * Either before eof or socket timeout occurs on the operation.
1474 * With SMTP we can tell if we have more lines to read if the
1475 * 4th character is '-' symbol. If it is a space then we don't
1476 * need to read anything else.
1477 * @access protected
1478 * @return string
1479 */
1480 protected function get_lines()
1481 {
1482 // If the connection is bad, give up straight away
1483 if (!is_resource($this->smtp_conn)) {
1484 return '';
1485 }
1486 $data = '';
1487 $endtime = 0;
1488 stream_set_timeout($this->smtp_conn, $this->Timeout);
1489 if ($this->Timelimit > 0) {
1490 $endtime = time() + $this->Timelimit;
1491 }
1492 while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
1493 $str = @fgets($this->smtp_conn, 515);
1494 $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
1495 $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
1496 $data .= $str;
1497 // If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen
1498 if (!isset($str[3]) or (isset($str[3]) and $str[3] == ' ')) {
1499 break;
1500 }
1501 // Timed-out? Log and break
1502 $info = stream_get_meta_data($this->smtp_conn);
1503 if ($info['timed_out']) {
1504 $this->edebug(
1505 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
1506 self::DEBUG_LOWLEVEL
1507 );
1508 break;
1509 }
1510 // Now check if reads took too long
1511 if ($endtime and time() > $endtime) {
1512 $this->edebug(
1513 'SMTP -> get_lines(): timelimit reached ('.
1514 $this->Timelimit . ' sec)',
1515 self::DEBUG_LOWLEVEL
1516 );
1517 break;
1518 }
1519 }
1520 return $data;
1521 }
1522 /**
1523 * Enable or disable VERP address generation.
1524 * @param boolean $enabled
1525 */
1526 public function setVerp($enabled = false)
1527 {
1528 $this->do_verp = $enabled;
1529 }
1530 /**
1531 * Get VERP address generation mode.
1532 * @return boolean
1533 */
1534 public function getVerp()
1535 {
1536 return $this->do_verp;
1537 }
1538 /**
1539 * Set error messages and codes.
1540 * @param string $message The error message
1541 * @param string $detail Further detail on the error
1542 * @param string $smtp_code An associated SMTP error code
1543 * @param string $smtp_code_ex Extended SMTP code
1544 */
1545 protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
1546 {
1547 $this->error = array(
1548 'error' => $message,
1549 'detail' => $detail,
1550 'smtp_code' => $smtp_code,
1551 'smtp_code_ex' => $smtp_code_ex
1552 );
1553 }
1554 /**
1555 * Set debug output method.
1556 * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
1557 */
1558 public function setDebugOutput($method = 'echo')
1559 {
1560 $this->Debugoutput = $method;
1561 }
1562 /**
1563 * Get debug output method.
1564 * @return string
1565 */
1566 public function getDebugOutput()
1567 {
1568 return $this->Debugoutput;
1569 }
1570 /**
1571 * Set debug output level.
1572 * @param integer $level
1573 */
1574 public function setDebugLevel($level = 0)
1575 {
1576 $this->do_debug = $level;
1577 }
1578 /**
1579 * Get debug output level.
1580 * @return integer
1581 */
1582 public function getDebugLevel()
1583 {
1584 return $this->do_debug;
1585 }
1586 /**
1587 * Set SMTP timeout.
1588 * @param integer $timeout
1589 */
1590 public function setTimeout($timeout = 0)
1591 {
1592 $this->Timeout = $timeout;
1593 }
1594 /**
1595 * Get SMTP timeout.
1596 * @return integer
1597 */
1598 public function getTimeout()
1599 {
1600 return $this->Timeout;
1601 }
1602 /**
1603 * Reports an error number and string.
1604 * @param integer $errno The error number returned by PHP.
1605 * @param string $errmsg The error message returned by PHP.
1606 */
1607 protected function errorHandler($errno, $errmsg)
1608 {
1609 $notice = 'Connection: Failed to connect to server.';
1610 $this->setError(
1611 $notice,
1612 $errno,
1613 $errmsg
1614 );
1615 $this->edebug(
1616 $notice . ' Error number ' . $errno . '. "Error notice: ' . $errmsg,
1617 self::DEBUG_CONNECTION
1618 );
1619 }
1620 /**
1621 * Will return the ID of the last smtp transaction based on a list of patterns provided
1622 * in SMTP::$smtp_transaction_id_patterns.
1623 * If no reply has been received yet, it will return null.
1624 * If no pattern has been matched, it will return false.
1625 * @return bool|null|string
1626 */
1627 public function getLastTransactionID()
1628 {
1629 $reply = $this->getLastReply();
1630 if (empty($reply)) {
1631 return null;
1632 }
1633 foreach($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
1634 if(preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
1635 return $matches[1];
1636 }
1637 }
1638 return false;
1639 }
1640}
1641class PHPMailer
1642{
1643 /**
1644 * The PHPMailer Version number.
1645 * @var string
1646 */
1647 public $Version = '5.2.17';
1648 /**
1649 * Email priority.
1650 * Options: null (default), 1 = High, 3 = Normal, 5 = low.
1651 * When null, the header is not set at all.
1652 * @var integer
1653 */
1654 public $Priority = null;
1655 /**
1656 * The character set of the message.
1657 * @var string
1658 */
1659 public $CharSet = 'iso-8859-1';
1660 /**
1661 * The MIME Content-type of the message.
1662 * @var string
1663 */
1664 public $ContentType = 'text/plain';
1665 /**
1666 * The message encoding.
1667 * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
1668 * @var string
1669 */
1670 public $Encoding = '8bit';
1671 /**
1672 * Holds the most recent mailer error message.
1673 * @var string
1674 */
1675 public $ErrorInfo = '';
1676 /**
1677 * The From email address for the message.
1678 * @var string
1679 */
1680 public $From = 'root@localhost';
1681 /**
1682 * The From name of the message.
1683 * @var string
1684 */
1685 public $FromName = 'Root User';
1686 /**
1687 * The Sender email (Return-Path) of the message.
1688 * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
1689 * @var string
1690 */
1691 public $Sender = '';
1692 /**
1693 * The Return-Path of the message.
1694 * If empty, it will be set to either From or Sender.
1695 * @var string
1696 * @deprecated Email senders should never set a return-path header;
1697 * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
1698 * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
1699 */
1700 public $ReturnPath = '';
1701 /**
1702 * The Subject of the message.
1703 * @var string
1704 */
1705 public $Subject = '';
1706 /**
1707 * An HTML or plain text message body.
1708 * If HTML then call isHTML(true).
1709 * @var string
1710 */
1711 public $Body = '';
1712 /**
1713 * The plain-text message body.
1714 * This body can be read by mail clients that do not have HTML email
1715 * capability such as mutt & Eudora.
1716 * Clients that can read HTML will view the normal Body.
1717 * @var string
1718 */
1719 public $AltBody = '';
1720 /**
1721 * An iCal message part body.
1722 * Only supported in simple alt or alt_inline message types
1723 * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
1724 * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
1725 * @link http://kigkonsult.se/iCalcreator/
1726 * @var string
1727 */
1728 public $Ical = '';
1729 /**
1730 * The complete compiled MIME message body.
1731 * @access protected
1732 * @var string
1733 */
1734 protected $MIMEBody = '';
1735 /**
1736 * The complete compiled MIME message headers.
1737 * @var string
1738 * @access protected
1739 */
1740 protected $MIMEHeader = '';
1741 /**
1742 * Extra headers that createHeader() doesn't fold in.
1743 * @var string
1744 * @access protected
1745 */
1746 protected $mailHeader = '';
1747 /**
1748 * Word-wrap the message body to this number of chars.
1749 * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
1750 * @var integer
1751 */
1752 public $WordWrap = 0;
1753 /**
1754 * Which method to use to send mail.
1755 * Options: "mail", "sendmail", or "smtp".
1756 * @var string
1757 */
1758 public $Mailer = 'mail';
1759 /**
1760 * The path to the sendmail program.
1761 * @var string
1762 */
1763 public $Sendmail = '/usr/sbin/sendmail';
1764 /**
1765 * Whether mail() uses a fully sendmail-compatible MTA.
1766 * One which supports sendmail's "-oi -f" options.
1767 * @var boolean
1768 */
1769 public $UseSendmailOptions = true;
1770 /**
1771 * Path to PHPMailer plugins.
1772 * Useful if the SMTP class is not in the PHP include path.
1773 * @var string
1774 * @deprecated Should not be needed now there is an autoloader.
1775 */
1776 public $PluginDir = '';
1777 /**
1778 * The email address that a reading confirmation should be sent to, also known as read receipt.
1779 * @var string
1780 */
1781 public $ConfirmReadingTo = '';
1782 /**
1783 * The hostname to use in the Message-ID header and as default HELO string.
1784 * If empty, PHPMailer attempts to find one with, in order,
1785 * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
1786 * 'localhost.localdomain'.
1787 * @var string
1788 */
1789 public $Hostname = '';
1790 /**
1791 * An ID to be used in the Message-ID header.
1792 * If empty, a unique id will be generated.
1793 * You can set your own, but it must be in the format "<id@domain>",
1794 * as defined in RFC5322 section 3.6.4 or it will be ignored.
1795 * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
1796 * @var string
1797 */
1798 public $MessageID = '';
1799 /**
1800 * The message Date to be used in the Date header.
1801 * If empty, the current date will be added.
1802 * @var string
1803 */
1804 public $MessageDate = '';
1805 /**
1806 * SMTP hosts.
1807 * Either a single hostname or multiple semicolon-delimited hostnames.
1808 * You can also specify a different port
1809 * for each host by using this format: [hostname:port]
1810 * (e.g. "smtp1.example.com:25;smtp2.example.com").
1811 * You can also specify encryption type, for example:
1812 * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
1813 * Hosts will be tried in order.
1814 * @var string
1815 */
1816 public $Host = 'localhost';
1817 /**
1818 * The default SMTP server port.
1819 * @var integer
1820 * @TODO Why is this needed when the SMTP class takes care of it?
1821 */
1822 public $Port = 25;
1823 /**
1824 * The SMTP HELO of the message.
1825 * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
1826 * one with the same method described above for $Hostname.
1827 * @var string
1828 * @see PHPMailer::$Hostname
1829 */
1830 public $Helo = '';
1831 /**
1832 * What kind of encryption to use on the SMTP connection.
1833 * Options: '', 'ssl' or 'tls'
1834 * @var string
1835 */
1836 public $SMTPSecure = '';
1837 /**
1838 * Whether to enable TLS encryption automatically if a server supports it,
1839 * even if `SMTPSecure` is not set to 'tls'.
1840 * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
1841 * @var boolean
1842 */
1843 public $SMTPAutoTLS = true;
1844 /**
1845 * Whether to use SMTP authentication.
1846 * Uses the Username and Password properties.
1847 * @var boolean
1848 * @see PHPMailer::$Username
1849 * @see PHPMailer::$Password
1850 */
1851 public $SMTPAuth = false;
1852 /**
1853 * Options array passed to stream_context_create when connecting via SMTP.
1854 * @var array
1855 */
1856 public $SMTPOptions = array();
1857 /**
1858 * SMTP username.
1859 * @var string
1860 */
1861 public $Username = '';
1862 /**
1863 * SMTP password.
1864 * @var string
1865 */
1866 public $Password = '';
1867 /**
1868 * SMTP auth type.
1869 * Options are CRAM-MD5, LOGIN, PLAIN, NTLM, XOAUTH2, attempted in that order if not specified
1870 * @var string
1871 */
1872 public $AuthType = '';
1873 /**
1874 * SMTP realm.
1875 * Used for NTLM auth
1876 * @var string
1877 */
1878 public $Realm = '';
1879 /**
1880 * SMTP workstation.
1881 * Used for NTLM auth
1882 * @var string
1883 */
1884 public $Workstation = '';
1885 /**
1886 * The SMTP server timeout in seconds.
1887 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
1888 * @var integer
1889 */
1890 public $Timeout = 300;
1891 /**
1892 * SMTP class debug output mode.
1893 * Debug output level.
1894 * Options:
1895 * * `0` No output
1896 * * `1` Commands
1897 * * `2` Data and commands
1898 * * `3` As 2 plus connection status
1899 * * `4` Low-level data output
1900 * @var integer
1901 * @see SMTP::$do_debug
1902 */
1903 public $SMTPDebug = 0;
1904 /**
1905 * How to handle debug output.
1906 * Options:
1907 * * `echo` Output plain-text as-is, appropriate for CLI
1908 * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
1909 * * `error_log` Output to error log as configured in php.ini
1910 *
1911 * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
1912 * <code>
1913 * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
1914 * </code>
1915 * @var string|callable
1916 * @see SMTP::$Debugoutput
1917 */
1918 public $Debugoutput = 'echo';
1919 /**
1920 * Whether to keep SMTP connection open after each message.
1921 * If this is set to true then to close the connection
1922 * requires an explicit call to smtpClose().
1923 * @var boolean
1924 */
1925 public $SMTPKeepAlive = false;
1926 /**
1927 * Whether to split multiple to addresses into multiple messages
1928 * or send them all in one message.
1929 * Only supported in `mail` and `sendmail` transports, not in SMTP.
1930 * @var boolean
1931 */
1932 public $SingleTo = false;
1933 /**
1934 * Storage for addresses when SingleTo is enabled.
1935 * @var array
1936 * @TODO This should really not be public
1937 */
1938 public $SingleToArray = array();
1939 /**
1940 * Whether to generate VERP addresses on send.
1941 * Only applicable when sending via SMTP.
1942 * @link https://en.wikipedia.org/wiki/Variable_envelope_return_path
1943 * @link http://www.postfix.org/VERP_README.html Postfix VERP info
1944 * @var boolean
1945 */
1946 public $do_verp = false;
1947 /**
1948 * Whether to allow sending messages with an empty body.
1949 * @var boolean
1950 */
1951 public $AllowEmpty = false;
1952 /**
1953 * The default line ending.
1954 * @note The default remains "\n". We force CRLF where we know
1955 * it must be used via self::CRLF.
1956 * @var string
1957 */
1958 public $LE = "\n";
1959 /**
1960 * DKIM selector.
1961 * @var string
1962 */
1963 public $DKIM_selector = '';
1964 /**
1965 * DKIM Identity.
1966 * Usually the email address used as the source of the email.
1967 * @var string
1968 */
1969 public $DKIM_identity = '';
1970 /**
1971 * DKIM passphrase.
1972 * Used if your key is encrypted.
1973 * @var string
1974 */
1975 public $DKIM_passphrase = '';
1976 /**
1977 * DKIM signing domain name.
1978 * @example 'example.com'
1979 * @var string
1980 */
1981 public $DKIM_domain = '';
1982 /**
1983 * DKIM private key file path.
1984 * @var string
1985 */
1986 public $DKIM_private = '';
1987 /**
1988 * DKIM private key string.
1989 * If set, takes precedence over `$DKIM_private`.
1990 * @var string
1991 */
1992 public $DKIM_private_string = '';
1993 /**
1994 * Callback Action function name.
1995 *
1996 * The function that handles the result of the send email action.
1997 * It is called out by send() for each email sent.
1998 *
1999 * Value can be any php callable: http://www.php.net/is_callable
2000 *
2001 * Parameters:
2002 * boolean $result result of the send action
2003 * string $to email address of the recipient
2004 * string $cc cc email addresses
2005 * string $bcc bcc email addresses
2006 * string $subject the subject
2007 * string $body the email body
2008 * string $from email address of sender
2009 * @var string
2010 */
2011 public $action_function = '';
2012 /**
2013 * What to put in the X-Mailer header.
2014 * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
2015 * @var string
2016 */
2017 public $XMailer = '';
2018 /**
2019 * Which validator to use by default when validating email addresses.
2020 * May be a callable to inject your own validator, but there are several built-in validators.
2021 * @see PHPMailer::validateAddress()
2022 * @var string|callable
2023 * @static
2024 */
2025 public static $validator = 'auto';
2026 /**
2027 * An instance of the SMTP sender class.
2028 * @var SMTP
2029 * @access protected
2030 */
2031 protected $smtp = null;
2032 /**
2033 * The array of 'to' names and addresses.
2034 * @var array
2035 * @access protected
2036 */
2037 protected $to = array();
2038 /**
2039 * The array of 'cc' names and addresses.
2040 * @var array
2041 * @access protected
2042 */
2043 protected $cc = array();
2044 /**
2045 * The array of 'bcc' names and addresses.
2046 * @var array
2047 * @access protected
2048 */
2049 protected $bcc = array();
2050 /**
2051 * The array of reply-to names and addresses.
2052 * @var array
2053 * @access protected
2054 */
2055 protected $ReplyTo = array();
2056 /**
2057 * An array of all kinds of addresses.
2058 * Includes all of $to, $cc, $bcc
2059 * @var array
2060 * @access protected
2061 * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
2062 */
2063 protected $all_recipients = array();
2064 /**
2065 * An array of names and addresses queued for validation.
2066 * In send(), valid and non duplicate entries are moved to $all_recipients
2067 * and one of $to, $cc, or $bcc.
2068 * This array is used only for addresses with IDN.
2069 * @var array
2070 * @access protected
2071 * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
2072 * @see PHPMailer::$all_recipients
2073 */
2074 protected $RecipientsQueue = array();
2075 /**
2076 * An array of reply-to names and addresses queued for validation.
2077 * In send(), valid and non duplicate entries are moved to $ReplyTo.
2078 * This array is used only for addresses with IDN.
2079 * @var array
2080 * @access protected
2081 * @see PHPMailer::$ReplyTo
2082 */
2083 protected $ReplyToQueue = array();
2084 /**
2085 * The array of attachments.
2086 * @var array
2087 * @access protected
2088 */
2089 protected $attachment = array();
2090 /**
2091 * The array of custom headers.
2092 * @var array
2093 * @access protected
2094 */
2095 protected $CustomHeader = array();
2096 /**
2097 * The most recent Message-ID (including angular brackets).
2098 * @var string
2099 * @access protected
2100 */
2101 protected $lastMessageID = '';
2102 /**
2103 * The message's MIME type.
2104 * @var string
2105 * @access protected
2106 */
2107 protected $message_type = '';
2108 /**
2109 * The array of MIME boundary strings.
2110 * @var array
2111 * @access protected
2112 */
2113 protected $boundary = array();
2114 /**
2115 * The array of available languages.
2116 * @var array
2117 * @access protected
2118 */
2119 protected $language = array();
2120 /**
2121 * The number of errors encountered.
2122 * @var integer
2123 * @access protected
2124 */
2125 protected $error_count = 0;
2126 /**
2127 * The S/MIME certificate file path.
2128 * @var string
2129 * @access protected
2130 */
2131 protected $sign_cert_file = '';
2132 /**
2133 * The S/MIME key file path.
2134 * @var string
2135 * @access protected
2136 */
2137 protected $sign_key_file = '';
2138 /**
2139 * The optional S/MIME extra certificates ("CA Chain") file path.
2140 * @var string
2141 * @access protected
2142 */
2143 protected $sign_extracerts_file = '';
2144 /**
2145 * The S/MIME password for the key.
2146 * Used only if the key is encrypted.
2147 * @var string
2148 * @access protected
2149 */
2150 protected $sign_key_pass = '';
2151 /**
2152 * Whether to throw exceptions for errors.
2153 * @var boolean
2154 * @access protected
2155 */
2156 protected $exceptions = false;
2157 /**
2158 * Unique ID used for message ID and boundaries.
2159 * @var string
2160 * @access protected
2161 */
2162 protected $uniqueid = '';
2163 /**
2164 * Error severity: message only, continue processing.
2165 */
2166 const STOP_MESSAGE = 0;
2167 /**
2168 * Error severity: message, likely ok to continue processing.
2169 */
2170 const STOP_CONTINUE = 1;
2171 /**
2172 * Error severity: message, plus full stop, critical error reached.
2173 */
2174 const STOP_CRITICAL = 2;
2175 /**
2176 * SMTP RFC standard line ending.
2177 */
2178 const CRLF = "\r\n";
2179 /**
2180 * The maximum line length allowed by RFC 2822 section 2.1.1
2181 * @var integer
2182 */
2183 const MAX_LINE_LENGTH = 998;
2184 /**
2185 * Constructor.
2186 * @param boolean $exceptions Should we throw external exceptions?
2187 */
2188 public function __construct($exceptions = null)
2189 {
2190 if ($exceptions !== null) {
2191 $this->exceptions = (boolean)$exceptions;
2192 }
2193 }
2194 /**
2195 * Destructor.
2196 */
2197 public function __destruct()
2198 {
2199 //Close any open SMTP connection nicely
2200 $this->smtpClose();
2201 }
2202 /**
2203 * Call mail() in a safe_mode-aware fashion.
2204 * Also, unless sendmail_path points to sendmail (or something that
2205 * claims to be sendmail), don't pass params (not a perfect fix,
2206 * but it will do)
2207 * @param string $to To
2208 * @param string $subject Subject
2209 * @param string $body Message Body
2210 * @param string $header Additional Header(s)
2211 * @param string $params Params
2212 * @access private
2213 * @return boolean
2214 */
2215 private function mailPassthru($to, $subject, $body, $header, $params)
2216 {
2217 //Check overloading of mail function to avoid double-encoding
2218 if (ini_get('mbstring.func_overload') & 1) {
2219 $subject = $this->secureHeader($subject);
2220 } else {
2221 $subject = $this->encodeHeader($this->secureHeader($subject));
2222 }
2223 //Can't use additional_parameters in safe_mode
2224 //@link http://php.net/manual/en/function.mail.php
2225 if (ini_get('safe_mode') or !$this->UseSendmailOptions or is_null($params)) {
2226 $result = @mail($to, $subject, $body, $header);
2227 } else {
2228 $result = @mail($to, $subject, $body, $header, $params);
2229 }
2230 return $result;
2231 }
2232 /**
2233 * Output debugging info via user-defined method.
2234 * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
2235 * @see PHPMailer::$Debugoutput
2236 * @see PHPMailer::$SMTPDebug
2237 * @param string $str
2238 */
2239 protected function edebug($str)
2240 {
2241 if ($this->SMTPDebug <= 0) {
2242 return;
2243 }
2244 //Avoid clash with built-in function names
2245 if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
2246 call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
2247 return;
2248 }
2249 switch ($this->Debugoutput) {
2250 case 'error_log':
2251 //Don't output, just log
2252 error_log($str);
2253 break;
2254 case 'html':
2255 //Cleans up output a bit for a better looking, HTML-safe output
2256 echo htmlentities(
2257 preg_replace('/[\r\n]+/', '', $str),
2258 ENT_QUOTES,
2259 'UTF-8'
2260 )
2261 . "<br>\n";
2262 break;
2263 case 'echo':
2264 default:
2265 //Normalize line breaks
2266 $str = preg_replace('/\r\n?/ms', "\n", $str);
2267 echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
2268 "\n",
2269 "\n \t ",
2270 trim($str)
2271 ) . "\n";
2272 }
2273 }
2274 /**
2275 * Sets message type to HTML or plain.
2276 * @param boolean $isHtml True for HTML mode.
2277 * @return void
2278 */
2279 public function isHTML($isHtml = true)
2280 {
2281 if ($isHtml) {
2282 $this->ContentType = 'text/html';
2283 } else {
2284 $this->ContentType = 'text/plain';
2285 }
2286 }
2287 /**
2288 * Send messages using SMTP.
2289 * @return void
2290 */
2291 public function isSMTP()
2292 {
2293 $this->Mailer = 'smtp';
2294 }
2295 /**
2296 * Send messages using PHP's mail() function.
2297 * @return void
2298 */
2299 public function isMail()
2300 {
2301 $this->Mailer = 'mail';
2302 }
2303 /**
2304 * Send messages using $Sendmail.
2305 * @return void
2306 */
2307 public function isSendmail()
2308 {
2309 $ini_sendmail_path = ini_get('sendmail_path');
2310 if (!stristr($ini_sendmail_path, 'sendmail')) {
2311 $this->Sendmail = '/usr/sbin/sendmail';
2312 } else {
2313 $this->Sendmail = $ini_sendmail_path;
2314 }
2315 $this->Mailer = 'sendmail';
2316 }
2317 /**
2318 * Send messages using qmail.
2319 * @return void
2320 */
2321 public function isQmail()
2322 {
2323 $ini_sendmail_path = ini_get('sendmail_path');
2324 if (!stristr($ini_sendmail_path, 'qmail')) {
2325 $this->Sendmail = '/var/qmail/bin/qmail-inject';
2326 } else {
2327 $this->Sendmail = $ini_sendmail_path;
2328 }
2329 $this->Mailer = 'qmail';
2330 }
2331 /**
2332 * Add a "To" address.
2333 * @param string $address The email address to send to
2334 * @param string $name
2335 * @return boolean true on success, false if address already used or invalid in some way
2336 */
2337 public function addAddress($address, $name = '')
2338 {
2339 return $this->addOrEnqueueAnAddress('to', $address, $name);
2340 }
2341 /**
2342 * Add a "CC" address.
2343 * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
2344 * @param string $address The email address to send to
2345 * @param string $name
2346 * @return boolean true on success, false if address already used or invalid in some way
2347 */
2348 public function addCC($address, $name = '')
2349 {
2350 return $this->addOrEnqueueAnAddress('cc', $address, $name);
2351 }
2352 /**
2353 * Add a "BCC" address.
2354 * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
2355 * @param string $address The email address to send to
2356 * @param string $name
2357 * @return boolean true on success, false if address already used or invalid in some way
2358 */
2359 public function addBCC($address, $name = '')
2360 {
2361 return $this->addOrEnqueueAnAddress('bcc', $address, $name);
2362 }
2363 /**
2364 * Add a "Reply-To" address.
2365 * @param string $address The email address to reply to
2366 * @param string $name
2367 * @return boolean true on success, false if address already used or invalid in some way
2368 */
2369 public function addReplyTo($address, $name = '')
2370 {
2371 return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
2372 }
2373 /**
2374 * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
2375 * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
2376 * be modified after calling this function), addition of such addresses is delayed until send().
2377 * Addresses that have been added already return false, but do not throw exceptions.
2378 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
2379 * @param string $address The email address to send, resp. to reply to
2380 * @param string $name
2381 * @throws phpmailerException
2382 * @return boolean true on success, false if address already used or invalid in some way
2383 * @access protected
2384 */
2385 protected function addOrEnqueueAnAddress($kind, $address, $name)
2386 {
2387 $address = trim($address);
2388 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
2389 if (($pos = strrpos($address, '@')) === false) {
2390 // At-sign is misssing.
2391 $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
2392 $this->setError($error_message);
2393 $this->edebug($error_message);
2394 if ($this->exceptions) {
2395 throw new phpmailerException($error_message);
2396 }
2397 return false;
2398 }
2399 $params = array($kind, $address, $name);
2400 // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
2401 if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) {
2402 if ($kind != 'Reply-To') {
2403 if (!array_key_exists($address, $this->RecipientsQueue)) {
2404 $this->RecipientsQueue[$address] = $params;
2405 return true;
2406 }
2407 } else {
2408 if (!array_key_exists($address, $this->ReplyToQueue)) {
2409 $this->ReplyToQueue[$address] = $params;
2410 return true;
2411 }
2412 }
2413 return false;
2414 }
2415 // Immediately add standard addresses without IDN.
2416 return call_user_func_array(array($this, 'addAnAddress'), $params);
2417 }
2418 /**
2419 * Add an address to one of the recipient arrays or to the ReplyTo array.
2420 * Addresses that have been added already return false, but do not throw exceptions.
2421 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
2422 * @param string $address The email address to send, resp. to reply to
2423 * @param string $name
2424 * @throws phpmailerException
2425 * @return boolean true on success, false if address already used or invalid in some way
2426 * @access protected
2427 */
2428 protected function addAnAddress($kind, $address, $name = '')
2429 {
2430 if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) {
2431 $error_message = $this->lang('Invalid recipient kind: ') . $kind;
2432 $this->setError($error_message);
2433 $this->edebug($error_message);
2434 if ($this->exceptions) {
2435 throw new phpmailerException($error_message);
2436 }
2437 return false;
2438 }
2439 if (!$this->validateAddress($address)) {
2440 $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
2441 $this->setError($error_message);
2442 $this->edebug($error_message);
2443 if ($this->exceptions) {
2444 throw new phpmailerException($error_message);
2445 }
2446 return false;
2447 }
2448 if ($kind != 'Reply-To') {
2449 if (!array_key_exists(strtolower($address), $this->all_recipients)) {
2450 array_push($this->$kind, array($address, $name));
2451 $this->all_recipients[strtolower($address)] = true;
2452 return true;
2453 }
2454 } else {
2455 if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
2456 $this->ReplyTo[strtolower($address)] = array($address, $name);
2457 return true;
2458 }
2459 }
2460 return false;
2461 }
2462 /**
2463 * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
2464 * of the form "display name <address>" into an array of name/address pairs.
2465 * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
2466 * Note that quotes in the name part are removed.
2467 * @param string $addrstr The address list string
2468 * @param bool $useimap Whether to use the IMAP extension to parse the list
2469 * @return array
2470 * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
2471 */
2472 public function parseAddresses($addrstr, $useimap = true)
2473 {
2474 $addresses = array();
2475 if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
2476 //Use this built-in parser if it's available
2477 $list = imap_rfc822_parse_adrlist($addrstr, '');
2478 foreach ($list as $address) {
2479 if ($address->host != '.SYNTAX-ERROR.') {
2480 if ($this->validateAddress($address->mailbox . '@' . $address->host)) {
2481 $addresses[] = array(
2482 'name' => (property_exists($address, 'personal') ? $address->personal : ''),
2483 'address' => $address->mailbox . '@' . $address->host
2484 );
2485 }
2486 }
2487 }
2488 } else {
2489 //Use this simpler parser
2490 $list = explode(',', $addrstr);
2491 foreach ($list as $address) {
2492 $address = trim($address);
2493 //Is there a separate name part?
2494 if (strpos($address, '<') === false) {
2495 //No separate name, just use the whole thing
2496 if ($this->validateAddress($address)) {
2497 $addresses[] = array(
2498 'name' => '',
2499 'address' => $address
2500 );
2501 }
2502 } else {
2503 list($name, $email) = explode('<', $address);
2504 $email = trim(str_replace('>', '', $email));
2505 if ($this->validateAddress($email)) {
2506 $addresses[] = array(
2507 'name' => trim(str_replace(array('"', "'"), '', $name)),
2508 'address' => $email
2509 );
2510 }
2511 }
2512 }
2513 }
2514 return $addresses;
2515 }
2516 /**
2517 * Set the From and FromName properties.
2518 * @param string $address
2519 * @param string $name
2520 * @param boolean $auto Whether to also set the Sender address, defaults to true
2521 * @throws phpmailerException
2522 * @return boolean
2523 */
2524 public function setFrom($address, $name = '', $auto = true)
2525 {
2526 $address = trim($address);
2527 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
2528 // Don't validate now addresses with IDN. Will be done in send().
2529 if (($pos = strrpos($address, '@')) === false or
2530 (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and
2531 !$this->validateAddress($address)) {
2532 $error_message = $this->lang('invalid_address') . " (setFrom) $address";
2533 $this->setError($error_message);
2534 $this->edebug($error_message);
2535 if ($this->exceptions) {
2536 throw new phpmailerException($error_message);
2537 }
2538 return false;
2539 }
2540 $this->From = $address;
2541 $this->FromName = $name;
2542 if ($auto) {
2543 if (empty($this->Sender)) {
2544 $this->Sender = $address;
2545 }
2546 }
2547 return true;
2548 }
2549 /**
2550 * Return the Message-ID header of the last email.
2551 * Technically this is the value from the last time the headers were created,
2552 * but it's also the message ID of the last sent message except in
2553 * pathological cases.
2554 * @return string
2555 */
2556 public function getLastMessageID()
2557 {
2558 return $this->lastMessageID;
2559 }
2560 /**
2561 * Check that a string looks like an email address.
2562 * @param string $address The email address to check
2563 * @param string|callable $patternselect A selector for the validation pattern to use :
2564 * * `auto` Pick best pattern automatically;
2565 * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
2566 * * `pcre` Use old PCRE implementation;
2567 * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
2568 * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
2569 * * `noregex` Don't use a regex: super fast, really dumb.
2570 * Alternatively you may pass in a callable to inject your own validator, for example:
2571 * PHPMailer::validateAddress('user@example.com', function($address) {
2572 * return (strpos($address, '@') !== false);
2573 * });
2574 * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
2575 * @return boolean
2576 * @static
2577 * @access public
2578 */
2579 public static function validateAddress($address, $patternselect = null)
2580 {
2581 if (is_null($patternselect)) {
2582 $patternselect = self::$validator;
2583 }
2584 if (is_callable($patternselect)) {
2585 return call_user_func($patternselect, $address);
2586 }
2587 //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
2588 if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
2589 return false;
2590 }
2591 if (!$patternselect or $patternselect == 'auto') {
2592 //Check this constant first so it works when extension_loaded() is disabled by safe mode
2593 //Constant was added in PHP 5.2.4
2594 if (defined('PCRE_VERSION')) {
2595 //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
2596 if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
2597 $patternselect = 'pcre8';
2598 } else {
2599 $patternselect = 'pcre';
2600 }
2601 } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
2602 //Fall back to older PCRE
2603 $patternselect = 'pcre';
2604 } else {
2605 //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
2606 if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
2607 $patternselect = 'php';
2608 } else {
2609 $patternselect = 'noregex';
2610 }
2611 }
2612 }
2613 switch ($patternselect) {
2614 case 'pcre8':
2615 /**
2616 * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
2617 * @link http://squiloople.com/2009/12/20/email-address-validation/
2618 * @copyright 2009-2010 Michael Rushton
2619 * Feel free to use and redistribute this code. But please keep this copyright notice.
2620 */
2621 return (boolean)preg_match(
2622 '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
2623 '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
2624 '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
2625 '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
2626 '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
2627 '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
2628 '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
2629 '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
2630 '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
2631 $address
2632 );
2633 case 'pcre':
2634 //An older regex that doesn't need a recent PCRE
2635 return (boolean)preg_match(
2636 '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
2637 '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
2638 '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
2639 '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
2640 '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
2641 '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
2642 '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
2643 '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
2644 '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
2645 '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
2646 $address
2647 );
2648 case 'html5':
2649 /**
2650 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
2651 * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
2652 */
2653 return (boolean)preg_match(
2654 '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
2655 '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
2656 $address
2657 );
2658 case 'noregex':
2659 //No PCRE! Do something _very_ approximate!
2660 //Check the address is 3 chars or longer and contains an @ that's not the first or last char
2661 return (strlen($address) >= 3
2662 and strpos($address, '@') >= 1
2663 and strpos($address, '@') != strlen($address) - 1);
2664 case 'php':
2665 default:
2666 return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
2667 }
2668 }
2669 /**
2670 * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
2671 * "intl" and "mbstring" PHP extensions.
2672 * @return bool "true" if required functions for IDN support are present
2673 */
2674 public function idnSupported()
2675 {
2676 // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2.
2677 return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
2678 }
2679 /**
2680 * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
2681 * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
2682 * This function silently returns unmodified address if:
2683 * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
2684 * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
2685 * or fails for any reason (e.g. domain has characters not allowed in an IDN)
2686 * @see PHPMailer::$CharSet
2687 * @param string $address The email address to convert
2688 * @return string The encoded address in ASCII form
2689 */
2690 public function punyencodeAddress($address)
2691 {
2692 // Verify we have required functions, CharSet, and at-sign.
2693 if ($this->idnSupported() and
2694 !empty($this->CharSet) and
2695 ($pos = strrpos($address, '@')) !== false) {
2696 $domain = substr($address, ++$pos);
2697 // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
2698 if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
2699 $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
2700 if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ?
2701 idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) :
2702 idn_to_ascii($domain)) !== false) {
2703 return substr($address, 0, $pos) . $punycode;
2704 }
2705 }
2706 }
2707 return $address;
2708 }
2709 /**
2710 * Create a message and send it.
2711 * Uses the sending method specified by $Mailer.
2712 * @throws phpmailerException
2713 * @return boolean false on error - See the ErrorInfo property for details of the error.
2714 */
2715 public function send()
2716 {
2717 try {
2718 if (!$this->preSend()) {
2719 return false;
2720 }
2721 return $this->postSend();
2722 } catch (phpmailerException $exc) {
2723 $this->mailHeader = '';
2724 $this->setError($exc->getMessage());
2725 if ($this->exceptions) {
2726 throw $exc;
2727 }
2728 return false;
2729 }
2730 }
2731 /**
2732 * Prepare a message for sending.
2733 * @throws phpmailerException
2734 * @return boolean
2735 */
2736 public function preSend()
2737 {
2738 try {
2739 $this->error_count = 0; // Reset errors
2740 $this->mailHeader = '';
2741 // Dequeue recipient and Reply-To addresses with IDN
2742 foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
2743 $params[1] = $this->punyencodeAddress($params[1]);
2744 call_user_func_array(array($this, 'addAnAddress'), $params);
2745 }
2746 if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
2747 throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
2748 }
2749 // Validate From, Sender, and ConfirmReadingTo addresses
2750 foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) {
2751 $this->$address_kind = trim($this->$address_kind);
2752 if (empty($this->$address_kind)) {
2753 continue;
2754 }
2755 $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
2756 if (!$this->validateAddress($this->$address_kind)) {
2757 $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind;
2758 $this->setError($error_message);
2759 $this->edebug($error_message);
2760 if ($this->exceptions) {
2761 throw new phpmailerException($error_message);
2762 }
2763 return false;
2764 }
2765 }
2766 // Set whether the message is multipart/alternative
2767 if ($this->alternativeExists()) {
2768 $this->ContentType = 'multipart/alternative';
2769 }
2770 $this->setMessageType();
2771 // Refuse to send an empty message unless we are specifically allowing it
2772 if (!$this->AllowEmpty and empty($this->Body)) {
2773 throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
2774 }
2775 // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
2776 $this->MIMEHeader = '';
2777 $this->MIMEBody = $this->createBody();
2778 // createBody may have added some headers, so retain them
2779 $tempheaders = $this->MIMEHeader;
2780 $this->MIMEHeader = $this->createHeader();
2781 $this->MIMEHeader .= $tempheaders;
2782 // To capture the complete message when using mail(), create
2783 // an extra header list which createHeader() doesn't fold in
2784 if ($this->Mailer == 'mail') {
2785 if (count($this->to) > 0) {
2786 $this->mailHeader .= $this->addrAppend('To', $this->to);
2787 } else {
2788 $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
2789 }
2790 $this->mailHeader .= $this->headerLine(
2791 'Subject',
2792 $this->encodeHeader($this->secureHeader(trim($this->Subject)))
2793 );
2794 }
2795 // Sign with DKIM if enabled
2796 if (!empty($this->DKIM_domain)
2797 && !empty($this->DKIM_selector)
2798 && (!empty($this->DKIM_private_string)
2799 || (!empty($this->DKIM_private) && file_exists($this->DKIM_private))
2800 )
2801 ) {
2802 $header_dkim = $this->DKIM_Add(
2803 $this->MIMEHeader . $this->mailHeader,
2804 $this->encodeHeader($this->secureHeader($this->Subject)),
2805 $this->MIMEBody
2806 );
2807 $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
2808 str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
2809 }
2810 return true;
2811 } catch (phpmailerException $exc) {
2812 $this->setError($exc->getMessage());
2813 if ($this->exceptions) {
2814 throw $exc;
2815 }
2816 return false;
2817 }
2818 }
2819 /**
2820 * Actually send a message.
2821 * Send the email via the selected mechanism
2822 * @throws phpmailerException
2823 * @return boolean
2824 */
2825 public function postSend()
2826 {
2827 try {
2828 // Choose the mailer and send through it
2829 switch ($this->Mailer) {
2830 case 'sendmail':
2831 case 'qmail':
2832 return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
2833 case 'smtp':
2834 return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
2835 case 'mail':
2836 return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
2837 default:
2838 $sendMethod = $this->Mailer.'Send';
2839 if (method_exists($this, $sendMethod)) {
2840 return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
2841 }
2842 return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
2843 }
2844 } catch (phpmailerException $exc) {
2845 $this->setError($exc->getMessage());
2846 $this->edebug($exc->getMessage());
2847 if ($this->exceptions) {
2848 throw $exc;
2849 }
2850 }
2851 return false;
2852 }
2853 /**
2854 * Send mail using the $Sendmail program.
2855 * @param string $header The message headers
2856 * @param string $body The message body
2857 * @see PHPMailer::$Sendmail
2858 * @throws phpmailerException
2859 * @access protected
2860 * @return boolean
2861 */
2862 protected function sendmailSend($header, $body)
2863 {
2864 if ($this->Sender != '') {
2865 if ($this->Mailer == 'qmail') {
2866 $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
2867 } else {
2868 $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
2869 }
2870 } else {
2871 if ($this->Mailer == 'qmail') {
2872 $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
2873 } else {
2874 $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
2875 }
2876 }
2877 if ($this->SingleTo) {
2878 foreach ($this->SingleToArray as $toAddr) {
2879 if (!@$mail = popen($sendmail, 'w')) {
2880 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
2881 }
2882 fputs($mail, 'To: ' . $toAddr . "\n");
2883 fputs($mail, $header);
2884 fputs($mail, $body);
2885 $result = pclose($mail);
2886 $this->doCallback(
2887 ($result == 0),
2888 array($toAddr),
2889 $this->cc,
2890 $this->bcc,
2891 $this->Subject,
2892 $body,
2893 $this->From
2894 );
2895 if ($result != 0) {
2896 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
2897 }
2898 }
2899 } else {
2900 if (!@$mail = popen($sendmail, 'w')) {
2901 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
2902 }
2903 fputs($mail, $header);
2904 fputs($mail, $body);
2905 $result = pclose($mail);
2906 $this->doCallback(
2907 ($result == 0),
2908 $this->to,
2909 $this->cc,
2910 $this->bcc,
2911 $this->Subject,
2912 $body,
2913 $this->From
2914 );
2915 if ($result != 0) {
2916 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
2917 }
2918 }
2919 return true;
2920 }
2921 /**
2922 * Send mail using the PHP mail() function.
2923 * @param string $header The message headers
2924 * @param string $body The message body
2925 * @link http://www.php.net/manual/en/book.mail.php
2926 * @throws phpmailerException
2927 * @access protected
2928 * @return boolean
2929 */
2930 protected function mailSend($header, $body)
2931 {
2932 $toArr = array();
2933 foreach ($this->to as $toaddr) {
2934 $toArr[] = $this->addrFormat($toaddr);
2935 }
2936 $to = implode(', ', $toArr);
2937 $params = null;
2938 //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
2939 if (!empty($this->Sender)) {
2940 $params = sprintf('-f%s', $this->Sender);
2941 }
2942 if ($this->Sender != '' and !ini_get('safe_mode')) {
2943 $old_from = ini_get('sendmail_from');
2944 ini_set('sendmail_from', $this->Sender);
2945 }
2946 $result = false;
2947 if ($this->SingleTo and count($toArr) > 1) {
2948 foreach ($toArr as $toAddr) {
2949 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
2950 $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
2951 }
2952 } else {
2953 $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
2954 $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
2955 }
2956 if (isset($old_from)) {
2957 ini_set('sendmail_from', $old_from);
2958 }
2959 if (!$result) {
2960 throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
2961 }
2962 return true;
2963 }
2964 /**
2965 * Get an instance to use for SMTP operations.
2966 * Override this function to load your own SMTP implementation
2967 * @return SMTP
2968 */
2969 public function getSMTPInstance()
2970 {
2971 if (!is_object($this->smtp)) {
2972 $this->smtp = new SMTP;
2973 }
2974 return $this->smtp;
2975 }
2976 /**
2977 * Send mail via SMTP.
2978 * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
2979 * Uses the PHPMailerSMTP class by default.
2980 * @see PHPMailer::getSMTPInstance() to use a different class.
2981 * @param string $header The message headers
2982 * @param string $body The message body
2983 * @throws phpmailerException
2984 * @uses SMTP
2985 * @access protected
2986 * @return boolean
2987 */
2988 protected function smtpSend($header, $body)
2989 {
2990 $bad_rcpt = array();
2991 if (!$this->smtpConnect($this->SMTPOptions)) {
2992 throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
2993 }
2994 if ('' == $this->Sender) {
2995 $smtp_from = $this->From;
2996 } else {
2997 $smtp_from = $this->Sender;
2998 }
2999 if (!$this->smtp->mail($smtp_from)) {
3000 $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
3001 throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
3002 }
3003 // Attempt to send to all recipients
3004 foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
3005 foreach ($togroup as $to) {
3006 if (!$this->smtp->recipient($to[0])) {
3007 $error = $this->smtp->getError();
3008 $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
3009 $isSent = false;
3010 } else {
3011 $isSent = true;
3012 }
3013 $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
3014 }
3015 }
3016 // Only send the DATA command if we have viable recipients
3017 if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
3018 throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
3019 }
3020 if ($this->SMTPKeepAlive) {
3021 $this->smtp->reset();
3022 } else {
3023 $this->smtp->quit();
3024 $this->smtp->close();
3025 }
3026 //Create error message for any bad addresses
3027 if (count($bad_rcpt) > 0) {
3028 $errstr = '';
3029 foreach ($bad_rcpt as $bad) {
3030 $errstr .= $bad['to'] . ': ' . $bad['error'];
3031 }
3032 throw new phpmailerException(
3033 $this->lang('recipients_failed') . $errstr,
3034 self::STOP_CONTINUE
3035 );
3036 }
3037 return true;
3038 }
3039 /**
3040 * Initiate a connection to an SMTP server.
3041 * Returns false if the operation failed.
3042 * @param array $options An array of options compatible with stream_context_create()
3043 * @uses SMTP
3044 * @access public
3045 * @throws phpmailerException
3046 * @return boolean
3047 */
3048 public function smtpConnect($options = null)
3049 {
3050 if (is_null($this->smtp)) {
3051 $this->smtp = $this->getSMTPInstance();
3052 }
3053 //If no options are provided, use whatever is set in the instance
3054 if (is_null($options)) {
3055 $options = $this->SMTPOptions;
3056 }
3057 // Already connected?
3058 if ($this->smtp->connected()) {
3059 return true;
3060 }
3061 $this->smtp->setTimeout($this->Timeout);
3062 $this->smtp->setDebugLevel($this->SMTPDebug);
3063 $this->smtp->setDebugOutput($this->Debugoutput);
3064 $this->smtp->setVerp($this->do_verp);
3065 $hosts = explode(';', $this->Host);
3066 $lastexception = null;
3067 foreach ($hosts as $hostentry) {
3068 $hostinfo = array();
3069 if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9:\[\]\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)){
3070 // Not a valid host entry
3071 continue;
3072 }
3073 // $hostinfo[2]: optional ssl or tls prefix
3074 // $hostinfo[3]: the hostname
3075 // $hostinfo[4]: optional port number
3076 // The host string prefix can temporarily override the current setting for SMTPSecure
3077 // If it's not specified, the default value is used
3078 $prefix = '';
3079 $secure = $this->SMTPSecure;
3080 $tls = ($this->SMTPSecure == 'tls');
3081 if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
3082 $prefix = 'ssl://';
3083 $tls = false; // Can't have SSL and TLS at the same time
3084 $secure = 'ssl';
3085 } elseif ($hostinfo[2] == 'tls') {
3086 $tls = true;
3087 // tls doesn't use a prefix
3088 $secure = 'tls';
3089 }
3090 //Do we need the OpenSSL extension?
3091 $sslext = defined('OPENSSL_ALGO_SHA1');
3092 if ('tls' === $secure or 'ssl' === $secure) {
3093 //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
3094 if (!$sslext) {
3095 throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
3096 }
3097 }
3098 $host = $hostinfo[3];
3099 $port = $this->Port;
3100 $tport = (integer)$hostinfo[4];
3101 if ($tport > 0 and $tport < 65536) {
3102 $port = $tport;
3103 }
3104 if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
3105 try {
3106 if ($this->Helo) {
3107 $hello = $this->Helo;
3108 } else {
3109 $hello = $this->serverHostname();
3110 }
3111 $this->smtp->hello($hello);
3112 //Automatically enable TLS encryption if:
3113 // * it's not disabled
3114 // * we have openssl extension
3115 // * we are not already using SSL
3116 // * the server offers STARTTLS
3117 if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
3118 $tls = true;
3119 }
3120 if ($tls) {
3121 if (!$this->smtp->startTLS()) {
3122 throw new phpmailerException($this->lang('connect_host'));
3123 }
3124 // We must resend EHLO after TLS negotiation
3125 $this->smtp->hello($hello);
3126 }
3127 if ($this->SMTPAuth) {
3128 if (!$this->smtp->authenticate(
3129 $this->Username,
3130 $this->Password,
3131 $this->AuthType,
3132 $this->Realm,
3133 $this->Workstation
3134 )
3135 ) {
3136 throw new phpmailerException($this->lang('authenticate'));
3137 }
3138 }
3139 return true;
3140 } catch (phpmailerException $exc) {
3141 $lastexception = $exc;
3142 $this->edebug($exc->getMessage());
3143 // We must have connected, but then failed TLS or Auth, so close connection nicely
3144 $this->smtp->quit();
3145 }
3146 }
3147 }
3148 // If we get here, all connection attempts have failed, so close connection hard
3149 $this->smtp->close();
3150 // As we've caught all exceptions, just report whatever the last one was
3151 if ($this->exceptions and !is_null($lastexception)) {
3152 throw $lastexception;
3153 }
3154 return false;
3155 }
3156 /**
3157 * Close the active SMTP session if one exists.
3158 * @return void
3159 */
3160 public function smtpClose()
3161 {
3162 if (is_a($this->smtp, 'SMTP')) {
3163 if ($this->smtp->connected()) {
3164 $this->smtp->quit();
3165 $this->smtp->close();
3166 }
3167 }
3168 }
3169 /**
3170 * Set the language for error messages.
3171 * Returns false if it cannot load the language file.
3172 * The default language is English.
3173 * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
3174 * @param string $lang_path Path to the language file directory, with trailing separator (slash)
3175 * @return boolean
3176 * @access public
3177 */
3178 public function setLanguage($langcode = 'en', $lang_path = '')
3179 {
3180 // Backwards compatibility for renamed language codes
3181 $renamed_langcodes = array(
3182 'br' => 'pt_br',
3183 'cz' => 'cs',
3184 'dk' => 'da',
3185 'no' => 'nb',
3186 'se' => 'sv',
3187 );
3188 if (isset($renamed_langcodes[$langcode])) {
3189 $langcode = $renamed_langcodes[$langcode];
3190 }
3191 // Define full set of translatable strings in English
3192 $PHPMAILER_LANG = array(
3193 'authenticate' => 'SMTP Error: Could not authenticate.',
3194 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
3195 'data_not_accepted' => 'SMTP Error: data not accepted.',
3196 'empty_message' => 'Message body empty',
3197 'encoding' => 'Unknown encoding: ',
3198 'execute' => 'Could not execute: ',
3199 'file_access' => 'Could not access file: ',
3200 'file_open' => 'File Error: Could not open file: ',
3201 'from_failed' => 'The following From address failed: ',
3202 'instantiate' => 'Could not instantiate mail function.',
3203 'invalid_address' => 'Invalid address: ',
3204 'mailer_not_supported' => ' mailer is not supported.',
3205 'provide_address' => 'You must provide at least one recipient email address.',
3206 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
3207 'signing' => 'Signing Error: ',
3208 'smtp_connect_failed' => 'SMTP connect() failed.',
3209 'smtp_error' => 'SMTP server error: ',
3210 'variable_set' => 'Cannot set or reset variable: ',
3211 'extension_missing' => 'Extension missing: '
3212 );
3213 if (empty($lang_path)) {
3214 // Calculate an absolute path so it can work if CWD is not here
3215 $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
3216 }
3217 //Validate $langcode
3218 if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
3219 $langcode = 'en';
3220 }
3221 $foundlang = true;
3222 $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
3223 // There is no English translation file
3224 if ($langcode != 'en') {
3225 // Make sure language file path is readable
3226 if (!is_readable($lang_file)) {
3227 $foundlang = false;
3228 } else {
3229 // Overwrite language-specific strings.
3230 // This way we'll never have missing translation keys.
3231 $foundlang = include $lang_file;
3232 }
3233 }
3234 $this->language = $PHPMAILER_LANG;
3235 return (boolean)$foundlang; // Returns false if language not found
3236 }
3237 /**
3238 * Get the array of strings for the current language.
3239 * @return array
3240 */
3241 public function getTranslations()
3242 {
3243 return $this->language;
3244 }
3245 /**
3246 * Create recipient headers.
3247 * @access public
3248 * @param string $type
3249 * @param array $addr An array of recipient,
3250 * where each recipient is a 2-element indexed array with element 0 containing an address
3251 * and element 1 containing a name, like:
3252 * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
3253 * @return string
3254 */
3255 public function addrAppend($type, $addr)
3256 {
3257 $addresses = array();
3258 foreach ($addr as $address) {
3259 $addresses[] = $this->addrFormat($address);
3260 }
3261 return $type . ': ' . implode(', ', $addresses) . $this->LE;
3262 }
3263 /**
3264 * Format an address for use in a message header.
3265 * @access public
3266 * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
3267 * like array('joe@example.com', 'Joe User')
3268 * @return string
3269 */
3270 public function addrFormat($addr)
3271 {
3272 if (empty($addr[1])) { // No name provided
3273 return $this->secureHeader($addr[0]);
3274 } else {
3275 return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
3276 $addr[0]
3277 ) . '>';
3278 }
3279 }
3280 /**
3281 * Word-wrap message.
3282 * For use with mailers that do not automatically perform wrapping
3283 * and for quoted-printable encoded messages.
3284 * Original written by philippe.
3285 * @param string $message The message to wrap
3286 * @param integer $length The line length to wrap to
3287 * @param boolean $qp_mode Whether to run in Quoted-Printable mode
3288 * @access public
3289 * @return string
3290 */
3291 public function wrapText($message, $length, $qp_mode = false)
3292 {
3293 if ($qp_mode) {
3294 $soft_break = sprintf(' =%s', $this->LE);
3295 } else {
3296 $soft_break = $this->LE;
3297 }
3298 // If utf-8 encoding is used, we will need to make sure we don't
3299 // split multibyte characters when we wrap
3300 $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
3301 $lelen = strlen($this->LE);
3302 $crlflen = strlen(self::CRLF);
3303 $message = $this->fixEOL($message);
3304 //Remove a trailing line break
3305 if (substr($message, -$lelen) == $this->LE) {
3306 $message = substr($message, 0, -$lelen);
3307 }
3308 //Split message into lines
3309 $lines = explode($this->LE, $message);
3310 //Message will be rebuilt in here
3311 $message = '';
3312 foreach ($lines as $line) {
3313 $words = explode(' ', $line);
3314 $buf = '';
3315 $firstword = true;
3316 foreach ($words as $word) {
3317 if ($qp_mode and (strlen($word) > $length)) {
3318 $space_left = $length - strlen($buf) - $crlflen;
3319 if (!$firstword) {
3320 if ($space_left > 20) {
3321 $len = $space_left;
3322 if ($is_utf8) {
3323 $len = $this->utf8CharBoundary($word, $len);
3324 } elseif (substr($word, $len - 1, 1) == '=') {
3325 $len--;
3326 } elseif (substr($word, $len - 2, 1) == '=') {
3327 $len -= 2;
3328 }
3329 $part = substr($word, 0, $len);
3330 $word = substr($word, $len);
3331 $buf .= ' ' . $part;
3332 $message .= $buf . sprintf('=%s', self::CRLF);
3333 } else {
3334 $message .= $buf . $soft_break;
3335 }
3336 $buf = '';
3337 }
3338 while (strlen($word) > 0) {
3339 if ($length <= 0) {
3340 break;
3341 }
3342 $len = $length;
3343 if ($is_utf8) {
3344 $len = $this->utf8CharBoundary($word, $len);
3345 } elseif (substr($word, $len - 1, 1) == '=') {
3346 $len--;
3347 } elseif (substr($word, $len - 2, 1) == '=') {
3348 $len -= 2;
3349 }
3350 $part = substr($word, 0, $len);
3351 $word = substr($word, $len);
3352 if (strlen($word) > 0) {
3353 $message .= $part . sprintf('=%s', self::CRLF);
3354 } else {
3355 $buf = $part;
3356 }
3357 }
3358 } else {
3359 $buf_o = $buf;
3360 if (!$firstword) {
3361 $buf .= ' ';
3362 }
3363 $buf .= $word;
3364 if (strlen($buf) > $length and $buf_o != '') {
3365 $message .= $buf_o . $soft_break;
3366 $buf = $word;
3367 }
3368 }
3369 $firstword = false;
3370 }
3371 $message .= $buf . self::CRLF;
3372 }
3373 return $message;
3374 }
3375 /**
3376 * Find the last character boundary prior to $maxLength in a utf-8
3377 * quoted-printable encoded string.
3378 * Original written by Colin Brown.
3379 * @access public
3380 * @param string $encodedText utf-8 QP text
3381 * @param integer $maxLength Find the last character boundary prior to this length
3382 * @return integer
3383 */
3384 public function utf8CharBoundary($encodedText, $maxLength)
3385 {
3386 $foundSplitPos = false;
3387 $lookBack = 3;
3388 while (!$foundSplitPos) {
3389 $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
3390 $encodedCharPos = strpos($lastChunk, '=');
3391 if (false !== $encodedCharPos) {
3392 // Found start of encoded character byte within $lookBack block.
3393 // Check the encoded byte value (the 2 chars after the '=')
3394 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
3395 $dec = hexdec($hex);
3396 if ($dec < 128) {
3397 // Single byte character.
3398 // If the encoded char was found at pos 0, it will fit
3399 // otherwise reduce maxLength to start of the encoded char
3400 if ($encodedCharPos > 0) {
3401 $maxLength = $maxLength - ($lookBack - $encodedCharPos);
3402 }
3403 $foundSplitPos = true;
3404 } elseif ($dec >= 192) {
3405 // First byte of a multi byte character
3406 // Reduce maxLength to split at start of character
3407 $maxLength = $maxLength - ($lookBack - $encodedCharPos);
3408 $foundSplitPos = true;
3409 } elseif ($dec < 192) {
3410 // Middle byte of a multi byte character, look further back
3411 $lookBack += 3;
3412 }
3413 } else {
3414 // No encoded character found
3415 $foundSplitPos = true;
3416 }
3417 }
3418 return $maxLength;
3419 }
3420 /**
3421 * Apply word wrapping to the message body.
3422 * Wraps the message body to the number of chars set in the WordWrap property.
3423 * You should only do this to plain-text bodies as wrapping HTML tags may break them.
3424 * This is called automatically by createBody(), so you don't need to call it yourself.
3425 * @access public
3426 * @return void
3427 */
3428 public function setWordWrap()
3429 {
3430 if ($this->WordWrap < 1) {
3431 return;
3432 }
3433 switch ($this->message_type) {
3434 case 'alt':
3435 case 'alt_inline':
3436 case 'alt_attach':
3437 case 'alt_inline_attach':
3438 $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
3439 break;
3440 default:
3441 $this->Body = $this->wrapText($this->Body, $this->WordWrap);
3442 break;
3443 }
3444 }
3445 /**
3446 * Assemble message headers.
3447 * @access public
3448 * @return string The assembled headers
3449 */
3450 public function createHeader()
3451 {
3452 $result = '';
3453 if ($this->MessageDate == '') {
3454 $this->MessageDate = self::rfcDate();
3455 }
3456 $result .= $this->headerLine('Date', $this->MessageDate == '' ? self::rfcDate() : $this->MessageDate);
3457 // To be created automatically by mail()
3458 if ($this->SingleTo) {
3459 if ($this->Mailer != 'mail') {
3460 foreach ($this->to as $toaddr) {
3461 $this->SingleToArray[] = $this->addrFormat($toaddr);
3462 }
3463 }
3464 } else {
3465 if (count($this->to) > 0) {
3466 if ($this->Mailer != 'mail') {
3467 $result .= $this->addrAppend('To', $this->to);
3468 }
3469 } elseif (count($this->cc) == 0) {
3470 $result .= $this->headerLine('To', 'undisclosed-recipients:;');
3471 }
3472 }
3473 $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
3474 // sendmail and mail() extract Cc from the header before sending
3475 if (count($this->cc) > 0) {
3476 $result .= $this->addrAppend('Cc', $this->cc);
3477 }
3478 // sendmail and mail() extract Bcc from the header before sending
3479 if ((
3480 $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
3481 )
3482 and count($this->bcc) > 0
3483 ) {
3484 $result .= $this->addrAppend('Bcc', $this->bcc);
3485 }
3486 if (count($this->ReplyTo) > 0) {
3487 $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
3488 }
3489 // mail() sets the subject itself
3490 if ($this->Mailer != 'mail') {
3491 $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
3492 }
3493 // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
3494 // https://tools.ietf.org/html/rfc5322#section-3.6.4
3495 if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {
3496 $this->lastMessageID = $this->MessageID;
3497 } else {
3498 //$this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
3499 $this->lastMessageID = '<'.md5($this->uniqueid)."@".explode("@",$this->From)[1].'>';
3500 }
3501 $result .= $this->headerLine('Message-ID', $this->lastMessageID);
3502 if (!is_null($this->Priority)) {
3503 $result .= $this->headerLine('X-Priority', $this->Priority);
3504 }
3505 /* if ($this->XMailer == '') {
3506 $result .= $this->headerLine(
3507 'X-Mailer',
3508 //'PHPMailer ' . $this->Version . '(https://github.com/PHPMailer/PHPMailer)'
3509 'PHPMailer ' . $this->uniqueid
3510 );
3511 } else {
3512 $myXmailer = trim($this->XMailer);
3513 if ($myXmailer) {
3514 //$result .= $this->headerLine('X-Mailer', $myXmailer);
3515 $result .= $this->headerLine('X-Mailer', $myXmailer.$this->uniqueid);
3516 }
3517 }*/
3518 if ($this->ConfirmReadingTo != '') {
3519 $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
3520 }
3521 // Add custom headers
3522 foreach ($this->CustomHeader as $header) {
3523 $result .= $this->headerLine(
3524 trim($header[0]),
3525 $this->encodeHeader(trim($header[1]))
3526 );
3527 }
3528 if (!$this->sign_key_file) {
3529 $result .= $this->headerLine('MIME-Version', '1.0');
3530 $result .= $this->getMailMIME();
3531 }
3532 return $result;
3533 }
3534 /**
3535 * Get the message MIME type headers.
3536 * @access public
3537 * @return string
3538 */
3539 public function getMailMIME()
3540 {
3541 $result = '';
3542 $ismultipart = true;
3543 switch ($this->message_type) {
3544 case 'inline':
3545 $result .= $this->headerLine('Content-Type', 'multipart/related;');
3546 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
3547 break;
3548 case 'attach':
3549 case 'inline_attach':
3550 case 'alt_attach':
3551 case 'alt_inline_attach':
3552 $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
3553 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
3554 break;
3555 case 'alt':
3556 case 'alt_inline':
3557 $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
3558 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
3559 break;
3560 default:
3561 // Catches case 'plain': and case '':
3562 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=utf-8');
3563 $ismultipart = false;
3564 break;
3565 }
3566 // RFC1341 part 5 says 7bit is assumed if not specified
3567 if ($this->Encoding != '7bit') {
3568 // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
3569 if ($ismultipart) {
3570 if ($this->Encoding == '8bit') {
3571 $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
3572 }
3573 // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
3574 } else {
3575 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
3576 }
3577 }
3578 if ($this->Mailer != 'mail') {
3579 $result .= $this->LE;
3580 }
3581 return $result;
3582 }
3583 /**
3584 * Returns the whole MIME message.
3585 * Includes complete headers and body.
3586 * Only valid post preSend().
3587 * @see PHPMailer::preSend()
3588 * @access public
3589 * @return string
3590 */
3591 public function getSentMIMEMessage()
3592 {
3593 return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody;
3594 }
3595 /**
3596 * Create unique ID
3597 * @return string
3598 */
3599 protected function generateId() {
3600 return md5(uniqid(time()));
3601 }
3602 /**
3603 * Assemble the message body.
3604 * Returns an empty string on failure.
3605 * @access public
3606 * @throws phpmailerException
3607 * @return string The assembled message body
3608 */
3609 public function createBody()
3610 {
3611 $body = '';
3612 //Create unique IDs and preset boundaries
3613 $this->uniqueid = $this->generateId();
3614 $this->boundary[1] = '1' . $this->uniqueid;
3615 $this->boundary[2] = '2' . $this->uniqueid;
3616 $this->boundary[3] = '3' . $this->uniqueid;
3617 if ($this->sign_key_file) {
3618 $body .= $this->getMailMIME() . $this->LE;
3619 }
3620 $this->setWordWrap();
3621 $bodyEncoding = $this->Encoding;
3622 $bodyCharSet = $this->CharSet;
3623 //Can we do a 7-bit downgrade?
3624 if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
3625 $bodyEncoding = '7bit';
3626 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
3627 $bodyCharSet = 'us-ascii';
3628 }
3629 //If lines are too long, and we're not already using an encoding that will shorten them,
3630 //change to quoted-printable transfer encoding for the body part only
3631 if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) {
3632 $bodyEncoding = 'quoted-printable';
3633 }
3634 $altBodyEncoding = $this->Encoding;
3635 $altBodyCharSet = $this->CharSet;
3636 //Can we do a 7-bit downgrade?
3637 if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
3638 $altBodyEncoding = '7bit';
3639 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
3640 $altBodyCharSet = 'us-ascii';
3641 }
3642 //If lines are too long, and we're not already using an encoding that will shorten them,
3643 //change to quoted-printable transfer encoding for the alt body part only
3644 if ('base64' != $altBodyEncoding and self::hasLineLongerThanMax($this->AltBody)) {
3645 $altBodyEncoding = 'quoted-printable';
3646 }
3647 //Use this as a preamble in all multipart message types
3648 $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE;
3649 switch ($this->message_type) {
3650 case 'inline':
3651 $body .= $mimepre;
3652 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
3653 $body .= $this->encodeString($this->Body, $bodyEncoding);
3654 $body .= $this->LE . $this->LE;
3655 $body .= $this->attachAll('inline', $this->boundary[1]);
3656 break;
3657 case 'attach':
3658 $body .= $mimepre;
3659 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
3660 $body .= $this->encodeString($this->Body, $bodyEncoding);
3661 $body .= $this->LE . $this->LE;
3662 $body .= $this->attachAll('attachment', $this->boundary[1]);
3663 break;
3664 case 'inline_attach':
3665 $body .= $mimepre;
3666 $body .= $this->textLine('--' . $this->boundary[1]);
3667 $body .= $this->headerLine('Content-Type', 'multipart/related;');
3668 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
3669 $body .= $this->LE;
3670 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
3671 $body .= $this->encodeString($this->Body, $bodyEncoding);
3672 $body .= $this->LE . $this->LE;
3673 $body .= $this->attachAll('inline', $this->boundary[2]);
3674 $body .= $this->LE;
3675 $body .= $this->attachAll('attachment', $this->boundary[1]);
3676 break;
3677 case 'alt':
3678 $body .= $mimepre;
3679 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
3680 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
3681 $body .= $this->LE . $this->LE;
3682 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
3683 $body .= $this->encodeString($this->Body, $bodyEncoding);
3684 $body .= $this->LE . $this->LE;
3685 if (!empty($this->Ical)) {
3686 $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
3687 $body .= $this->encodeString($this->Ical, $this->Encoding);
3688 $body .= $this->LE . $this->LE;
3689 }
3690 $body .= $this->endBoundary($this->boundary[1]);
3691 break;
3692 case 'alt_inline':
3693 $body .= $mimepre;
3694 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
3695 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
3696 $body .= $this->LE . $this->LE;
3697 $body .= $this->textLine('--' . $this->boundary[1]);
3698 $body .= $this->headerLine('Content-Type', 'multipart/related;');
3699 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
3700 $body .= $this->LE;
3701 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
3702 $body .= $this->encodeString($this->Body, $bodyEncoding);
3703 $body .= $this->LE . $this->LE;
3704 $body .= $this->attachAll('inline', $this->boundary[2]);
3705 $body .= $this->LE;
3706 $body .= $this->endBoundary($this->boundary[1]);
3707 break;
3708 case 'alt_attach':
3709 $body .= $mimepre;
3710 $body .= $this->textLine('--' . $this->boundary[1]);
3711 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
3712 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
3713 $body .= $this->LE;
3714 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
3715 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
3716 $body .= $this->LE . $this->LE;
3717 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
3718 $body .= $this->encodeString($this->Body, $bodyEncoding);
3719 $body .= $this->LE . $this->LE;
3720 $body .= $this->endBoundary($this->boundary[2]);
3721 $body .= $this->LE;
3722 $body .= $this->attachAll('attachment', $this->boundary[1]);
3723 break;
3724 case 'alt_inline_attach':
3725 $body .= $mimepre;
3726 $body .= $this->textLine('--' . $this->boundary[1]);
3727 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
3728 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
3729 $body .= $this->LE;
3730 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
3731 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
3732 $body .= $this->LE . $this->LE;
3733 $body .= $this->textLine('--' . $this->boundary[2]);
3734 $body .= $this->headerLine('Content-Type', 'multipart/related;');
3735 $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
3736 $body .= $this->LE;
3737 $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
3738 $body .= $this->encodeString($this->Body, $bodyEncoding);
3739 $body .= $this->LE . $this->LE;
3740 $body .= $this->attachAll('inline', $this->boundary[3]);
3741 $body .= $this->LE;
3742 $body .= $this->endBoundary($this->boundary[2]);
3743 $body .= $this->LE;
3744 $body .= $this->attachAll('attachment', $this->boundary[1]);
3745 break;
3746 default:
3747 // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
3748 //Reset the `Encoding` property in case we changed it for line length reasons
3749 $this->Encoding = $bodyEncoding;
3750 $body .= $this->encodeString($this->Body, $this->Encoding);
3751 break;
3752 }
3753 if ($this->isError()) {
3754 $body = '';
3755 } elseif ($this->sign_key_file) {
3756 try {
3757 if (!defined('PKCS7_TEXT')) {
3758 throw new phpmailerException($this->lang('extension_missing') . 'openssl');
3759 }
3760 // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
3761 $file = tempnam(sys_get_temp_dir(), 'mail');
3762 if (false === file_put_contents($file, $body)) {
3763 throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
3764 }
3765 $signed = tempnam(sys_get_temp_dir(), 'signed');
3766 //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
3767 if (empty($this->sign_extracerts_file)) {
3768 $sign = @openssl_pkcs7_sign(
3769 $file,
3770 $signed,
3771 'file://' . realpath($this->sign_cert_file),
3772 array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
3773 null
3774 );
3775 } else {
3776 $sign = @openssl_pkcs7_sign(
3777 $file,
3778 $signed,
3779 'file://' . realpath($this->sign_cert_file),
3780 array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
3781 null,
3782 PKCS7_DETACHED,
3783 $this->sign_extracerts_file
3784 );
3785 }
3786 if ($sign) {
3787 @unlink($file);
3788 $body = file_get_contents($signed);
3789 @unlink($signed);
3790 //The message returned by openssl contains both headers and body, so need to split them up
3791 $parts = explode("\n\n", $body, 2);
3792 $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE;
3793 $body = $parts[1];
3794 } else {
3795 @unlink($file);
3796 @unlink($signed);
3797 throw new phpmailerException($this->lang('signing') . openssl_error_string());
3798 }
3799 } catch (phpmailerException $exc) {
3800 $body = '';
3801 if ($this->exceptions) {
3802 throw $exc;
3803 }
3804 }
3805 }
3806 return $body;
3807 }
3808 /**
3809 * Return the start of a message boundary.
3810 * @access protected
3811 * @param string $boundary
3812 * @param string $charSet
3813 * @param string $contentType
3814 * @param string $encoding
3815 * @return string
3816 */
3817 protected function getBoundary($boundary, $charSet, $contentType, $encoding)
3818 {
3819 $result = '';
3820 if ($charSet == '') {
3821 $charSet = $this->CharSet;
3822 }
3823 if ($contentType == '') {
3824 $contentType = $this->ContentType;
3825 }
3826 if ($encoding == '') {
3827 $encoding = $this->Encoding;
3828 }
3829 $result .= $this->textLine('--' . $boundary);
3830 $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
3831 $result .= $this->LE;
3832 // RFC1341 part 5 says 7bit is assumed if not specified
3833 if ($encoding != '7bit') {
3834 $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
3835 }
3836 $result .= $this->LE;
3837 return $result;
3838 }
3839 /**
3840 * Return the end of a message boundary.
3841 * @access protected
3842 * @param string $boundary
3843 * @return string
3844 */
3845 protected function endBoundary($boundary)
3846 {
3847 return $this->LE . '--' . $boundary . '--' . $this->LE;
3848 }
3849 /**
3850 * Set the message type.
3851 * PHPMailer only supports some preset message types, not arbitrary MIME structures.
3852 * @access protected
3853 * @return void
3854 */
3855 protected function setMessageType()
3856 {
3857 $type = array();
3858 if ($this->alternativeExists()) {
3859 $type[] = 'alt';
3860 }
3861 if ($this->inlineImageExists()) {
3862 $type[] = 'inline';
3863 }
3864 if ($this->attachmentExists()) {
3865 $type[] = 'attach';
3866 }
3867 $this->message_type = implode('_', $type);
3868 if ($this->message_type == '') {
3869 //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
3870 $this->message_type = 'plain';
3871 }
3872 }
3873 /**
3874 * Format a header line.
3875 * @access public
3876 * @param string $name
3877 * @param string $value
3878 * @return string
3879 */
3880 public function headerLine($name, $value)
3881 {
3882 return $name . ': ' . $value . $this->LE;
3883 }
3884 /**
3885 * Return a formatted mail line.
3886 * @access public
3887 * @param string $value
3888 * @return string
3889 */
3890 public function textLine($value)
3891 {
3892 return $value . $this->LE;
3893 }
3894 /**
3895 * Add an attachment from a path on the filesystem.
3896 * Returns false if the file could not be found or read.
3897 * @param string $path Path to the attachment.
3898 * @param string $name Overrides the attachment name.
3899 * @param string $encoding File encoding (see $Encoding).
3900 * @param string $type File extension (MIME) type.
3901 * @param string $disposition Disposition to use
3902 * @throws phpmailerException
3903 * @return boolean
3904 */
3905 public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
3906 {
3907 try {
3908 if (!@is_file($path)) {
3909 throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
3910 }
3911 // If a MIME type is not specified, try to work it out from the file name
3912 if ($type == '') {
3913 $type = self::filenameToType($path);
3914 }
3915 $filename = basename($path);
3916 if ($name == '') {
3917 $name = $filename;
3918 }
3919 $this->attachment[] = array(
3920 0 => $path,
3921 1 => $filename,
3922 2 => $name,
3923 3 => $encoding,
3924 4 => $type,
3925 5 => false, // isStringAttachment
3926 6 => $disposition,
3927 7 => 0
3928 );
3929 } catch (phpmailerException $exc) {
3930 $this->setError($exc->getMessage());
3931 $this->edebug($exc->getMessage());
3932 if ($this->exceptions) {
3933 throw $exc;
3934 }
3935 return false;
3936 }
3937 return true;
3938 }
3939 /**
3940 * Return the array of attachments.
3941 * @return array
3942 */
3943 public function getAttachments()
3944 {
3945 return $this->attachment;
3946 }
3947 /**
3948 * Attach all file, string, and binary attachments to the message.
3949 * Returns an empty string on failure.
3950 * @access protected
3951 * @param string $disposition_type
3952 * @param string $boundary
3953 * @return string
3954 */
3955 protected function attachAll($disposition_type, $boundary)
3956 {
3957 // Return text of body
3958 $mime = array();
3959 $cidUniq = array();
3960 $incl = array();
3961 // Add all attachments
3962 foreach ($this->attachment as $attachment) {
3963 // Check if it is a valid disposition_filter
3964 if ($attachment[6] == $disposition_type) {
3965 // Check for string attachment
3966 $string = '';
3967 $path = '';
3968 $bString = $attachment[5];
3969 if ($bString) {
3970 $string = $attachment[0];
3971 } else {
3972 $path = $attachment[0];
3973 }
3974 $inclhash = md5(serialize($attachment));
3975 if (in_array($inclhash, $incl)) {
3976 continue;
3977 }
3978 $incl[] = $inclhash;
3979 $name = $attachment[2];
3980 $encoding = $attachment[3];
3981 $type = $attachment[4];
3982 $disposition = $attachment[6];
3983 $cid = $attachment[7];
3984 if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) {
3985 continue;
3986 }
3987 $cidUniq[$cid] = true;
3988 $mime[] = sprintf('--%s%s', $boundary, $this->LE);
3989 //Only include a filename property if we have one
3990 if (!empty($name)) {
3991 $mime[] = sprintf(
3992 'Content-Type: %s; name="%s"%s',
3993 $type,
3994 $this->encodeHeader($this->secureHeader($name)),
3995 $this->LE
3996 );
3997 } else {
3998 $mime[] = sprintf(
3999 'Content-Type: %s%s',
4000 $type,
4001 $this->LE
4002 );
4003 }
4004 // RFC1341 part 5 says 7bit is assumed if not specified
4005 if ($encoding != '7bit') {
4006 $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
4007 }
4008 if ($disposition == 'inline') {
4009 $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
4010 }
4011 // If a filename contains any of these chars, it should be quoted,
4012 // but not otherwise: RFC2183 & RFC2045 5.1
4013 // Fixes a warning in IETF's msglint MIME checker
4014 // Allow for bypassing the Content-Disposition header totally
4015 if (!(empty($disposition))) {
4016 $encoded_name = $this->encodeHeader($this->secureHeader($name));
4017 if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
4018 $mime[] = sprintf(
4019 'Content-Disposition: %s; filename="%s"%s',
4020 $disposition,
4021 $encoded_name,
4022 $this->LE . $this->LE
4023 );
4024 } else {
4025 if (!empty($encoded_name)) {
4026 $mime[] = sprintf(
4027 'Content-Disposition: %s; filename=%s%s',
4028 $disposition,
4029 $encoded_name,
4030 $this->LE . $this->LE
4031 );
4032 } else {
4033 $mime[] = sprintf(
4034 'Content-Disposition: %s%s',
4035 $disposition,
4036 $this->LE . $this->LE
4037 );
4038 }
4039 }
4040 } else {
4041 $mime[] = $this->LE;
4042 }
4043 // Encode as string attachment
4044 if ($bString) {
4045 $mime[] = $this->encodeString($string, $encoding);
4046 if ($this->isError()) {
4047 return '';
4048 }
4049 $mime[] = $this->LE . $this->LE;
4050 } else {
4051 $mime[] = $this->encodeFile($path, $encoding);
4052 if ($this->isError()) {
4053 return '';
4054 }
4055 $mime[] = $this->LE . $this->LE;
4056 }
4057 }
4058 }
4059 $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
4060 return implode('', $mime);
4061 }
4062 /**
4063 * Encode a file attachment in requested format.
4064 * Returns an empty string on failure.
4065 * @param string $path The full path to the file
4066 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
4067 * @throws phpmailerException
4068 * @access protected
4069 * @return string
4070 */
4071 protected function encodeFile($path, $encoding = 'base64')
4072 {
4073 try {
4074 if (!is_readable($path)) {
4075 throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
4076 }
4077 $magic_quotes = get_magic_quotes_runtime();
4078 if ($magic_quotes) {
4079 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
4080 set_magic_quotes_runtime(false);
4081 } else {
4082 //Doesn't exist in PHP 5.4, but we don't need to check because
4083 //get_magic_quotes_runtime always returns false in 5.4+
4084 //so it will never get here
4085 ini_set('magic_quotes_runtime', false);
4086 }
4087 }
4088 $file_buffer = file_get_contents($path);
4089 $file_buffer = $this->encodeString($file_buffer, $encoding);
4090 if ($magic_quotes) {
4091 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
4092 set_magic_quotes_runtime($magic_quotes);
4093 } else {
4094 ini_set('magic_quotes_runtime', $magic_quotes);
4095 }
4096 }
4097 return $file_buffer;
4098 } catch (Exception $exc) {
4099 $this->setError($exc->getMessage());
4100 return '';
4101 }
4102 }
4103 /**
4104 * Encode a string in requested format.
4105 * Returns an empty string on failure.
4106 * @param string $str The text to encode
4107 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
4108 * @access public
4109 * @return string
4110 */
4111 public function encodeString($str, $encoding = 'base64')
4112 {
4113 $encoded = '';
4114 switch (strtolower($encoding)) {
4115 case 'base64':
4116 $encoded = chunk_split(base64_encode($str), 76, $this->LE);
4117 break;
4118 case '7bit':
4119 case '8bit':
4120 $encoded = $this->fixEOL($str);
4121 // Make sure it ends with a line break
4122 if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
4123 $encoded .= $this->LE;
4124 }
4125 break;
4126 case 'binary':
4127 $encoded = $str;
4128 break;
4129 case 'quoted-printable':
4130 $encoded = $this->encodeQP($str);
4131 break;
4132 default:
4133 $this->setError($this->lang('encoding') . $encoding);
4134 break;
4135 }
4136 return $encoded;
4137 }
4138 /**
4139 * Encode a header string optimally.
4140 * Picks shortest of Q, B, quoted-printable or none.
4141 * @access public
4142 * @param string $str
4143 * @param string $position
4144 * @return string
4145 */
4146 public function encodeHeader($str, $position = 'text')
4147 {
4148 $matchcount = 0;
4149 switch (strtolower($position)) {
4150 case 'phrase':
4151 if (!preg_match('/[\200-\377]/', $str)) {
4152 // Can't use addslashes as we don't know the value of magic_quotes_sybase
4153 $encoded = addcslashes($str, "\0..\37\177\\\"");
4154 if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
4155 return ($encoded);
4156 } else {
4157 return ("\"$encoded\"");
4158 }
4159 }
4160 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
4161 break;
4162 /** @noinspection PhpMissingBreakStatementInspection */
4163 case 'comment':
4164 $matchcount = preg_match_all('/[()"]/', $str, $matches);
4165 // Intentional fall-through
4166 case 'text':
4167 default:
4168 $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
4169 break;
4170 }
4171 //There are no chars that need encoding
4172 if ($matchcount == 0) {
4173 return ($str);
4174 }
4175 $maxlen = 75 - 7 - strlen($this->CharSet);
4176 // Try to select the encoding which should produce the shortest output
4177 if ($matchcount > strlen($str) / 3) {
4178 // More than a third of the content will need encoding, so B encoding will be most efficient
4179 $encoding = 'B';
4180 if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
4181 // Use a custom function which correctly encodes and wraps long
4182 // multibyte strings without breaking lines within a character
4183 $encoded = $this->base64EncodeWrapMB($str, "\n");
4184 } else {
4185 $encoded = base64_encode($str);
4186 $maxlen -= $maxlen % 4;
4187 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
4188 }
4189 } else {
4190 $encoding = 'Q';
4191 $encoded = $this->encodeQ($str, $position);
4192 $encoded = $this->wrapText($encoded, $maxlen, true);
4193 $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
4194 }
4195 $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
4196 $encoded = trim(str_replace("\n", $this->LE, $encoded));
4197 return $encoded;
4198 }
4199 /**
4200 * Check if a string contains multi-byte characters.
4201 * @access public
4202 * @param string $str multi-byte text to wrap encode
4203 * @return boolean
4204 */
4205 public function hasMultiBytes($str)
4206 {
4207 if (function_exists('mb_strlen')) {
4208 return (strlen($str) > mb_strlen($str, $this->CharSet));
4209 } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
4210 return false;
4211 }
4212 }
4213 /**
4214 * Does a string contain any 8-bit chars (in any charset)?
4215 * @param string $text
4216 * @return boolean
4217 */
4218 public function has8bitChars($text)
4219 {
4220 return (boolean)preg_match('/[\x80-\xFF]/', $text);
4221 }
4222 /**
4223 * Encode and wrap long multibyte strings for mail headers
4224 * without breaking lines within a character.
4225 * Adapted from a function by paravoid
4226 * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
4227 * @access public
4228 * @param string $str multi-byte text to wrap encode
4229 * @param string $linebreak string to use as linefeed/end-of-line
4230 * @return string
4231 */
4232 public function base64EncodeWrapMB($str, $linebreak = null)
4233 {
4234 $start = '=?' . $this->CharSet . '?B?';
4235 $end = '?=';
4236 $encoded = '';
4237 if ($linebreak === null) {
4238 $linebreak = $this->LE;
4239 }
4240 $mb_length = mb_strlen($str, $this->CharSet);
4241 // Each line must have length <= 75, including $start and $end
4242 $length = 75 - strlen($start) - strlen($end);
4243 // Average multi-byte ratio
4244 $ratio = $mb_length / strlen($str);
4245 // Base64 has a 4:3 ratio
4246 $avgLength = floor($length * $ratio * .75);
4247 for ($i = 0; $i < $mb_length; $i += $offset) {
4248 $lookBack = 0;
4249 do {
4250 $offset = $avgLength - $lookBack;
4251 $chunk = mb_substr($str, $i, $offset, $this->CharSet);
4252 $chunk = base64_encode($chunk);
4253 $lookBack++;
4254 } while (strlen($chunk) > $length);
4255 $encoded .= $chunk . $linebreak;
4256 }
4257 // Chomp the last linefeed
4258 $encoded = substr($encoded, 0, -strlen($linebreak));
4259 return $encoded;
4260 }
4261 /**
4262 * Encode a string in quoted-printable format.
4263 * According to RFC2045 section 6.7.
4264 * @access public
4265 * @param string $string The text to encode
4266 * @param integer $line_max Number of chars allowed on a line before wrapping
4267 * @return string
4268 * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
4269 */
4270 public function encodeQP($string, $line_max = 76)
4271 {
4272 // Use native function if it's available (>= PHP5.3)
4273 if (function_exists('quoted_printable_encode')) {
4274 return quoted_printable_encode($string);
4275 }
4276 // Fall back to a pure PHP implementation
4277 $string = str_replace(
4278 array('%20', '%0D%0A.', '%0D%0A', '%'),
4279 array(' ', "\r\n=2E", "\r\n", '='),
4280 rawurlencode($string)
4281 );
4282 return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
4283 }
4284 /**
4285 * Backward compatibility wrapper for an old QP encoding function that was removed.
4286 * @see PHPMailer::encodeQP()
4287 * @access public
4288 * @param string $string
4289 * @param integer $line_max
4290 * @param boolean $space_conv
4291 * @return string
4292 * @deprecated Use encodeQP instead.
4293 */
4294 public function encodeQPphp(
4295 $string,
4296 $line_max = 76,
4297 /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
4298 ) {
4299 return $this->encodeQP($string, $line_max);
4300 }
4301 /**
4302 * Encode a string using Q encoding.
4303 * @link http://tools.ietf.org/html/rfc2047
4304 * @param string $str the text to encode
4305 * @param string $position Where the text is going to be used, see the RFC for what that means
4306 * @access public
4307 * @return string
4308 */
4309 public function encodeQ($str, $position = 'text')
4310 {
4311 // There should not be any EOL in the string
4312 $pattern = '';
4313 $encoded = str_replace(array("\r", "\n"), '', $str);
4314 switch (strtolower($position)) {
4315 case 'phrase':
4316 // RFC 2047 section 5.3
4317 $pattern = '^A-Za-z0-9!*+\/ -';
4318 break;
4319 /** @noinspection PhpMissingBreakStatementInspection */
4320 case 'comment':
4321 // RFC 2047 section 5.2
4322 $pattern = '\(\)"';
4323 // intentional fall-through
4324 // for this reason we build the $pattern without including delimiters and []
4325 case 'text':
4326 default:
4327 // RFC 2047 section 5.1
4328 // Replace every high ascii, control, =, ? and _ characters
4329 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
4330 break;
4331 }
4332 $matches = array();
4333 if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
4334 // If the string contains an '=', make sure it's the first thing we replace
4335 // so as to avoid double-encoding
4336 $eqkey = array_search('=', $matches[0]);
4337 if (false !== $eqkey) {
4338 unset($matches[0][$eqkey]);
4339 array_unshift($matches[0], '=');
4340 }
4341 foreach (array_unique($matches[0]) as $char) {
4342 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
4343 }
4344 }
4345 // Replace every spaces to _ (more readable than =20)
4346 return str_replace(' ', '_', $encoded);
4347 }
4348 /**
4349 * Add a string or binary attachment (non-filesystem).
4350 * This method can be used to attach ascii or binary data,
4351 * such as a BLOB record from a database.
4352 * @param string $string String attachment data.
4353 * @param string $filename Name of the attachment.
4354 * @param string $encoding File encoding (see $Encoding).
4355 * @param string $type File extension (MIME) type.
4356 * @param string $disposition Disposition to use
4357 * @return void
4358 */
4359 public function addStringAttachment(
4360 $string,
4361 $filename,
4362 $encoding = 'base64',
4363 $type = '',
4364 $disposition = 'attachment'
4365 ) {
4366 // If a MIME type is not specified, try to work it out from the file name
4367 if ($type == '') {
4368 $type = self::filenameToType($filename);
4369 }
4370 // Append to $attachment array
4371 $this->attachment[] = array(
4372 0 => $string,
4373 1 => $filename,
4374 2 => basename($filename),
4375 3 => $encoding,
4376 4 => $type,
4377 5 => true, // isStringAttachment
4378 6 => $disposition,
4379 7 => 0
4380 );
4381 }
4382 /**
4383 * Add an embedded (inline) attachment from a file.
4384 * This can include images, sounds, and just about any other document type.
4385 * These differ from 'regular' attachments in that they are intended to be
4386 * displayed inline with the message, not just attached for download.
4387 * This is used in HTML messages that embed the images
4388 * the HTML refers to using the $cid value.
4389 * @param string $path Path to the attachment.
4390 * @param string $cid Content ID of the attachment; Use this to reference
4391 * the content when using an embedded image in HTML.
4392 * @param string $name Overrides the attachment name.
4393 * @param string $encoding File encoding (see $Encoding).
4394 * @param string $type File MIME type.
4395 * @param string $disposition Disposition to use
4396 * @return boolean True on successfully adding an attachment
4397 */
4398 public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
4399 {
4400 if (!@is_file($path)) {
4401 $this->setError($this->lang('file_access') . $path);
4402 return false;
4403 }
4404 // If a MIME type is not specified, try to work it out from the file name
4405 if ($type == '') {
4406 $type = self::filenameToType($path);
4407 }
4408 $filename = basename($path);
4409 if ($name == '') {
4410 $name = $filename;
4411 }
4412 // Append to $attachment array
4413 $this->attachment[] = array(
4414 0 => $path,
4415 1 => $filename,
4416 2 => $name,
4417 3 => $encoding,
4418 4 => $type,
4419 5 => false, // isStringAttachment
4420 6 => $disposition,
4421 7 => $cid
4422 );
4423 return true;
4424 }
4425 /**
4426 * Add an embedded stringified attachment.
4427 * This can include images, sounds, and just about any other document type.
4428 * Be sure to set the $type to an image type for images:
4429 * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
4430 * @param string $string The attachment binary data.
4431 * @param string $cid Content ID of the attachment; Use this to reference
4432 * the content when using an embedded image in HTML.
4433 * @param string $name
4434 * @param string $encoding File encoding (see $Encoding).
4435 * @param string $type MIME type.
4436 * @param string $disposition Disposition to use
4437 * @return boolean True on successfully adding an attachment
4438 */
4439 public function addStringEmbeddedImage(
4440 $string,
4441 $cid,
4442 $name = '',
4443 $encoding = 'base64',
4444 $type = '',
4445 $disposition = 'inline'
4446 ) {
4447 // If a MIME type is not specified, try to work it out from the name
4448 if ($type == '' and !empty($name)) {
4449 $type = self::filenameToType($name);
4450 }
4451 // Append to $attachment array
4452 $this->attachment[] = array(
4453 0 => $string,
4454 1 => $name,
4455 2 => $name,
4456 3 => $encoding,
4457 4 => $type,
4458 5 => true, // isStringAttachment
4459 6 => $disposition,
4460 7 => $cid
4461 );
4462 return true;
4463 }
4464 /**
4465 * Check if an inline attachment is present.
4466 * @access public
4467 * @return boolean
4468 */
4469 public function inlineImageExists()
4470 {
4471 foreach ($this->attachment as $attachment) {
4472 if ($attachment[6] == 'inline') {
4473 return true;
4474 }
4475 }
4476 return false;
4477 }
4478 /**
4479 * Check if an attachment (non-inline) is present.
4480 * @return boolean
4481 */
4482 public function attachmentExists()
4483 {
4484 foreach ($this->attachment as $attachment) {
4485 if ($attachment[6] == 'attachment') {
4486 return true;
4487 }
4488 }
4489 return false;
4490 }
4491 /**
4492 * Check if this message has an alternative body set.
4493 * @return boolean
4494 */
4495 public function alternativeExists()
4496 {
4497 return !empty($this->AltBody);
4498 }
4499 /**
4500 * Clear queued addresses of given kind.
4501 * @access protected
4502 * @param string $kind 'to', 'cc', or 'bcc'
4503 * @return void
4504 */
4505 public function clearQueuedAddresses($kind)
4506 {
4507 $RecipientsQueue = $this->RecipientsQueue;
4508 foreach ($RecipientsQueue as $address => $params) {
4509 if ($params[0] == $kind) {
4510 unset($this->RecipientsQueue[$address]);
4511 }
4512 }
4513 }
4514 /**
4515 * Clear all To recipients.
4516 * @return void
4517 */
4518 public function clearAddresses()
4519 {
4520 foreach ($this->to as $to) {
4521 unset($this->all_recipients[strtolower($to[0])]);
4522 }
4523 $this->to = array();
4524 $this->clearQueuedAddresses('to');
4525 }
4526 /**
4527 * Clear all CC recipients.
4528 * @return void
4529 */
4530 public function clearCCs()
4531 {
4532 foreach ($this->cc as $cc) {
4533 unset($this->all_recipients[strtolower($cc[0])]);
4534 }
4535 $this->cc = array();
4536 $this->clearQueuedAddresses('cc');
4537 }
4538 /**
4539 * Clear all BCC recipients.
4540 * @return void
4541 */
4542 public function clearBCCs()
4543 {
4544 foreach ($this->bcc as $bcc) {
4545 unset($this->all_recipients[strtolower($bcc[0])]);
4546 }
4547 $this->bcc = array();
4548 $this->clearQueuedAddresses('bcc');
4549 }
4550 /**
4551 * Clear all ReplyTo recipients.
4552 * @return void
4553 */
4554 public function clearReplyTos()
4555 {
4556 $this->ReplyTo = array();
4557 $this->ReplyToQueue = array();
4558 }
4559 /**
4560 * Clear all recipient types.
4561 * @return void
4562 */
4563 public function clearAllRecipients()
4564 {
4565 $this->to = array();
4566 $this->cc = array();
4567 $this->bcc = array();
4568 $this->all_recipients = array();
4569 $this->RecipientsQueue = array();
4570 }
4571 /**
4572 * Clear all filesystem, string, and binary attachments.
4573 * @return void
4574 */
4575 public function clearAttachments()
4576 {
4577 $this->attachment = array();
4578 }
4579 /**
4580 * Clear all custom headers.
4581 * @return void
4582 */
4583 public function clearCustomHeaders()
4584 {
4585 $this->CustomHeader = array();
4586 }
4587 /**
4588 * Add an error message to the error container.
4589 * @access protected
4590 * @param string $msg
4591 * @return void
4592 */
4593 protected function setError($msg)
4594 {
4595 $this->error_count++;
4596 if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
4597 $lasterror = $this->smtp->getError();
4598 if (!empty($lasterror['error'])) {
4599 $msg .= $this->lang('smtp_error') . $lasterror['error'];
4600 if (!empty($lasterror['detail'])) {
4601 $msg .= ' Detail: '. $lasterror['detail'];
4602 }
4603 if (!empty($lasterror['smtp_code'])) {
4604 $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
4605 }
4606 if (!empty($lasterror['smtp_code_ex'])) {
4607 $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
4608 }
4609 }
4610 }
4611 $this->ErrorInfo = $msg;
4612 }
4613 /**
4614 * Return an RFC 822 formatted date.
4615 * @access public
4616 * @return string
4617 * @static
4618 */
4619 public static function rfcDate()
4620 {
4621 // Set the time zone to whatever the default is to avoid 500 errors
4622 // Will default to UTC if it's not set properly in php.ini
4623 date_default_timezone_set(@date_default_timezone_get());
4624 return date('D, j M Y H:i:s O');
4625 }
4626 /**
4627 * Get the server hostname.
4628 * Returns 'localhost.localdomain' if unknown.
4629 * @access protected
4630 * @return string
4631 */
4632 protected function serverHostname()
4633 {
4634 $result = 'localhost.localdomain';
4635 if (!empty($this->Hostname)) {
4636 $result = $this->Hostname;
4637 } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
4638 $result = $_SERVER['SERVER_NAME'];
4639 } elseif (function_exists('gethostname') && gethostname() !== false) {
4640 $result = gethostname();
4641 } elseif (php_uname('n') !== false) {
4642 $result = php_uname('n');
4643 }
4644 return $result;
4645 }
4646 /**
4647 * Get an error message in the current language.
4648 * @access protected
4649 * @param string $key
4650 * @return string
4651 */
4652 protected function lang($key)
4653 {
4654 if (count($this->language) < 1) {
4655 $this->setLanguage('en'); // set the default language
4656 }
4657 if (array_key_exists($key, $this->language)) {
4658 if ($key == 'smtp_connect_failed') {
4659 //Include a link to troubleshooting docs on SMTP connection failure
4660 //this is by far the biggest cause of support questions
4661 //but it's usually not PHPMailer's fault.
4662 return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
4663 }
4664 return $this->language[$key];
4665 } else {
4666 //Return the key as a fallback
4667 return $key;
4668 }
4669 }
4670 /**
4671 * Check if an error occurred.
4672 * @access public
4673 * @return boolean True if an error did occur.
4674 */
4675 public function isError()
4676 {
4677 return ($this->error_count > 0);
4678 }
4679 /**
4680 * Ensure consistent line endings in a string.
4681 * Changes every end of line from CRLF, CR or LF to $this->LE.
4682 * @access public
4683 * @param string $str String to fixEOL
4684 * @return string
4685 */
4686 public function fixEOL($str)
4687 {
4688 // Normalise to \n
4689 $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
4690 // Now convert LE as needed
4691 if ($this->LE !== "\n") {
4692 $nstr = str_replace("\n", $this->LE, $nstr);
4693 }
4694 return $nstr;
4695 }
4696 /**
4697 * Add a custom header.
4698 * $name value can be overloaded to contain
4699 * both header name and value (name:value)
4700 * @access public
4701 * @param string $name Custom header name
4702 * @param string $value Header value
4703 * @return void
4704 */
4705 public function addCustomHeader($name, $value = null,$overwrite = false)
4706 {
4707 if ($value === null)
4708 {
4709 $header = explode(':', $name, 2);
4710 $name = $header[0];
4711 }
4712 if ($overwrite)
4713 {
4714 $this->CustomHeader[$name] = isset($header) ? $header : array($name, $value);
4715 }
4716 else
4717 {
4718 $this->CustomHeader[] = isset($header) ? $header : array($name, $value);
4719 }
4720 }
4721 /**
4722 * Returns all custom headers.
4723 * @return array
4724 */
4725 public function getCustomHeaders()
4726 {
4727 return array_values($this->CustomHeader);
4728 }
4729 /**
4730 * Create a message body from an HTML string.
4731 * Automatically inlines images and creates a plain-text version by converting the HTML,
4732 * overwriting any existing values in Body and AltBody.
4733 * $basedir is used when handling relative image paths, e.g. <img src="images/a.png">
4734 * will look for an image file in $basedir/images/a.png and convert it to inline.
4735 * If you don't want to apply these transformations to your HTML, just set Body and AltBody yourself.
4736 * @access public
4737 * @param string $message HTML message string
4738 * @param string $basedir base directory for relative paths to images
4739 * @param boolean|callable $advanced Whether to use the internal HTML to text converter
4740 * or your own custom converter @see PHPMailer::html2text()
4741 * @return string $message The transformed message Body
4742 */
4743 public function msgHTML($message, $basedir = '', $advanced = false)
4744 {
4745 preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
4746 if (array_key_exists(2, $images)) {
4747 foreach ($images[2] as $imgindex => $url) {
4748 // Convert data URIs into embedded images
4749 if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
4750 $data = substr($url, strpos($url, ','));
4751 if ($match[2]) {
4752 $data = base64_decode($data);
4753 } else {
4754 $data = rawurldecode($data);
4755 }
4756 $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
4757 if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) {
4758 $message = str_replace(
4759 $images[0][$imgindex],
4760 $images[1][$imgindex] . '="cid:' . $cid . '"',
4761 $message
4762 );
4763 }
4764 } elseif (substr($url, 0, 4) !== 'cid:' && !preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) {
4765 // Do not change urls for absolute images (thanks to corvuscorax)
4766 // Do not change urls that are already inline images
4767 $filename = basename($url);
4768 $directory = dirname($url);
4769 if ($directory == '.') {
4770 $directory = '';
4771 }
4772 $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
4773 if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
4774 $basedir .= '/';
4775 }
4776 if (strlen($directory) > 1 && substr($directory, -1) != '/') {
4777 $directory .= '/';
4778 }
4779 if ($this->addEmbeddedImage(
4780 $basedir . $directory . $filename,
4781 $cid,
4782 $filename,
4783 'base64',
4784 self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
4785 )
4786 ) {
4787 $message = preg_replace(
4788 '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
4789 $images[1][$imgindex] . '="cid:' . $cid . '"',
4790 $message
4791 );
4792 }
4793 }
4794 }
4795 }
4796 $this->isHTML(true);
4797 // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
4798 $this->Body = $this->normalizeBreaks($message);
4799 $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
4800 if (!$this->alternativeExists()) {
4801 $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
4802 self::CRLF . self::CRLF;
4803 }
4804 return $this->Body;
4805 }
4806 /**
4807 * Convert an HTML string into plain text.
4808 * This is used by msgHTML().
4809 * Note - older versions of this function used a bundled advanced converter
4810 * which was been removed for license reasons in #232.
4811 * Example usage:
4812 * <code>
4813 * // Use default conversion
4814 * $plain = $mail->html2text($html);
4815 * // Use your own custom converter
4816 * $plain = $mail->html2text($html, function($html) {
4817 * $converter = new MyHtml2text($html);
4818 * return $converter->get_text();
4819 * });
4820 * </code>
4821 * @param string $html The HTML text to convert
4822 * @param boolean|callable $advanced Any boolean value to use the internal converter,
4823 * or provide your own callable for custom conversion.
4824 * @return string
4825 */
4826 public function html2text($html, $advanced = false)
4827 {
4828 if (is_callable($advanced)) {
4829 return call_user_func($advanced, $html);
4830 }
4831 return html_entity_decode(
4832 trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
4833 ENT_QUOTES,
4834 $this->CharSet
4835 );
4836 }
4837 /**
4838 * Get the MIME type for a file extension.
4839 * @param string $ext File extension
4840 * @access public
4841 * @return string MIME type of file.
4842 * @static
4843 */
4844 public static function _mime_types($ext = '')
4845 {
4846 $mimes = array(
4847 'xl' => 'application/excel',
4848 'js' => 'application/javascript',
4849 'hqx' => 'application/mac-binhex40',
4850 'cpt' => 'application/mac-compactpro',
4851 'bin' => 'application/macbinary',
4852 'doc' => 'application/msword',
4853 'word' => 'application/msword',
4854 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
4855 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
4856 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
4857 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
4858 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
4859 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
4860 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
4861 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
4862 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
4863 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
4864 'class' => 'application/octet-stream',
4865 'dll' => 'application/octet-stream',
4866 'dms' => 'application/octet-stream',
4867 'exe' => 'application/octet-stream',
4868 'lha' => 'application/octet-stream',
4869 'lzh' => 'application/octet-stream',
4870 'psd' => 'application/octet-stream',
4871 'sea' => 'application/octet-stream',
4872 'so' => 'application/octet-stream',
4873 'oda' => 'application/oda',
4874 'pdf' => 'application/pdf',
4875 'ai' => 'application/postscript',
4876 'eps' => 'application/postscript',
4877 'ps' => 'application/postscript',
4878 'smi' => 'application/smil',
4879 'smil' => 'application/smil',
4880 'mif' => 'application/vnd.mif',
4881 'xls' => 'application/vnd.ms-excel',
4882 'ppt' => 'application/vnd.ms-powerpoint',
4883 'wbxml' => 'application/vnd.wap.wbxml',
4884 'wmlc' => 'application/vnd.wap.wmlc',
4885 'dcr' => 'application/x-director',
4886 'dir' => 'application/x-director',
4887 'dxr' => 'application/x-director',
4888 'dvi' => 'application/x-dvi',
4889 'gtar' => 'application/x-gtar',
4890 'php3' => 'application/x-httpd-php',
4891 'php4' => 'application/x-httpd-php',
4892 'php' => 'application/x-httpd-php',
4893 'phtml' => 'application/x-httpd-php',
4894 'phps' => 'application/x-httpd-php-source',
4895 'swf' => 'application/x-shockwave-flash',
4896 'sit' => 'application/x-stuffit',
4897 'tar' => 'application/x-tar',
4898 'tgz' => 'application/x-tar',
4899 'xht' => 'application/xhtml+xml',
4900 'xhtml' => 'application/xhtml+xml',
4901 'zip' => 'application/zip',
4902 'mid' => 'audio/midi',
4903 'midi' => 'audio/midi',
4904 'mp2' => 'audio/mpeg',
4905 'mp3' => 'audio/mpeg',
4906 'mpga' => 'audio/mpeg',
4907 'aif' => 'audio/x-aiff',
4908 'aifc' => 'audio/x-aiff',
4909 'aiff' => 'audio/x-aiff',
4910 'ram' => 'audio/x-pn-realaudio',
4911 'rm' => 'audio/x-pn-realaudio',
4912 'rpm' => 'audio/x-pn-realaudio-plugin',
4913 'ra' => 'audio/x-realaudio',
4914 'wav' => 'audio/x-wav',
4915 'bmp' => 'image/bmp',
4916 'gif' => 'image/gif',
4917 'jpeg' => 'image/jpeg',
4918 'jpe' => 'image/jpeg',
4919 'jpg' => 'image/jpeg',
4920 'png' => 'image/png',
4921 'tiff' => 'image/tiff',
4922 'tif' => 'image/tiff',
4923 'eml' => 'message/rfc822',
4924 'css' => 'text/css',
4925 'html' => 'text/html',
4926 'htm' => 'text/html',
4927 'shtml' => 'text/html',
4928 'log' => 'text/plain',
4929 'text' => 'text/plain',
4930 'txt' => 'text/plain',
4931 'rtx' => 'text/richtext',
4932 'rtf' => 'text/rtf',
4933 'vcf' => 'text/vcard',
4934 'vcard' => 'text/vcard',
4935 'xml' => 'text/xml',
4936 'xsl' => 'text/xml',
4937 'mpeg' => 'video/mpeg',
4938 'mpe' => 'video/mpeg',
4939 'mpg' => 'video/mpeg',
4940 'mov' => 'video/quicktime',
4941 'qt' => 'video/quicktime',
4942 'rv' => 'video/vnd.rn-realvideo',
4943 'avi' => 'video/x-msvideo',
4944 'movie' => 'video/x-sgi-movie'
4945 );
4946 if (array_key_exists(strtolower($ext), $mimes)) {
4947 return $mimes[strtolower($ext)];
4948 }
4949 return 'application/octet-stream';
4950 }
4951 /**
4952 * Map a file name to a MIME type.
4953 * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
4954 * @param string $filename A file name or full path, does not need to exist as a file
4955 * @return string
4956 * @static
4957 */
4958 public static function filenameToType($filename)
4959 {
4960 // In case the path is a URL, strip any query string before getting extension
4961 $qpos = strpos($filename, '?');
4962 if (false !== $qpos) {
4963 $filename = substr($filename, 0, $qpos);
4964 }
4965 $pathinfo = self::mb_pathinfo($filename);
4966 return self::_mime_types($pathinfo['extension']);
4967 }
4968 /**
4969 * Multi-byte-safe pathinfo replacement.
4970 * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
4971 * Works similarly to the one in PHP >= 5.2.0
4972 * @link http://www.php.net/manual/en/function.pathinfo.php#107461
4973 * @param string $path A filename or path, does not need to exist as a file
4974 * @param integer|string $options Either a PATHINFO_* constant,
4975 * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
4976 * @return string|array
4977 * @static
4978 */
4979 public static function mb_pathinfo($path, $options = null)
4980 {
4981 $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
4982 $pathinfo = array();
4983 if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
4984 if (array_key_exists(1, $pathinfo)) {
4985 $ret['dirname'] = $pathinfo[1];
4986 }
4987 if (array_key_exists(2, $pathinfo)) {
4988 $ret['basename'] = $pathinfo[2];
4989 }
4990 if (array_key_exists(5, $pathinfo)) {
4991 $ret['extension'] = $pathinfo[5];
4992 }
4993 if (array_key_exists(3, $pathinfo)) {
4994 $ret['filename'] = $pathinfo[3];
4995 }
4996 }
4997 switch ($options) {
4998 case PATHINFO_DIRNAME:
4999 case 'dirname':
5000 return $ret['dirname'];
5001 case PATHINFO_BASENAME:
5002 case 'basename':
5003 return $ret['basename'];
5004 case PATHINFO_EXTENSION:
5005 case 'extension':
5006 return $ret['extension'];
5007 case PATHINFO_FILENAME:
5008 case 'filename':
5009 return $ret['filename'];
5010 default:
5011 return $ret;
5012 }
5013 }
5014 /**
5015 * Set or reset instance properties.
5016 * You should avoid this function - it's more verbose, less efficient, more error-prone and
5017 * harder to debug than setting properties directly.
5018 * Usage Example:
5019 * `$mail->set('SMTPSecure', 'tls');`
5020 * is the same as:
5021 * `$mail->SMTPSecure = 'tls';`
5022 * @access public
5023 * @param string $name The property name to set
5024 * @param mixed $value The value to set the property to
5025 * @return boolean
5026 * @TODO Should this not be using the __set() magic function?
5027 */
5028 public function set($name, $value = '')
5029 {
5030 if (property_exists($this, $name)) {
5031 $this->$name = $value;
5032 return true;
5033 } else {
5034 $this->setError($this->lang('variable_set') . $name);
5035 return false;
5036 }
5037 }
5038 /**
5039 * Strip newlines to prevent header injection.
5040 * @access public
5041 * @param string $str
5042 * @return string
5043 */
5044 public function secureHeader($str)
5045 {
5046 return trim(str_replace(array("\r", "\n"), '', $str));
5047 }
5048 /**
5049 * Normalize line breaks in a string.
5050 * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
5051 * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
5052 * @param string $text
5053 * @param string $breaktype What kind of line break to use, defaults to CRLF
5054 * @return string
5055 * @access public
5056 * @static
5057 */
5058 public static function normalizeBreaks($text, $breaktype = "\r\n")
5059 {
5060 return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
5061 }
5062 /**
5063 * Set the public and private key files and password for S/MIME signing.
5064 * @access public
5065 * @param string $cert_filename
5066 * @param string $key_filename
5067 * @param string $key_pass Password for private key
5068 * @param string $extracerts_filename Optional path to chain certificate
5069 */
5070 public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
5071 {
5072 $this->sign_cert_file = $cert_filename;
5073 $this->sign_key_file = $key_filename;
5074 $this->sign_key_pass = $key_pass;
5075 $this->sign_extracerts_file = $extracerts_filename;
5076 }
5077 /**
5078 * Quoted-Printable-encode a DKIM header.
5079 * @access public
5080 * @param string $txt
5081 * @return string
5082 */
5083 public function DKIM_QP($txt)
5084 {
5085 $line = '';
5086 for ($i = 0; $i < strlen($txt); $i++) {
5087 $ord = ord($txt[$i]);
5088 if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
5089 $line .= $txt[$i];
5090 } else {
5091 $line .= '=' . sprintf('%02X', $ord);
5092 }
5093 }
5094 return $line;
5095 }
5096 /**
5097 * Generate a DKIM signature.
5098 * @access public
5099 * @param string $signHeader
5100 * @throws phpmailerException
5101 * @return string The DKIM signature value
5102 */
5103 public function DKIM_Sign($signHeader)
5104 {
5105 if (!defined('PKCS7_TEXT')) {
5106 if ($this->exceptions) {
5107 throw new phpmailerException($this->lang('extension_missing') . 'openssl');
5108 }
5109 return '';
5110 }
5111 $privKeyStr = !empty($this->DKIM_private_string) ? $this->DKIM_private_string : file_get_contents($this->DKIM_private);
5112 if ('' != $this->DKIM_passphrase) {
5113 $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
5114 } else {
5115 $privKey = openssl_pkey_get_private($privKeyStr);
5116 }
5117 //Workaround for missing digest algorithms in old PHP & OpenSSL versions
5118 //@link http://stackoverflow.com/a/11117338/333340
5119 if (version_compare(PHP_VERSION, '5.3.0') >= 0 and
5120 in_array('sha256WithRSAEncryption', openssl_get_md_methods(true))) {
5121 if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
5122 openssl_pkey_free($privKey);
5123 return base64_encode($signature);
5124 }
5125 } else {
5126 $pinfo = openssl_pkey_get_details($privKey);
5127 $hash = hash('sha256', $signHeader);
5128 //'Magic' constant for SHA256 from RFC3447
5129 //@link https://tools.ietf.org/html/rfc3447#page-43
5130 $t = '3031300d060960864801650304020105000420' . $hash;
5131 $pslen = $pinfo['bits'] / 8 - (strlen($t) / 2 + 3);
5132 $eb = pack('H*', '0001' . str_repeat('FF', $pslen) . '00' . $t);
5133 if (openssl_private_encrypt($eb, $signature, $privKey, OPENSSL_NO_PADDING)) {
5134 openssl_pkey_free($privKey);
5135 return base64_encode($signature);
5136 }
5137 }
5138 openssl_pkey_free($privKey);
5139 return '';
5140 }
5141 /**
5142 * Generate a DKIM canonicalization header.
5143 * @access public
5144 * @param string $signHeader Header
5145 * @return string
5146 */
5147 public function DKIM_HeaderC($signHeader)
5148 {
5149 $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
5150 $lines = explode("\r\n", $signHeader);
5151 foreach ($lines as $key => $line) {
5152 list($heading, $value) = explode(':', $line, 2);
5153 $heading = strtolower($heading);
5154 $value = preg_replace('/\s{2,}/', ' ', $value); // Compress useless spaces
5155 $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
5156 }
5157 $signHeader = implode("\r\n", $lines);
5158 return $signHeader;
5159 }
5160 /**
5161 * Generate a DKIM canonicalization body.
5162 * @access public
5163 * @param string $body Message Body
5164 * @return string
5165 */
5166 public function DKIM_BodyC($body)
5167 {
5168 if ($body == '') {
5169 return "\r\n";
5170 }
5171 // stabilize line endings
5172 $body = str_replace("\r\n", "\n", $body);
5173 $body = str_replace("\n", "\r\n", $body);
5174 // END stabilize line endings
5175 while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
5176 $body = substr($body, 0, strlen($body) - 2);
5177 }
5178 return $body;
5179 }
5180 /**
5181 * Create the DKIM header and body in a new message header.
5182 * @access public
5183 * @param string $headers_line Header lines
5184 * @param string $subject Subject
5185 * @param string $body Body
5186 * @return string
5187 */
5188 public function DKIM_Add($headers_line, $subject, $body)
5189 {
5190 $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
5191 $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
5192 $DKIMquery = 'dns/txt'; // Query method
5193 $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
5194 $subject_header = "Subject: $subject";
5195 $headers = explode($this->LE, $headers_line);
5196 $from_header = '';
5197 $to_header = '';
5198 $date_header = '';
5199 $current = '';
5200 foreach ($headers as $header) {
5201 if (strpos($header, 'From:') === 0) {
5202 $from_header = $header;
5203 $current = 'from_header';
5204 } elseif (strpos($header, 'To:') === 0) {
5205 $to_header = $header;
5206 $current = 'to_header';
5207 } elseif (strpos($header, 'Date:') === 0) {
5208 $date_header = $header;
5209 $current = 'date_header';
5210 } else {
5211 if (!empty($$current) && strpos($header, ' =?') === 0) {
5212 $$current .= $header;
5213 } else {
5214 $current = '';
5215 }
5216 }
5217 }
5218 $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
5219 $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
5220 $date = str_replace('|', '=7C', $this->DKIM_QP($date_header));
5221 $subject = str_replace(
5222 '|',
5223 '=7C',
5224 $this->DKIM_QP($subject_header)
5225 ); // Copied header fields (dkim-quoted-printable)
5226 $body = $this->DKIM_BodyC($body);
5227 $DKIMlen = strlen($body); // Length of body
5228 $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
5229 if ('' == $this->DKIM_identity) {
5230 $ident = '';
5231 } else {
5232 $ident = ' i=' . $this->DKIM_identity . ';';
5233 }
5234 $dkimhdrs = 'DKIM-Signature: v=1; a=' .
5235 $DKIMsignatureType . '; q=' .
5236 $DKIMquery . '; l=' .
5237 $DKIMlen . '; s=' .
5238 $this->DKIM_selector .
5239 ";\r\n" .
5240 "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
5241 "\th=From:To:Date:Subject;\r\n" .
5242 "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
5243 "\tz=$from\r\n" .
5244 "\t|$to\r\n" .
5245 "\t|$date\r\n" .
5246 "\t|$subject;\r\n" .
5247 "\tbh=" . $DKIMb64 . ";\r\n" .
5248 "\tb=";
5249 $toSign = $this->DKIM_HeaderC(
5250 $from_header . "\r\n" .
5251 $to_header . "\r\n" .
5252 $date_header . "\r\n" .
5253 $subject_header . "\r\n" .
5254 $dkimhdrs
5255 );
5256 $signed = $this->DKIM_Sign($toSign);
5257 return $dkimhdrs . $signed . "\r\n";
5258 }
5259 /**
5260 * Detect if a string contains a line longer than the maximum line length allowed.
5261 * @param string $str
5262 * @return boolean
5263 * @static
5264 */
5265 public static function hasLineLongerThanMax($str)
5266 {
5267 //+2 to include CRLF line break for a 1000 total
5268 return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str);
5269 }
5270 /**
5271 * Allows for public read access to 'to' property.
5272 * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5273 * @access public
5274 * @return array
5275 */
5276 public function getToAddresses()
5277 {
5278 return $this->to;
5279 }
5280 /**
5281 * Allows for public read access to 'cc' property.
5282 * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5283 * @access public
5284 * @return array
5285 */
5286 public function getCcAddresses()
5287 {
5288 return $this->cc;
5289 }
5290 /**
5291 * Allows for public read access to 'bcc' property.
5292 * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5293 * @access public
5294 * @return array
5295 */
5296 public function getBccAddresses()
5297 {
5298 return $this->bcc;
5299 }
5300 /**
5301 * Allows for public read access to 'ReplyTo' property.
5302 * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5303 * @access public
5304 * @return array
5305 */
5306 public function getReplyToAddresses()
5307 {
5308 return $this->ReplyTo;
5309 }
5310 /**
5311 * Allows for public read access to 'all_recipients' property.
5312 * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5313 * @access public
5314 * @return array
5315 */
5316 public function getAllRecipientAddresses()
5317 {
5318 return $this->all_recipients;
5319 }
5320 /**
5321 * Perform a callback.
5322 * @param boolean $isSent
5323 * @param array $to
5324 * @param array $cc
5325 * @param array $bcc
5326 * @param string $subject
5327 * @param string $body
5328 * @param string $from
5329 */
5330 protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
5331 {
5332 if (!empty($this->action_function) && is_callable($this->action_function)) {
5333 $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
5334 call_user_func_array($this->action_function, $params);
5335 }
5336 }
5337}
5338/**
5339 * PHPMailer exception handler
5340 * @package PHPMailer
5341 */
5342class phpmailerException extends Exception
5343{
5344 /**
5345 * Prettify error message output
5346 * @return string
5347 */
5348 public function errorMessage()
5349 {
5350 $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
5351 return $errorMsg;
5352 }
5353}
5354
5355
5356$mail = new PHPMailer();
5357
5358
5359// REMOVE ALL HTML TAG WILL BE USED IN ALTBODY
5360function strip_tags_content($text, $tags = '', $invert = FALSE) {
5361
5362 /*preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
5363 $tags = array_unique($tags[1]);
5364
5365 if(is_array($tags) AND count($tags) > 0) {
5366 if($invert == FALSE) {
5367 return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text);
5368 }
5369 else {
5370 return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text);
5371 }
5372 }
5373 elseif($invert == FALSE) {
5374 return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
5375 } */
5376 return strip_tags($text);
5377}
5378
5379// TRIM LEFT AND RIGHT
5380function lrtrim($string)
5381{
5382 return stripslashes(ltrim(rtrim($string)));
5383}
5384// REPLACE LAST OCCURENCE OF STRING
5385function str_lreplace($search, $replace, $subject)
5386{
5387 $pos = strrpos($subject, $search);
5388
5389 if($pos !== false)
5390 {
5391 $subject = substr_replace($subject, $replace, $pos, strlen($search));
5392 }
5393
5394 return $subject;
5395}
5396// RANDOM STRING FUNCTION
5397function generateRandomString($matches)
5398{
5399 $length = intval(ltrim(rtrim($matches[3])));
5400 $PATTERN = str_lreplace('-','',$matches[2]);
5401
5402 $characters = '';
5403 if(strpos($PATTERN, '09') !== false)
5404 $characters .= '0123456789';
5405 if(strpos($PATTERN, 'az') !== false)
5406 $characters .= 'abcdefghijklmnopqrstuvwxyz';
5407 if(strpos($PATTERN, 'AZ') !== false)
5408 $characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
5409 $charactersLength = strlen($characters);
5410 $randomString = '';
5411 for ($i = 0; $i < $length; $i++) {
5412 $randomString .= $characters[rand(0, $charactersLength - 1)];
5413 }
5414 return $randomString;
5415}
5416// WAITING FUNCTION
5417function pause($pause,$mail)
5418{
5419 $sec=doubleval($pause);
5420 $mail->SmtpClose();
5421 echo "\n\n<br><br>############################### WAITING $sec SEC TO CONTINUE SENDING ###############################<br><br>\n\n";
5422 flush();
5423 sleep($sec);
5424}
5425// SMTP SWITCH
5426function switch_smtp()
5427{
5428 global $allsmtps;
5429 global $curentsmtp;
5430 global $mail;
5431 global $isbcc;
5432 global $from;
5433 global $lase;
5434 global $replyto;
5435 global $reading;
5436 global $repaslog;
5437 if(count($allsmtps) > $curentsmtp)
5438 {
5439 $smtprot = explode(':',$allsmtps[$curentsmtp]);
5440 if(count($smtprot) > 0)
5441 {
5442 $mail->Host = $smtprot[0];
5443 $mail->Port = $smtprot[1];
5444 $mail->Username = $smtprot[2];
5445 $mail->Password = $smtprot[3];
5446 if($reading && $repaslog)
5447 $replyto = $smtprot[2];
5448 if($lase)
5449 {
5450 $from = $smtprot[2];
5451 $from_base = $smtprot[2];
5452 }
5453
5454 if($smtprot[4] =="SSL")
5455 $mail->SMTPSecure = "ssl"; //you can change it to ssl or tls
5456 else if($smtprot[4] =="TLS")
5457 $mail->SMTPSecure = "tls";
5458 else if($smtprot[4] =="NON")
5459 $mail->SMTPSecure = "";
5460 if($smtprot[5] =="BCC")
5461 $isbcc = true;
5462 else $isbcc = false;
5463
5464 }
5465 }
5466}
5467
5468
5469 if ($action)
5470 {
5471 if (!$from && !$subject && !$message && !$emaillist)
5472 {
5473 print "<script>alert('PLEASE FILL ALL FIELDS BEFORE SENDING YOUR MESSAGE.'); </script>";
5474 die();
5475 }
5476 else
5477 {
5478 $allemails = preg_split("/\\r\\n|\\r|\\n/", $emaillist);
5479 $numemails = count($allemails);
5480 $nq=0;
5481 $qx=0;
5482
5483 if(!empty($epriority))
5484 $mail->Priority = "$epriority";
5485 if($contenttype == "html")
5486 $mail->IsHtml(true);
5487 else
5488 $mail->IsHtml(false);
5489 if(empty($reconnect))
5490 $reconnect=0;
5491 if(!empty($replyto))
5492 $mail->AddReplyTo("$replyto");
5493 if(empty($my_smtp))
5494 {
5495 $mail->SMTPAuth = false;
5496 $mail->IsSendmail();
5497 $default_system="1";
5498 }
5499 else
5500 {
5501 $mail->IsSMTP();
5502 $mail->SMTPKeepAlive = true;
5503 $mail->SMTPAuth = true;
5504 switch_smtp();
5505 }
5506 $mail->From = $from;
5507 #$mail->addCustomHeader('List-Unsubscribe',preg_replace_callback('/(##([a-zA-Z0-9\-]+)\{([0-9]+)\}##)/', "generateRandomString", 'mailto:bounce##09-{3}##-##az-AZ-09-{15}##@'.explode('@',$from)[1].'?subject=list-unsubscribe'));
5508 // SET DEBUG LVL
5509 $mail->SMTPDebug = $debg;
5510 // SET CHARSET
5511 $mail->CharSet = "UTF-8";
5512 // READING CONFIRMATION
5513 if($reading)
5514 $mail->ConfirmReadingTo = $replyto;
5515 else $mail->ConfirmReadingTo = '';
5516 // SET ENCODING TYPE
5517 if($encodety !="no") $mail->Encoding = $encodety;
5518 // ADD ATTACH
5519 if (array_key_exists('userfile', $_FILES))
5520 {
5521 // First handle the upload
5522 // Don't trust provided filename - same goes for MIME types
5523 // See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
5524 $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));
5525 if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
5526 {
5527 $mail->addAttachment($uploadfile,$_FILES['userfile']['name']);
5528 }
5529 }
5530 for($x=1; $x<=$numemails; $x++)
5531 {
5532 // BCC EMAIL COUNT
5533 if($isbcc && $x % intval($nbcc) == 0)
5534 {
5535 $nm += 1;
5536 $nopose=false;
5537 $canrotat=true;
5538 }
5539 else
5540 {
5541 $nopose=true;
5542 $canrotat=false;
5543 }
5544 //END//
5545
5546 $send=false;
5547 $v=$x-1;
5548 $to = $allemails[$v];
5549 $to = preg_replace("/ /", "", $to);
5550
5551 // ADD ADRESSES TO QUEUE
5552 if($isbcc && !empty($nbcc) )
5553 {
5554
5555 if($x % intval($nbcc) != 0 && $x <= $numemails)
5556 {
5557 $mail->addBCC("$to");
5558 print "<span style=\"color:red;\">Line $qx </span> : Sending mail to $to<br>";
5559 flush();
5560 if($x % intval($nbcc) != 0 && $x == $numemails)
5561 $send=true;
5562 }
5563 else
5564 {
5565 $mail->addBCC("$to");
5566 print "<span style=\"color:red;\">Line $qx </span> : Sending mail to $to<br>";
5567 flush();
5568 $send = true;
5569 }
5570 $qx=$x;
5571 }
5572 else
5573 {
5574 $mail->clearAddresses();
5575 $mail->AddAddress("$to");
5576 $send=true;
5577 print "<span style=\"color:red;\">Line $qx </span> : Sending mail to $to.......";
5578 flush();
5579 $qx=$x;
5580 }
5581 //END//
5582 if($send)
5583 {
5584
5585 $realname = preg_replace_callback('/(##([a-zA-Z0-9\-]+)\{([0-9]+)\}##)/', "generateRandomString", $realname_base);
5586 $message = preg_replace_callback('/(##([a-zA-Z0-9\-]+)\{([0-9]+)\}##)/', "generateRandomString", $message_base);
5587 $subject = preg_replace_callback('/(##([a-zA-Z0-9\-]+)\{([0-9]+)\}##)/', "generateRandomString", $subject_base);
5588 $from = preg_replace_callback('/(##([a-zA-Z0-9\-]+)\{([0-9]+)\}##)/', "generateRandomString", $from_base);
5589
5590 if(!$isbcc)
5591 {
5592 $message = preg_replace("/!!EMAIL!!/", $to, $message);
5593 $subject = preg_replace("/!!EMAIL!!/", $to, $subject);
5594 }
5595 $message = preg_replace("/!!DATE!!/", date("d/m/Y"), $message);
5596 $subject = preg_replace("/!!DATE!!/", date("d/m/Y"), $subject);
5597 $message = preg_replace("/!!TIME!!/", date("H:i:s"), $message);
5598 $subject = preg_replace("/!!TIME!!/", date("H:i:s"), $subject);
5599 $message = urlencode($message);
5600 $message = preg_replace("/%5C%22/", "%22", $message);
5601 $message = urldecode($message);
5602 $message = stripslashes($message);
5603 $subject = stripslashes($subject);
5604
5605 if ($encodety != "no")
5606 {
5607 $subject = "=?UTF-8?B?".base64_encode($subject)."?=";
5608 $realname = "=?UTF-8?B?".base64_encode($realname)."?=";
5609 }
5610
5611 $mail->FromName = "$realname";
5612 $mail->Subject = "$subject";
5613 $mail->Body = "$message";
5614 $mail->AltBody = strip_tags_content($message);
5615 // SENDING AND TESTING
5616 if(!$mail->Send())
5617 {
5618 if($default_system != "1")
5619 {
5620 echo "FAILED !!<font color=\"#D4001A\"> [RECEPIENT CAN'T RECEIVE MESSAGE.]</font><br>";
5621 }
5622 if($default_system == "1")
5623 {
5624 $mail->IsMail();
5625 if(!$mail->Send())
5626 {
5627 echo "FAILED !!<font color=\"#D4001A\"> [RECEPIENT CAN'T RECEIVE MESSAGE.]</font><br>";
5628 }
5629 else
5630 {
5631 if($isbcc)
5632 echo "# BCC EMAIL NUMERO <span style=\"color:red;\">NUMERO $nm </span> SEND :<b>OK</b><br>";
5633 else echo "<b>OK</b><br>";
5634 }
5635 }
5636 }
5637 else
5638 {
5639 if($isbcc)
5640 echo "# BCC EMAIL <span style=\"color:red;\">NUMERO $nm </span> SEND :<b>OK</b><br>";
5641 else echo "<b>OK</b><br>";
5642 }
5643 if($reconnect >0 && $reconnect==$nq && !(intval($nrotat) > 0 && count($allsmtps) > 1))
5644 {
5645 $mail->SmtpClose();
5646 echo "<p><b>########################### SMTP CLOSED AND ATTEMPTS TO RECONNECT NEW CONNECTION SEASON ########################### </b></p>";
5647 $nq=0;
5648 }
5649 $nq=$nq+1;
5650 flush();
5651 if($isbcc)
5652 $mail->clearBCCs();
5653 }
5654 //END//
5655
5656 // SMTP IP ROTATION NB: 1 BCC = 1 EMAIL
5657 if(intval($nrotat) > 0 && count($allsmtps) > 1)
5658 {
5659 $curentsmtp += 1;
5660 $nq=0;
5661 $mail->SmtpClose();
5662 switch_smtp();
5663 if($isbcc)
5664 {
5665 if($nm > 0 && $nm % intval($nrotat) == 0 && $canrotat && $x < $numemails)
5666 {
5667 echo "\n<br><span style=\"color:red;\">##############</span><b> ROTATE TO SMTP ".($curentsmtp+1)." IP: ".$mail->Host."</b><span style=\"color:red;\"> ##############</span><br><br>\n";
5668
5669 }
5670 }
5671 else if ($x % intval($nrotat)==0 && $x < $numemails)
5672 {
5673 if($x >= intval($nrotat))
5674 echo "\n<br><span style=\"color:red;\">##############</span><b> ROTATE TO SMTP ".($curentsmtp+1)." IP: ".$mail->Host."</b><span style=\"color:red;\"> ##############</span><br><br>\n\n";
5675 }
5676 if($curentsmtp >= count($allsmtps))
5677 {
5678 $curentsmtp=0;
5679 }
5680
5681 }
5682 //END//
5683
5684 // WAITING PAUSE TIME
5685 if(!empty($pause) && !empty($pemails))
5686 {
5687 if(doubleval($pause) > 0)
5688 {
5689 if(!$isbcc)
5690 {
5691 if($x % intval($pemails) == 0 && $x < $numemails)
5692 {
5693 pause($pause,$mail);
5694 }
5695 }
5696 else if($nm > 0 && $nm % intval($pemails) == 0 && $x < $numemails && !$nopose)
5697 {
5698 pause($pause,$mail);
5699 }
5700 }
5701 }
5702 //END//
5703 }
5704 }
5705 }