smtp.mail.inc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. <?php
  2. /**
  3. * @file
  4. * The code processing mail in the smtp module.
  5. *
  6. */
  7. /**
  8. * Modify the drupal mail system to use smtp when sending emails.
  9. * Include the option to choose between plain text or HTML
  10. */
  11. class SmtpMailSystem implements MailSystemInterface {
  12. protected $AllowHtml;
  13. /**
  14. * Concatenate and wrap the e-mail body for either
  15. * plain-text or HTML emails.
  16. *
  17. * @param $message
  18. * A message array, as described in hook_mail_alter().
  19. *
  20. * @return
  21. * The formatted $message.
  22. */
  23. public function format(array $message) {
  24. $this->AllowHtml = variable_get('smtp_allowhtml', 0);
  25. // Join the body array into one string.
  26. $message['body'] = implode("\n\n", $message['body']);
  27. if ($this->AllowHtml == 0) {
  28. // Convert any HTML to plain-text.
  29. $message['body'] = drupal_html_to_text($message['body']);
  30. // Wrap the mail body for sending.
  31. $message['body'] = drupal_wrap_mail($message['body']);
  32. }
  33. return $message;
  34. }
  35. /**
  36. * Send the e-mail message.
  37. *
  38. * @see drupal_mail()
  39. *
  40. * @param $message
  41. * A message array, as described in hook_mail_alter().
  42. * @return
  43. * TRUE if the mail was successfully accepted, otherwise FALSE.
  44. */
  45. public function mail(array $message) {
  46. $id = $message['id'];
  47. $to = $message['to'];
  48. $from = $message['from'];
  49. $subject = $message['subject'];
  50. $body = $message['body'];
  51. $headers = $message['headers'];
  52. // Create a new PHPMailer object - autoloaded from registry.
  53. $mailer = new PHPMailer();
  54. // Turn on debugging, if requested.
  55. if (variable_get('smtp_debugging', 0) == 1) {
  56. $mailer->SMTPDebug = TRUE;
  57. }
  58. // Set the from name and e-mail address.
  59. if (variable_get('smtp_fromname', '') != '') {
  60. $from_name = variable_get('smtp_fromname', '');
  61. }
  62. else {
  63. // If value is not defined in settings, use site_name.
  64. $from_name = variable_get('site_name', '');
  65. }
  66. //Hack to fix reply-to issue.
  67. $properfrom = variable_get('site_mail', '');
  68. if (!empty($properfrom)) {
  69. $headers['From'] = $properfrom;
  70. }
  71. if (!isset($headers['Reply-To']) || empty($headers['Reply-To'])) {
  72. if (strpos($from, '<')) {
  73. $reply = preg_replace('/>.*/', '', preg_replace('/.*</', '', $from));
  74. }
  75. else {
  76. $reply = $from;
  77. }
  78. $headers['Reply-To'] = $reply;
  79. }
  80. // Blank value will let the e-mail address appear.
  81. if ($from == NULL || $from == '') {
  82. // If from e-mail address is blank, use smtp_from config option.
  83. if (($from = variable_get('smtp_from', '')) == '') {
  84. // If smtp_from config option is blank, use site_email.
  85. if (($from = variable_get('site_mail', '')) == '') {
  86. drupal_set_message(t('There is no submitted from address.'), 'error');
  87. watchdog('smtp', 'There is no submitted from address.', array(), WATCHDOG_ERROR);
  88. return FALSE;
  89. }
  90. }
  91. }
  92. if (preg_match('/^"?.*"?\s*<.*>$/', $from)) {
  93. // . == Matches any single character except line break characters \r and \n.
  94. // * == Repeats the previous item zero or more times.
  95. $from_name = preg_replace('/"?([^("\t\n)]*)"?.*$/', '$1', $from); // It gives: Name
  96. $from = preg_replace("/(.*)\<(.*)\>/i", '$2', $from); // It gives: name@domain.tld
  97. }
  98. elseif (!valid_email_address($from)) {
  99. drupal_set_message(t('The submitted from address (@from) is not valid.', array('@from' => $from)), 'error');
  100. watchdog('smtp', 'The submitted from address (@from) is not valid.', array('@from' => $from), WATCHDOG_ERROR);
  101. return FALSE;
  102. }
  103. // Defines the From value to what we expect.
  104. $mailer->From = $from;
  105. $mailer->FromName = $from_name;
  106. $mailer->Sender = $from;
  107. // Create the list of 'To:' recipients.
  108. $torecipients = explode(',', $to);
  109. foreach ($torecipients as $torecipient) {
  110. if (strpos($torecipient, '<') !== FALSE) {
  111. $toparts = explode(' <', $torecipient);
  112. $toname = $toparts[0];
  113. $toaddr = rtrim($toparts[1], '>');
  114. }
  115. else {
  116. $toname = '';
  117. $toaddr = $torecipient;
  118. }
  119. $mailer->AddAddress($toaddr, $toname);
  120. }
  121. // Parse the headers of the message and set the PHPMailer object's settings
  122. // accordingly.
  123. foreach ($headers as $key => $value) {
  124. //watchdog('error', 'Key: ' . $key . ' Value: ' . $value);
  125. switch (drupal_strtolower($key)) {
  126. case 'from':
  127. if ($from == NULL or $from == '') {
  128. // If a from value was already given, then set based on header.
  129. // Should be the most common situation since drupal_mail moves the
  130. // from to headers.
  131. $from = $value;
  132. $mailer->From = $value;
  133. // then from can be out of sync with from_name !
  134. $mailer->FromName = '';
  135. $mailer->Sender = $value;
  136. }
  137. break;
  138. case 'content-type':
  139. // Parse several values on the Content-type header, storing them in an array like
  140. // key=value -> $vars['key']='value'
  141. $vars = explode(';', $value);
  142. foreach ($vars as $i => $var) {
  143. if ($cut = strpos($var, '=')) {
  144. $new_var = trim(drupal_strtolower(drupal_substr($var, $cut + 1)));
  145. $new_key = trim(drupal_substr($var, 0, $cut));
  146. unset($vars[$i]);
  147. $vars[$new_key] = $new_var;
  148. }
  149. }
  150. // Set the charset based on the provided value, otherwise set it to UTF-8 (which is Drupals internal default).
  151. $mailer->CharSet = isset($vars['charset']) ? $vars['charset'] : 'UTF-8';
  152. switch ($vars[0]) {
  153. case 'text/plain':
  154. // The message includes only a plain text part.
  155. $mailer->IsHTML(FALSE);
  156. $content_type = 'text/plain';
  157. break;
  158. case 'text/html':
  159. // The message includes only an HTML part.
  160. $mailer->IsHTML(TRUE);
  161. $content_type = 'text/html';
  162. break;
  163. case 'multipart/related':
  164. // Get the boundary ID from the Content-Type header.
  165. $boundary = $this->_get_substring($value, 'boundary', '"', '"');
  166. // The message includes an HTML part w/inline attachments.
  167. $mailer->ContentType = $content_type = 'multipart/related; boundary="' . $boundary . '"';
  168. break;
  169. case 'multipart/alternative':
  170. // The message includes both a plain text and an HTML part.
  171. $mailer->ContentType = $content_type = 'multipart/alternative';
  172. // Get the boundary ID from the Content-Type header.
  173. $boundary = $this->_get_substring($value, 'boundary', '"', '"');
  174. break;
  175. case 'multipart/mixed':
  176. // The message includes one or more attachments.
  177. $mailer->ContentType = $content_type = 'multipart/mixed';
  178. // Get the boundary ID from the Content-Type header.
  179. $boundary = $this->_get_substring($value, 'boundary', '"', '"');
  180. break;
  181. default:
  182. // Everything else is unsuppored by PHPMailer.
  183. drupal_set_message(t('The %header of your message is not supported by PHPMailer and will be sent as text/plain instead.', array('%header' => "Content-Type: $value")), 'error');
  184. watchdog('smtp', 'The %header of your message is not supported by PHPMailer and will be sent as text/plain instead.', array('%header' => "Content-Type: $value"), WATCHDOG_ERROR);
  185. // Force the Content-Type to be text/plain.
  186. $mailer->IsHTML(FALSE);
  187. $content_type = 'text/plain';
  188. }
  189. break;
  190. case 'reply-to':
  191. // Only add a "reply-to" if it's not the same as "return-path".
  192. if ($value != $headers['Return-Path']) {
  193. if (strpos($value, '<') !== FALSE) {
  194. $replyToParts = explode('<', $value);
  195. $replyToName = trim($replyToParts[0]);
  196. $replyToName = trim($replyToName, '"');
  197. $replyToAddr = rtrim($replyToParts[1], '>');
  198. $mailer->AddReplyTo($replyToAddr, $replyToName);
  199. }
  200. else {
  201. $mailer->AddReplyTo($value);
  202. }
  203. }
  204. break;
  205. case 'content-transfer-encoding':
  206. $mailer->Encoding = $value;
  207. break;
  208. case 'return-path':
  209. case 'mime-version':
  210. case 'x-mailer':
  211. // Let PHPMailer specify these.
  212. break;
  213. case 'errors-to':
  214. $mailer->AddCustomHeader('Errors-To: ' . $value);
  215. break;
  216. case 'cc':
  217. $ccrecipients = explode(',', $value);
  218. foreach ($ccrecipients as $ccrecipient) {
  219. if (strpos($ccrecipient, '<') !== FALSE) {
  220. $ccparts = explode(' <', $ccrecipient);
  221. $ccname = $ccparts[0];
  222. $ccaddr = rtrim($ccparts[1], '>');
  223. }
  224. else {
  225. $ccname = '';
  226. $ccaddr = $ccrecipient;
  227. }
  228. $mailer->AddBCC($ccaddr, $ccname);
  229. }
  230. break;
  231. case 'bcc':
  232. $bccrecipients = explode(',', $value);
  233. foreach ($bccrecipients as $bccrecipient) {
  234. if (strpos($bccrecipient, '<') !== FALSE) {
  235. $bccparts = explode(' <', $bccrecipient);
  236. $bccname = $bccparts[0];
  237. $bccaddr = rtrim($bccparts[1], '>');
  238. }
  239. else {
  240. $bccname = '';
  241. $bccaddr = $bccrecipient;
  242. }
  243. $mailer->AddBCC($bccaddr, $bccname);
  244. }
  245. break;
  246. default:
  247. // The header key is not special - add it as is.
  248. $mailer->AddCustomHeader($key . ': ' . $value);
  249. }
  250. }
  251. /**
  252. * TODO
  253. * Need to figure out the following.
  254. // Add one last header item, but not if it has already been added.
  255. $errors_to = FALSE;
  256. foreach ($mailer->CustomHeader as $custom_header) {
  257. if ($custom_header[0] = '') {
  258. $errors_to = TRUE;
  259. }
  260. }
  261. if ($errors_to) {
  262. $mailer->AddCustomHeader('Errors-To: '. $from);
  263. }
  264. */
  265. // Add the message's subject.
  266. $mailer->Subject = $subject;
  267. // Processes the message's body.
  268. switch ($content_type) {
  269. case 'multipart/related':
  270. $mailer->Body = $body;
  271. /**
  272. * TODO
  273. * Firgure out if there is anything more to handling this type.
  274. */
  275. break;
  276. case 'multipart/alternative':
  277. // Split the body based on the boundary ID.
  278. $body_parts = $this->_boundary_split($body, $boundary);
  279. foreach ($body_parts as $body_part) {
  280. // If plain/text within the body part, add it to $mailer->AltBody.
  281. if (strpos($body_part, 'text/plain')) {
  282. // Clean up the text.
  283. $body_part = trim($this->_remove_headers(trim($body_part)));
  284. // Include it as part of the mail object.
  285. $mailer->AltBody = $body_part;
  286. }
  287. // If plain/html within the body part, add it to $mailer->Body.
  288. elseif (strpos($body_part, 'text/html')) {
  289. // Clean up the text.
  290. $body_part = trim($this->_remove_headers(trim($body_part)));
  291. // Include it as part of the mail object.
  292. $mailer->Body = $body_part;
  293. }
  294. }
  295. break;
  296. case 'multipart/mixed':
  297. // Split the body based on the boundary ID.
  298. $body_parts = $this->_boundary_split($body, $boundary);
  299. // Determine if there is an HTML part for when adding the plain text part.
  300. $text_plain = FALSE;
  301. $text_html = FALSE;
  302. foreach ($body_parts as $body_part) {
  303. if (strpos($body_part, 'text/plain')) {
  304. $text_plain = TRUE;
  305. }
  306. if (strpos($body_part, 'text/html')) {
  307. $text_html = TRUE;
  308. }
  309. }
  310. foreach ($body_parts as $body_part) {
  311. // If test/plain within the body part, add it to either
  312. // $mailer->AltBody or $mailer->Body, depending on whether there is
  313. // also a text/html part ot not.
  314. if (strpos($body_part, 'multipart/alternative')) {
  315. // Clean up the text.
  316. $body_part = trim($this->_remove_headers(trim($body_part)));
  317. // Get boundary ID from the Content-Type header.
  318. $boundary2 = $this->_get_substring($body_part, 'boundary', '"', '"');
  319. // Split the body based on the boundary ID.
  320. $body_parts2 = $this->_boundary_split($body_part, $boundary2);
  321. foreach ($body_parts2 as $body_part2) {
  322. // If plain/text within the body part, add it to $mailer->AltBody.
  323. if (strpos($body_part2, 'text/plain')) {
  324. // Clean up the text.
  325. $body_part2 = trim($this->_remove_headers(trim($body_part2)));
  326. // Include it as part of the mail object.
  327. $mailer->AltBody = $body_part2;
  328. $mailer->ContentType = 'multipart/mixed';
  329. }
  330. // If plain/html within the body part, add it to $mailer->Body.
  331. elseif (strpos($body_part2, 'text/html')) {
  332. // Clean up the text.
  333. $body_part2 = trim($this->_remove_headers(trim($body_part2)));
  334. // Include it as part of the mail object.
  335. $mailer->Body = $body_part2;
  336. $mailer->ContentType = 'multipart/mixed';
  337. }
  338. }
  339. }
  340. // If text/plain within the body part, add it to $mailer->Body.
  341. elseif (strpos($body_part, 'text/plain')) {
  342. // Clean up the text.
  343. $body_part = trim($this->_remove_headers(trim($body_part)));
  344. if ($text_html) {
  345. $mailer->AltBody = $body_part;
  346. $mailer->IsHTML(TRUE);
  347. $mailer->ContentType = 'multipart/mixed';
  348. }
  349. else {
  350. $mailer->Body = $body_part;
  351. $mailer->IsHTML(FALSE);
  352. $mailer->ContentType = 'multipart/mixed';
  353. }
  354. }
  355. // If text/html within the body part, add it to $mailer->Body.
  356. elseif (strpos($body_part, 'text/html')) {
  357. // Clean up the text.
  358. $body_part = trim($this->_remove_headers(trim($body_part)));
  359. // Include it as part of the mail object.
  360. $mailer->Body = $body_part;
  361. $mailer->IsHTML(TRUE);
  362. $mailer->ContentType = 'multipart/mixed';
  363. }
  364. // Add the attachment.
  365. elseif (strpos($body_part, 'Content-Disposition: attachment;')) {
  366. $file_path = $this->_get_substring($body_part, 'filename=', '"', '"');
  367. $file_name = $this->_get_substring($body_part, ' name=', '"', '"');
  368. $file_encoding = $this->_get_substring($body_part, 'Content-Transfer-Encoding', ' ', "\n");
  369. $file_type = $this->_get_substring($body_part, 'Content-Type', ' ', ';');
  370. if (file_exists($file_path)) {
  371. if (!$mailer->AddAttachment($file_path, $file_name, $file_encoding, $filetype)) {
  372. drupal_set_message(t('Attahment could not be found or accessed.'));
  373. }
  374. }
  375. else {
  376. // Clean up the text.
  377. $body_part = trim($this->_remove_headers(trim($body_part)));
  378. if (drupal_strtolower($file_encoding) == 'base64') {
  379. $attachment = base64_decode($body_part);
  380. }
  381. elseif (drupal_strtolower($file_encoding) == 'quoted-printable') {
  382. $attachment = quoted_printable_decode($body_part);
  383. }
  384. else {
  385. $attachment = $body_part;
  386. }
  387. $attachment_new_filename = tempnam(realpath(file_directory_temp()), 'smtp');
  388. $file_path = file_save_data($attachment, $attachment_new_filename, FILE_EXISTS_RENAME);
  389. if (!$mailer->AddAttachment($file_path, $file_name)) { // , $file_encoding, $filetype);
  390. drupal_set_message(t('Attachment could not be found or accessed.'));
  391. }
  392. }
  393. }
  394. }
  395. break;
  396. default:
  397. $mailer->Body = $body;
  398. break;
  399. }
  400. // Set the authentication settings.
  401. $username = variable_get('smtp_username', '');
  402. $password = variable_get('smtp_password', '');
  403. // If username and password are given, use SMTP authentication.
  404. if ($username != '' && $password != '') {
  405. $mailer->SMTPAuth = TRUE;
  406. $mailer->Username = $username;
  407. $mailer->Password = $password;
  408. }
  409. // Set the protocol prefix for the smtp host.
  410. switch (variable_get('smtp_protocol', 'standard')) {
  411. case 'ssl':
  412. $mailer->SMTPSecure = 'ssl';
  413. break;
  414. case 'tls':
  415. $mailer->SMTPSecure = 'tls';
  416. break;
  417. default:
  418. $mailer->SMTPSecure = '';
  419. }
  420. // Set other connection settings.
  421. $mailer->Host = variable_get('smtp_host', '') . ';' . variable_get('smtp_hostbackup', '');
  422. $mailer->Port = variable_get('smtp_port', '25');
  423. $mailer->Mailer = 'smtp';
  424. // Let the people know what is going on.
  425. watchdog('smtp', 'Sending mail to: @to', array('@to' => $to));
  426. // Try to send e-mail. If it fails, set watchdog entry.
  427. if (!$mailer->Send()) {
  428. watchdog('smtp', 'Error sending e-mail from @from to @to : !error_message', array('@from' => $from, '@to' => $to, '!error_message' => $mailer->ErrorInfo), WATCHDOG_ERROR);
  429. return FALSE;
  430. }
  431. $mailer->SmtpClose();
  432. return TRUE;
  433. }
  434. /**
  435. * Splits the input into parts based on the given boundary.
  436. *
  437. * Swiped from Mail::MimeDecode, with modifications based on Drupal's coding
  438. * standards and this bug report: http://pear.php.net/bugs/bug.php?id=6495
  439. *
  440. * @param input
  441. * A string containing the body text to parse.
  442. * @param boundary
  443. * A string with the boundary string to parse on.
  444. * @return
  445. * An array containing the resulting mime parts
  446. */
  447. protected function _boundary_split($input, $boundary) {
  448. $parts = array();
  449. $bs_possible = drupal_substr($boundary, 2, -2);
  450. $bs_check = '\"' . $bs_possible . '\"';
  451. if ($boundary == $bs_check) {
  452. $boundary = $bs_possible;
  453. }
  454. $tmp = explode('--' . $boundary, $input);
  455. for ($i = 1; $i < count($tmp); $i++) {
  456. if (trim($tmp[$i])) {
  457. $parts[] = $tmp[$i];
  458. }
  459. }
  460. return $parts;
  461. } // End of _smtp_boundary_split().
  462. /**
  463. * Strips the headers from the body part.
  464. *
  465. * @param input
  466. * A string containing the body part to strip.
  467. * @return
  468. * A string with the stripped body part.
  469. */
  470. protected function _remove_headers($input) {
  471. $part_array = explode("\n", $input);
  472. if (strpos($part_array[0], 'Content') !== FALSE) {
  473. if (strpos($part_array[1], 'Content') !== FALSE) {
  474. if (strpos($part_array[2], 'Content') !== FALSE) {
  475. array_shift($part_array);
  476. array_shift($part_array);
  477. array_shift($part_array);
  478. }
  479. else {
  480. array_shift($part_array);
  481. array_shift($part_array);
  482. }
  483. }
  484. else {
  485. array_shift($part_array);
  486. }
  487. }
  488. $output = implode("\n", $part_array);
  489. return $output;
  490. } // End of _smtp_remove_headers().
  491. /**
  492. * Returns a string that is contained within another string.
  493. *
  494. * Returns the string from within $source that is some where after $target
  495. * and is between $beginning_character and $ending_character.
  496. *
  497. * @param $source
  498. * A string containing the text to look through.
  499. * @param $target
  500. * A string containing the text in $source to start looking from.
  501. * @param $beginning_character
  502. * A string containing the character just before the sought after text.
  503. * @param $ending_character
  504. * A string containing the character just after the sought after text.
  505. * @return
  506. * A string with the text found between the $beginning_character and the
  507. * $ending_character.
  508. */
  509. protected function _get_substring($source, $target, $beginning_character, $ending_character) {
  510. $search_start = strpos($source, $target) + 1;
  511. $first_character = strpos($source, $beginning_character, $search_start) + 1;
  512. $second_character = strpos($source, $ending_character, $first_character) + 1;
  513. $substring = drupal_substr($source, $first_character, $second_character - $first_character);
  514. $string_length = drupal_strlen($substring) - 1;
  515. if ($substring[$string_length] == $ending_character) {
  516. $substring = drupal_substr($substring, 0, $string_length);
  517. }
  518. return $substring;
  519. } // End of _smtp_get_substring().
  520. }