3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
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', []);
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.', [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.', [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.', [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.', [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', []);
110 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MOCK
) {
111 $mailer = self
::_createMailer('mock', []);
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.', [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.', [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.', [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.', [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),
207 // On some servers mail() fails when 'Cc' or 'Bcc' headers are defined but empty.
208 foreach (['Cc', 'Bcc'] as $optionalHeader) {
209 $headers[$optionalHeader] = CRM_Utils_Array
::value(strtolower($optionalHeader), $params);
210 if (empty($headers[$optionalHeader])) {
211 unset($headers[$optionalHeader]);
215 $headers['Subject'] = CRM_Utils_Array
::value('subject', $params);
216 $headers['Content-Type'] = $htmlMessage ?
'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
217 $headers['Content-Disposition'] = 'inline';
218 $headers['Content-Transfer-Encoding'] = '8bit';
219 $headers['Return-Path'] = CRM_Utils_Array
::value('returnPath', $params, $defaultReturnPath);
221 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
222 $replyTo = CRM_Utils_Array
::value('replyTo', $params, CRM_Utils_Array
::value('from', $params));
224 if (!empty($replyTo)) {
225 $headers['Reply-To'] = $replyTo;
227 $headers['Date'] = date('r');
228 if ($includeMessageId) {
229 $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@$emailDomain>";
231 if (!empty($params['autoSubmitted'])) {
232 $headers['Auto-Submitted'] = "Auto-Generated";
235 // make sure we has to have space, CRM-6977
236 foreach (['From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path'] as $fld) {
237 if (isset($headers[$fld])) {
238 $headers[$fld] = str_replace('"<', '" <', $headers[$fld]);
242 // quote FROM, if comma is detected AND is not already quoted. CRM-7053
243 if (strpos($headers['From'], ',') !== FALSE) {
244 $from = explode(' <', $headers['From']);
245 $headers['From'] = self
::formatRFC822Email(
247 substr(trim($from[1]), 0, -1),
252 require_once 'Mail/mime.php';
253 $msg = new Mail_mime("\n");
255 $msg->setTxtBody($textMessage);
259 $msg->setHTMLBody($htmlMessage);
262 if (!empty($attachments)) {
263 foreach ($attachments as $fileID => $attach) {
266 $attach['mime_type'],
272 $message = self
::setMimeParams($msg);
273 $headers = $msg->headers($headers);
275 $to = [$params['toEmail']];
277 $mailer = \Civi
::service('pear_mail');
279 // CRM-3795, CRM-7355, CRM-7557, CRM-9058, CRM-9887, CRM-12883, CRM-19173 and others ...
280 // The PEAR library requires different parameters based on the mailer used:
281 // * Mail_mail requires the Cc/Bcc recipients listed ONLY in the $headers variable
282 // * All other mailers require that all be recipients be listed in the $to array AND that
283 // the Bcc must not be present in $header as otherwise it will be shown to all recipients
284 // ref: https://pear.php.net/bugs/bug.php?id=8047, full thread and answer [2011-04-19 20:48 UTC]
285 if (get_class($mailer) != "Mail_mail") {
286 // get emails from headers, since these are
287 // combination of name and email addresses.
288 if (!empty($headers['Cc'])) {
289 $to[] = CRM_Utils_Array
::value('Cc', $headers);
291 if (!empty($headers['Bcc'])) {
292 $to[] = CRM_Utils_Array
::value('Bcc', $headers);
293 unset($headers['Bcc']);
297 if (is_object($mailer)) {
298 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
299 $result = $mailer->send($to, $headers, $message);
300 if (is_a($result, 'PEAR_Error')) {
301 $message = self
::errorMessage($mailer, $result);
302 // append error message in case multiple calls are being made to
303 // this method in the course of sending a batch of messages.
304 CRM_Core_Session
::setStatus($message, ts('Mailing Error'), 'error');
308 CRM_Utils_Hook
::postEmailSend($params);
320 public static function errorMessage($mailer, $result) {
321 $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.', [
323 ]) . '</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>';
325 if (is_a($mailer, 'Mail_smtp')) {
326 $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>';
329 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
332 $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.', [
333 1 => CRM_Utils_System
::docURL2('user/advanced-configuration/email-system-configuration', TRUE),
344 public static function logger(&$to, &$headers, &$message) {
346 $toString = implode(', ', $to);
350 $toString = $fileName = $to;
352 $content = "To: " . $toString . "\n";
353 foreach ($headers as $key => $val) {
354 $content .= "$key: $val\n";
356 $content .= "\n" . $message . "\n";
358 if (is_numeric(CIVICRM_MAIL_LOG
)) {
359 $config = CRM_Core_Config
::singleton();
360 // create the directory if not there
361 $dirName = $config->configAndLogDir
. 'mail' . DIRECTORY_SEPARATOR
;
362 CRM_Utils_File
::createDir($dirName);
363 $fileName = md5(uniqid(CRM_Utils_String
::munge($fileName))) . '.txt';
364 file_put_contents($dirName . $fileName,
369 file_put_contents(CIVICRM_MAIL_LOG
, $content, FILE_APPEND
);
374 * Get the email address itself from a formatted full name + address string
378 * @param string $header
379 * The full name + email address string.
382 * the plucked email address
384 public static function pluckEmailFromHeader($header) {
385 preg_match('/<([^<]*)>$/', $header, $matches);
387 if (isset($matches[1])) {
394 * Get the Active outBound email.
397 * TRUE if valid outBound email configuration found, false otherwise.
399 public static function validOutBoundMail() {
400 $mailingInfo = Civi
::settings()->get('mailing_backend');
401 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MAIL
) {
404 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SMTP
) {
405 if (!isset($mailingInfo['smtpServer']) ||
$mailingInfo['smtpServer'] == '' ||
406 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
407 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' ||
$mailingInfo['smtpPassword'] == ''))
413 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SENDMAIL
) {
414 if (!$mailingInfo['sendmail_path'] ||
!$mailingInfo['sendmail_args']) {
419 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_REDIRECT_TO_DB
) {
427 * @param array $params
431 public static function setMimeParams($message, $params = NULL) {
432 static $mimeParams = NULL;
436 'text_encoding' => '8bit',
437 'html_encoding' => '8bit',
438 'head_charset' => 'utf-8',
439 'text_charset' => 'utf-8',
440 'html_charset' => 'utf-8',
443 $params = $mimeParams;
445 return $message->get($params);
449 * @param string $name
451 * @param bool $useQuote
453 * @return null|string
455 public static function formatRFC822Email($name, $email, $useQuote = FALSE) {
460 // strip out double quotes if present at the beginning AND end
461 if (substr($name, 0, 1) == '"' &&
462 substr($name, -1, 1) == '"'
464 $name = substr($name, 1, -1);
468 // escape the special characters
469 $name = str_replace(['<', '"', '>'],
473 if (strpos($name, ',') !== FALSE ||
476 // quote the string if it has a comma
477 $name = '"' . $name . '"';
483 $result .= "<{$email}>";
488 * Takes a string and checks to see if it needs to be escaped / double quoted
489 * and if so does the needful and return the formatted name
491 * This code has been copied and adapted from ezc/Mail/src/tools.php
493 * @param string $name
497 public static function formatRFC2822Name($name) {
500 // remove the quotes around the name part if they are already there
501 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
502 $name = substr($name, 1, -1);
505 // add slashes to " and \ and surround the name part with quotes
506 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
507 $name = '"' . addcslashes($name, '\\"') . '"';
515 * @param string $fileName
516 * @param string $html
517 * @param string $format
521 public static function appendPDF($fileName, $html, $format = NULL) {
522 $pdf_filename = CRM_Core_Config
::singleton()->templateCompileDir
. CRM_Utils_File
::makeFileName($fileName);
525 // xmlns attribute is required in XHTML but it is invalid in HTML,
526 // Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
527 // and will be added to the <html> tag even if you do not include it.
528 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
530 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils
::html2pdf($html,
536 'fullPath' => $pdf_filename,
537 'mime_type' => 'application/pdf',
538 'cleanName' => $fileName,
543 * Format an email string from email fields.
545 * @param array $fields
548 * The formatted email string.
550 public static function format($fields) {
551 $formattedEmail = '';
552 if (!empty($fields['email'])) {
553 $formattedEmail = $fields['email'];
556 $formattedSuffix = [];
557 if (!empty($fields['is_bulkmail'])) {
558 $formattedSuffix[] = '(' . ts('Bulk') . ')';
560 if (!empty($fields['on_hold'])) {
561 if ($fields['on_hold'] == 2) {
562 $formattedSuffix[] = '(' . ts('On Hold - Opt Out') . ')';
565 $formattedSuffix[] = '(' . ts('On Hold') . ')';
568 if (!empty($fields['signature_html']) ||
!empty($fields['signature_text'])) {
569 $formattedSuffix[] = '(' . ts('Signature') . ')';
572 // Add suffixes on a new line, if there is any.
573 if (!empty($formattedSuffix)) {
574 $formattedEmail .= "\n" . implode(' ', $formattedSuffix);
577 return $formattedEmail;
581 * When passed a value, returns the value if it's non-numeric.
582 * If it's numeric, look up the display name and email of the corresponding
583 * contact ID in RFC822 format.
585 * @param string $from
586 * contact ID or formatted "From address", eg. 12 or "Fred Bloggs" <fred@example.org>
588 * The RFC822-formatted email header (display name + address)
590 public static function formatFromAddress($from) {
591 if (is_numeric($from)) {
592 $result = civicrm_api3('Email', 'get', [
594 'return' => ['contact_id.display_name', 'email'],
597 $from = '"' . $result['contact_id.display_name'] . '" <' . $result['email'] . '>';