3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
33 class CRM_Utils_Mail
{
36 * Create a new mailer to send any mail from the application.
38 * Note: The mailer is opened in persistent mode.
40 * Note: You probably don't want to call this directly. Get a reference
41 * to the mailer through the container.
45 public static function createMailer() {
46 $mailingInfo = Civi
::settings()->get('mailing_backend');
48 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_REDIRECT_TO_DB ||
49 (defined('CIVICRM_MAILER_SPOOL') && CIVICRM_MAILER_SPOOL
)
51 $mailer = self
::_createMailer('CRM_Mailing_BAO_Spool', array());
53 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SMTP
) {
54 if ($mailingInfo['smtpServer'] == '' ||
!$mailingInfo['smtpServer']) {
55 CRM_Core_Error
::debug_log_message(ts('There is no valid smtp server setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the SMTP Server.', array(1 => CRM_Utils_System
::url('civicrm/admin/setting/smtp', 'reset=1'))));
56 CRM_Core_Error
::fatal(ts('There is no valid smtp server setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the SMTP Server.', array(1 => CRM_Utils_System
::url('civicrm/admin/setting/smtp', 'reset=1'))));
59 $params['host'] = $mailingInfo['smtpServer'] ?
$mailingInfo['smtpServer'] : 'localhost';
60 $params['port'] = $mailingInfo['smtpPort'] ?
$mailingInfo['smtpPort'] : 25;
62 if ($mailingInfo['smtpAuth']) {
63 $params['username'] = $mailingInfo['smtpUsername'];
64 $params['password'] = CRM_Utils_Crypt
::decrypt($mailingInfo['smtpPassword']);
65 $params['auth'] = TRUE;
68 $params['auth'] = FALSE;
72 * Set the localhost value, CRM-3153
73 * Use the host name of the web server, falling back to the base URL
74 * (eg when using the PHP CLI), and then falling back to localhost.
76 $params['localhost'] = CRM_Utils_Array
::value(
79 CRM_Utils_Array
::value(
81 parse_url(CIVICRM_UF_BASEURL
),
86 // also set the timeout value, lets set it to 30 seconds
88 $params['timeout'] = 30;
91 $params['persist'] = TRUE;
93 $mailer = self
::_createMailer('smtp', $params);
95 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SENDMAIL
) {
96 if ($mailingInfo['sendmail_path'] == '' ||
97 !$mailingInfo['sendmail_path']
99 CRM_Core_Error
::debug_log_message(ts('There is no valid sendmail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the sendmail server.', array(1 => CRM_Utils_System
::url('civicrm/admin/setting/smtp', 'reset=1'))));
100 CRM_Core_Error
::fatal(ts('There is no valid sendmail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the sendmail server.', array(1 => CRM_Utils_System
::url('civicrm/admin/setting/smtp', 'reset=1'))));
102 $params['sendmail_path'] = $mailingInfo['sendmail_path'];
103 $params['sendmail_args'] = $mailingInfo['sendmail_args'];
105 $mailer = self
::_createMailer('sendmail', $params);
107 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MAIL
) {
108 $mailer = self
::_createMailer('mail', array());
110 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MOCK
) {
111 $mailer = self
::_createMailer('mock', array());
113 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
) {
114 CRM_Core_Error
::debug_log_message(ts('Outbound mail has been disabled. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System
::url('civicrm/admin/setting/smtp', 'reset=1'))));
115 CRM_Core_Error
::statusBounce(ts('Outbound mail has been disabled. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System
::url('civicrm/admin/setting/smtp', 'reset=1'))));
118 CRM_Core_Error
::debug_log_message(ts('There is no valid SMTP server Setting Or SendMail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System
::url('civicrm/admin/setting/smtp', 'reset=1'))));
119 CRM_Core_Error
::debug_var('mailing_info', $mailingInfo);
120 CRM_Core_Error
::statusBounce(ts('There is no valid SMTP server Setting Or sendMail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System
::url('civicrm/admin/setting/smtp', 'reset=1'))));
126 * Create a new instance of a PEAR Mail driver.
128 * @param string $driver
129 * 'CRM_Mailing_BAO_Spool' or a name suitable for Mail::factory().
130 * @param array $params
132 * More specifically, a class which implements the "send()" function
134 public static function _createMailer($driver, $params) {
135 if ($driver == 'CRM_Mailing_BAO_Spool') {
136 $mailer = new CRM_Mailing_BAO_Spool($params);
139 $mailer = Mail
::factory($driver, $params);
141 CRM_Utils_Hook
::alterMailer($mailer, $driver, $params);
146 * Wrapper function to send mail in CiviCRM. Hooks are called from this function. The input parameter
147 * is an associateive array which holds the values of field needed to send an email. These are:
149 * from : complete from envelope
150 * toName : name of person to send email
151 * toEmail : email address to send to
152 * cc : email addresses to cc
153 * bcc : email addresses to bcc
154 * subject : subject of the email
155 * text : text of the message
156 * html : html version of the message
157 * replyTo : reply-to header in the email
158 * attachments: an associative array of
159 * fullPath : complete pathname to the file
160 * mime_type: mime type of the attachment
161 * cleanName: the user friendly name of the attachmment
163 * @param array $params
167 * TRUE if a mail was sent, else FALSE.
169 public static function send(&$params) {
170 $defaultReturnPath = CRM_Core_BAO_MailSettings
::defaultReturnPath();
171 $includeMessageId = CRM_Core_BAO_MailSettings
::includeMessageId();
172 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
173 $from = CRM_Utils_Array
::value('from', $params);
174 if (!$defaultReturnPath) {
175 $defaultReturnPath = self
::pluckEmailFromHeader($from);
178 // first call the mail alter hook
179 CRM_Utils_Hook
::alterMailParams($params, 'singleEmail');
181 // check if any module has aborted mail sending
182 if (!empty($params['abortMailSend']) ||
empty($params['toEmail'])) {
186 $textMessage = CRM_Utils_Array
::value('text', $params);
187 $htmlMessage = CRM_Utils_Array
::value('html', $params);
188 $attachments = CRM_Utils_Array
::value('attachments', $params);
191 if (trim(CRM_Utils_String
::htmlToText($htmlMessage)) == '') {
192 $htmlMessage = FALSE;
196 // CRM-10699 support custom email headers
197 if (!empty($params['headers'])) {
198 $headers = array_merge($headers, $params['headers']);
200 $headers['From'] = $params['from'];
201 $headers['To'] = self
::formatRFC822Email(
202 CRM_Utils_Array
::value('toName', $params),
203 CRM_Utils_Array
::value('toEmail', $params),
206 $headers['Cc'] = CRM_Utils_Array
::value('cc', $params);
207 $headers['Bcc'] = CRM_Utils_Array
::value('bcc', $params);
208 $headers['Subject'] = CRM_Utils_Array
::value('subject', $params);
209 $headers['Content-Type'] = $htmlMessage ?
'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
210 $headers['Content-Disposition'] = 'inline';
211 $headers['Content-Transfer-Encoding'] = '8bit';
212 $headers['Return-Path'] = CRM_Utils_Array
::value('returnPath', $params, $defaultReturnPath);
214 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
215 $replyTo = CRM_Utils_Array
::value('replyTo', $params, CRM_Utils_Array
::value('from', $params));
217 if (!empty($replyTo)) {
218 $headers['Reply-To'] = $replyTo;
220 $headers['Date'] = date('r');
221 if ($includeMessageId) {
222 $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@$emailDomain>";
224 if (!empty($params['autoSubmitted'])) {
225 $headers['Auto-Submitted'] = "Auto-Generated";
228 // make sure we has to have space, CRM-6977
229 foreach (array('From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path') as $fld) {
230 if (isset($headers[$fld])) {
231 $headers[$fld] = str_replace('"<', '" <', $headers[$fld]);
235 // quote FROM, if comma is detected AND is not already quoted. CRM-7053
236 if (strpos($headers['From'], ',') !== FALSE) {
237 $from = explode(' <', $headers['From']);
238 $headers['From'] = self
::formatRFC822Email(
240 substr(trim($from[1]), 0, -1),
245 require_once 'Mail/mime.php';
246 $msg = new Mail_mime("\n");
248 $msg->setTxtBody($textMessage);
252 $msg->setHTMLBody($htmlMessage);
255 if (!empty($attachments)) {
256 foreach ($attachments as $fileID => $attach) {
259 $attach['mime_type'],
265 $message = self
::setMimeParams($msg);
266 $headers = &$msg->headers($headers);
268 $to = array($params['toEmail']);
270 $mailer = \Civi
::service('pear_mail');
272 // CRM-3795, CRM-7355, CRM-7557, CRM-9058, CRM-9887, CRM-12883, CRM-19173 and others ...
273 // The PEAR library requires different parameters based on the mailer used:
274 // * Mail_mail requires the Cc/Bcc recipients listed ONLY in the $headers variable
275 // * All other mailers require that all be recipients be listed in the $to array AND that
276 // the Bcc must not be present in $header as otherwise it will be shown to all recipients
277 // ref: https://pear.php.net/bugs/bug.php?id=8047, full thread and answer [2011-04-19 20:48 UTC]
278 if (get_class($mailer) != "Mail_mail") {
279 // get emails from headers, since these are
280 // combination of name and email addresses.
281 if (!empty($headers['Cc'])) {
282 $to[] = CRM_Utils_Array
::value('Cc', $headers);
284 if (!empty($headers['Bcc'])) {
285 $to[] = CRM_Utils_Array
::value('Bcc', $headers);
286 unset($headers['Bcc']);
290 if (is_object($mailer)) {
291 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
292 $result = $mailer->send($to, $headers, $message);
293 if (is_a($result, 'PEAR_Error')) {
294 $message = self
::errorMessage($mailer, $result);
295 // append error message in case multiple calls are being made to
296 // this method in the course of sending a batch of messages.
297 CRM_Core_Session
::setStatus($message, ts('Mailing Error'), 'error');
301 CRM_Utils_Hook
::postEmailSend($params);
313 public static function errorMessage($mailer, $result) {
314 $message = '<p>' . ts('An error occurred when CiviCRM attempted to send an email (via %1). If you received this error after submitting on online contribution or event registration - the transaction was completed, but we were unable to send the email receipt.', array(
316 )) . '</p>' . '<p>' . ts('The mail library returned the following error message:') . '<br /><span class="font-red"><strong>' . $result->getMessage() . '</strong></span></p>' . '<p>' . ts('This is probably related to a problem in your Outbound Email Settings (Administer CiviCRM » System Settings » Outbound Email), OR the FROM email address specifically configured for your contribution page or event. Possible causes are:') . '</p>';
318 if (is_a($mailer, 'Mail_smtp')) {
319 $message .= '<ul>' . '<li>' . ts('Your SMTP Username or Password are incorrect.') . '</li>' . '<li>' . ts('Your SMTP Server (machine) name is incorrect.') . '</li>' . '<li>' . ts('You need to use a Port other than the default port 25 in your environment.') . '</li>' . '<li>' . ts('Your SMTP server is just not responding right now (it is down for some reason).') . '</li>';
322 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
325 $message .= '<li>' . ts('The FROM Email Address configured for this feature may not be a valid sender based on your email service provider rules.') . '</li>' . '</ul>' . '<p>' . ts('Check <a href="%1">this page</a> for more information.', array(
326 1 => CRM_Utils_System
::docURL2('user/advanced-configuration/email-system-configuration', TRUE),
337 public static function logger(&$to, &$headers, &$message) {
339 $toString = implode(', ', $to);
343 $toString = $fileName = $to;
345 $content = "To: " . $toString . "\n";
346 foreach ($headers as $key => $val) {
347 $content .= "$key: $val\n";
349 $content .= "\n" . $message . "\n";
351 if (is_numeric(CIVICRM_MAIL_LOG
)) {
352 $config = CRM_Core_Config
::singleton();
353 // create the directory if not there
354 $dirName = $config->configAndLogDir
. 'mail' . DIRECTORY_SEPARATOR
;
355 CRM_Utils_File
::createDir($dirName);
356 $fileName = md5(uniqid(CRM_Utils_String
::munge($fileName))) . '.txt';
357 file_put_contents($dirName . $fileName,
362 file_put_contents(CIVICRM_MAIL_LOG
, $content, FILE_APPEND
);
367 * Get the email address itself from a formatted full name + address string
371 * @param string $header
372 * The full name + email address string.
375 * the plucked email address
377 public static function pluckEmailFromHeader($header) {
378 preg_match('/<([^<]*)>$/', $header, $matches);
380 if (isset($matches[1])) {
387 * Get the Active outBound email.
390 * TRUE if valid outBound email configuration found, false otherwise.
392 public static function validOutBoundMail() {
393 $mailingInfo = Civi
::settings()->get('mailing_backend');
394 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MAIL
) {
397 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SMTP
) {
398 if (!isset($mailingInfo['smtpServer']) ||
$mailingInfo['smtpServer'] == '' ||
399 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
400 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' ||
$mailingInfo['smtpPassword'] == ''))
406 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SENDMAIL
) {
407 if (!$mailingInfo['sendmail_path'] ||
!$mailingInfo['sendmail_args']) {
412 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_REDIRECT_TO_DB
) {
420 * @param array $params
424 public static function &setMimeParams(&$message, $params = NULL) {
425 static $mimeParams = NULL;
429 'text_encoding' => '8bit',
430 'html_encoding' => '8bit',
431 'head_charset' => 'utf-8',
432 'text_charset' => 'utf-8',
433 'html_charset' => 'utf-8',
436 $params = $mimeParams;
438 return $message->get($params);
442 * @param string $name
444 * @param bool $useQuote
446 * @return null|string
448 public static function formatRFC822Email($name, $email, $useQuote = FALSE) {
453 // strip out double quotes if present at the beginning AND end
454 if (substr($name, 0, 1) == '"' &&
455 substr($name, -1, 1) == '"'
457 $name = substr($name, 1, -1);
461 // escape the special characters
462 $name = str_replace(array('<', '"', '>'),
463 array('\<', '\"', '\>'),
466 if (strpos($name, ',') !== FALSE ||
469 // quote the string if it has a comma
470 $name = '"' . $name . '"';
476 $result .= "<{$email}>";
481 * Takes a string and checks to see if it needs to be escaped / double quoted
482 * and if so does the needful and return the formatted name
484 * This code has been copied and adapted from ezc/Mail/src/tools.php
486 * @param string $name
490 public static function formatRFC2822Name($name) {
493 // remove the quotes around the name part if they are already there
494 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
495 $name = substr($name, 1, -1);
498 // add slashes to " and \ and surround the name part with quotes
499 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
500 $name = '"' . addcslashes($name, '\\"') . '"';
508 * @param string $fileName
509 * @param string $html
510 * @param string $format
514 public static function appendPDF($fileName, $html, $format = NULL) {
515 $pdf_filename = CRM_Core_Config
::singleton()->templateCompileDir
. CRM_Utils_File
::makeFileName($fileName);
518 // xmlns attribute is required in XHTML but it is invalid in HTML,
519 // Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
520 // and will be added to the <html> tag even if you do not include it.
521 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
523 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils
::html2pdf($html,
529 'fullPath' => $pdf_filename,
530 'mime_type' => 'application/pdf',
531 'cleanName' => $fileName,