3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
50 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_REDIRECT_TO_DB ||
51 (defined('CIVICRM_MAILER_SPOOL') && CIVICRM_MAILER_SPOOL
)
53 $mailer = self
::_createMailer('CRM_Mailing_BAO_Spool', array());
55 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SMTP
) {
56 if ($mailingInfo['smtpServer'] == '' ||
!$mailingInfo['smtpServer']) {
57 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'))));
58 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'))));
61 $params['host'] = $mailingInfo['smtpServer'] ?
$mailingInfo['smtpServer'] : 'localhost';
62 $params['port'] = $mailingInfo['smtpPort'] ?
$mailingInfo['smtpPort'] : 25;
64 if ($mailingInfo['smtpAuth']) {
65 $params['username'] = $mailingInfo['smtpUsername'];
66 $params['password'] = CRM_Utils_Crypt
::decrypt($mailingInfo['smtpPassword']);
67 $params['auth'] = TRUE;
70 $params['auth'] = FALSE;
73 // set the localhost value, CRM-3153
74 $params['localhost'] = CRM_Utils_Array
::value('SERVER_NAME', $_SERVER, 'localhost');
76 // also set the timeout value, lets set it to 30 seconds
78 $params['timeout'] = 30;
81 $params['persist'] = TRUE;
83 $mailer = self
::_createMailer('smtp', $params);
85 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SENDMAIL
) {
86 if ($mailingInfo['sendmail_path'] == '' ||
87 !$mailingInfo['sendmail_path']
89 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'))));
90 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'))));
92 $params['sendmail_path'] = $mailingInfo['sendmail_path'];
93 $params['sendmail_args'] = $mailingInfo['sendmail_args'];
95 $mailer = self
::_createMailer('sendmail', $params);
97 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MAIL
) {
98 $mailer = self
::_createMailer('mail', array());
100 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MOCK
) {
101 $mailer = self
::_createMailer('mock', array());
103 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
) {
104 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'))));
105 CRM_Core_Session
::setStatus(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'))));
108 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'))));
109 CRM_Core_Session
::setStatus(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'))));
110 CRM_Core_Error
::debug_var('mailing_info', $mailingInfo);
116 * Create a new instance of a PEAR Mail driver.
118 * @param string $driver
119 * 'CRM_Mailing_BAO_Spool' or a name suitable for Mail::factory().
120 * @param array $params
122 * More specifically, a class which implements the "send()" function
124 public static function _createMailer($driver, $params) {
125 if ($driver == 'CRM_Mailing_BAO_Spool') {
126 $mailer = new CRM_Mailing_BAO_Spool($params);
129 $mailer = Mail
::factory($driver, $params);
131 CRM_Utils_Hook
::alterMail($mailer, $driver, $params);
136 * Wrapper function to send mail in CiviCRM. Hooks are called from this function. The input parameter
137 * is an associateive array which holds the values of field needed to send an email. These are:
139 * from : complete from envelope
140 * toName : name of person to send email
141 * toEmail : email address to send to
142 * cc : email addresses to cc
143 * bcc : email addresses to bcc
144 * subject : subject of the email
145 * text : text of the message
146 * html : html version of the message
147 * replyTo : reply-to header in the email
148 * attachments: an associative array of
149 * fullPath : complete pathname to the file
150 * mime_type: mime type of the attachment
151 * cleanName: the user friendly name of the attachmment
153 * @param array $params
157 * TRUE if a mail was sent, else FALSE.
159 public static function send(&$params) {
160 $returnPath = CRM_Core_BAO_MailSettings
::defaultReturnPath();
161 $includeMessageId = CRM_Core_BAO_MailSettings
::includeMessageId();
162 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
163 $from = CRM_Utils_Array
::value('from', $params);
165 $returnPath = self
::pluckEmailFromHeader($from);
167 $params['returnPath'] = $returnPath;
169 // first call the mail alter hook
170 CRM_Utils_Hook
::alterMailParams($params);
172 // check if any module has aborted mail sending
173 if (!empty($params['abortMailSend']) ||
empty($params['toEmail'])) {
177 $textMessage = CRM_Utils_Array
::value('text', $params);
178 $htmlMessage = CRM_Utils_Array
::value('html', $params);
179 $attachments = CRM_Utils_Array
::value('attachments', $params);
182 if (trim(CRM_Utils_String
::htmlToText($htmlMessage)) == '') {
183 $htmlMessage = FALSE;
187 // CRM-10699 support custom email headers
188 if (!empty($params['headers'])) {
189 $headers = array_merge($headers, $params['headers']);
191 $headers['From'] = $params['from'];
192 $headers['To'] = self
::formatRFC822Email(
193 CRM_Utils_Array
::value('toName', $params),
194 CRM_Utils_Array
::value('toEmail', $params),
197 $headers['Cc'] = CRM_Utils_Array
::value('cc', $params);
198 $headers['Bcc'] = CRM_Utils_Array
::value('bcc', $params);
199 $headers['Subject'] = CRM_Utils_Array
::value('subject', $params);
200 $headers['Content-Type'] = $htmlMessage ?
'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
201 $headers['Content-Disposition'] = 'inline';
202 $headers['Content-Transfer-Encoding'] = '8bit';
203 $headers['Return-Path'] = CRM_Utils_Array
::value('returnPath', $params);
205 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
206 $replyTo = CRM_Utils_Array
::value('replyTo', $params, CRM_Utils_Array
::value('from', $params));
208 if (!empty($replyTo)) {
209 $headers['Reply-To'] = $replyTo;
211 $headers['Date'] = date('r');
212 if ($includeMessageId) {
213 $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@$emailDomain>";
215 if (!empty($params['autoSubmitted'])) {
216 $headers['Auto-Submitted'] = "Auto-Generated";
219 // make sure we has to have space, CRM-6977
220 foreach (array('From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path') as $fld) {
221 if (isset($headers[$fld])) {
222 $headers[$fld] = str_replace('"<', '" <', $headers[$fld]);
226 // quote FROM, if comma is detected AND is not already quoted. CRM-7053
227 if (strpos($headers['From'], ',') !== FALSE) {
228 $from = explode(' <', $headers['From']);
229 $headers['From'] = self
::formatRFC822Email(
231 substr(trim($from[1]), 0, -1),
236 require_once 'Mail/mime.php';
237 $msg = new Mail_mime("\n");
239 $msg->setTxtBody($textMessage);
243 $msg->setHTMLBody($htmlMessage);
246 if (!empty($attachments)) {
247 foreach ($attachments as $fileID => $attach) {
250 $attach['mime_type'],
256 $message = self
::setMimeParams($msg);
257 $headers = &$msg->headers($headers);
259 $to = array($params['toEmail']);
261 $mailer = \Civi
::service('pear_mail');
263 // Mail_smtp and Mail_sendmail mailers require Bcc anc Cc emails
264 // be included in both $to and $headers['Cc', 'Bcc']
265 if (get_class($mailer) != "Mail_mail") {
266 // get emails from headers, since these are
267 // combination of name and email addresses.
268 if (!empty($headers['Cc'])) {
269 $to[] = CRM_Utils_Array
::value('Cc', $headers);
271 if (!empty($headers['Bcc'])) {
272 $to[] = CRM_Utils_Array
::value('Bcc', $headers);
275 if (is_object($mailer)) {
276 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
277 $result = $mailer->send($to, $headers, $message);
278 if (is_a($result, 'PEAR_Error')) {
279 $message = self
::errorMessage($mailer, $result);
280 // append error message in case multiple calls are being made to
281 // this method in the course of sending a batch of messages.
282 CRM_Core_Session
::setStatus($message, ts('Mailing Error'), 'error');
286 CRM_Utils_Hook
::postEmailSend($params);
298 public static function errorMessage($mailer, $result) {
299 $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(
301 )) . '</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>';
303 if (is_a($mailer, 'Mail_smtp')) {
304 $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>';
307 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
310 $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(
311 1 => CRM_Utils_System
::docURL2('user/advanced-configuration/email-system-configuration', TRUE),
322 public static function logger(&$to, &$headers, &$message) {
324 $toString = implode(', ', $to);
328 $toString = $fileName = $to;
330 $content = "To: " . $toString . "\n";
331 foreach ($headers as $key => $val) {
332 $content .= "$key: $val\n";
334 $content .= "\n" . $message . "\n";
336 if (is_numeric(CIVICRM_MAIL_LOG
)) {
337 $config = CRM_Core_Config
::singleton();
338 // create the directory if not there
339 $dirName = $config->configAndLogDir
. 'mail' . DIRECTORY_SEPARATOR
;
340 CRM_Utils_File
::createDir($dirName);
341 $fileName = md5(uniqid(CRM_Utils_String
::munge($fileName))) . '.txt';
342 file_put_contents($dirName . $fileName,
347 file_put_contents(CIVICRM_MAIL_LOG
, $content, FILE_APPEND
);
352 * Get the email address itself from a formatted full name + address string
356 * @param string $header
357 * The full name + email address string.
360 * the plucked email address
362 public static function pluckEmailFromHeader($header) {
363 preg_match('/<([^<]*)>$/', $header, $matches);
365 if (isset($matches[1])) {
372 * Get the Active outBound email.
375 * TRUE if valid outBound email configuration found, false otherwise.
377 public static function validOutBoundMail() {
378 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
381 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MAIL
) {
384 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SMTP
) {
385 if (!isset($mailingInfo['smtpServer']) ||
$mailingInfo['smtpServer'] == '' ||
386 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
387 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' ||
$mailingInfo['smtpPassword'] == ''))
393 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SENDMAIL
) {
394 if (!$mailingInfo['sendmail_path'] ||
!$mailingInfo['sendmail_args']) {
399 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_REDIRECT_TO_DB
) {
407 * @param array $params
411 public static function &setMimeParams(&$message, $params = NULL) {
412 static $mimeParams = NULL;
416 'text_encoding' => '8bit',
417 'html_encoding' => '8bit',
418 'head_charset' => 'utf-8',
419 'text_charset' => 'utf-8',
420 'html_charset' => 'utf-8',
423 $params = $mimeParams;
425 return $message->get($params);
429 * @param string $name
431 * @param bool $useQuote
433 * @return null|string
435 public static function formatRFC822Email($name, $email, $useQuote = FALSE) {
440 // strip out double quotes if present at the beginning AND end
441 if (substr($name, 0, 1) == '"' &&
442 substr($name, -1, 1) == '"'
444 $name = substr($name, 1, -1);
448 // escape the special characters
449 $name = str_replace(array('<', '"', '>'),
450 array('\<', '\"', '\>'),
453 if (strpos($name, ',') !== FALSE ||
456 // quote the string if it has a comma
457 $name = '"' . $name . '"';
463 $result .= "<{$email}>";
468 * Takes a string and checks to see if it needs to be escaped / double quoted
469 * and if so does the needful and return the formatted name
471 * This code has been copied and adapted from ezc/Mail/src/tools.php
473 * @param string $name
477 public static function formatRFC2822Name($name) {
480 // remove the quotes around the name part if they are already there
481 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
482 $name = substr($name, 1, -1);
485 // add slashes to " and \ and surround the name part with quotes
486 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
487 $name = '"' . addcslashes($name, '\\"') . '"';
495 * @param string $fileName
496 * @param string $html
497 * @param string $format
501 public static function appendPDF($fileName, $html, $format = NULL) {
502 $pdf_filename = CRM_Core_Config
::singleton()->templateCompileDir
. CRM_Utils_File
::makeFileName($fileName);
505 // xmlns attribute is required in XHTML but it is invalid in HTML,
506 // Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
507 // and will be added to the <html> tag even if you do not include it.
508 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
510 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils
::html2pdf($html,
516 'fullPath' => $pdf_filename,
517 'mime_type' => 'application/pdf',
518 'cleanName' => $fileName,