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
35 class CRM_Utils_Mail
{
38 * Create a new mailer to send any mail from the application.
40 * Note: The mailer is opened in persistent mode.
42 * Note: You probably don't want to call this directly. Get a reference
43 * to the mailer through the container.
47 public static function createMailer() {
48 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
52 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_REDIRECT_TO_DB ||
53 (defined('CIVICRM_MAILER_SPOOL') && CIVICRM_MAILER_SPOOL
)
55 $mailer = self
::_createMailer('CRM_Mailing_BAO_Spool', array());
57 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SMTP
) {
58 if ($mailingInfo['smtpServer'] == '' ||
!$mailingInfo['smtpServer']) {
59 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'))));
60 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'))));
63 $params['host'] = $mailingInfo['smtpServer'] ?
$mailingInfo['smtpServer'] : 'localhost';
64 $params['port'] = $mailingInfo['smtpPort'] ?
$mailingInfo['smtpPort'] : 25;
66 if ($mailingInfo['smtpAuth']) {
67 $params['username'] = $mailingInfo['smtpUsername'];
68 $params['password'] = CRM_Utils_Crypt
::decrypt($mailingInfo['smtpPassword']);
69 $params['auth'] = TRUE;
72 $params['auth'] = FALSE;
75 // set the localhost value, CRM-3153
76 $params['localhost'] = CRM_Utils_Array
::value('SERVER_NAME', $_SERVER, 'localhost');
78 // also set the timeout value, lets set it to 30 seconds
80 $params['timeout'] = 30;
83 $params['persist'] = TRUE;
85 $mailer = self
::_createMailer('smtp', $params);
87 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SENDMAIL
) {
88 if ($mailingInfo['sendmail_path'] == '' ||
89 !$mailingInfo['sendmail_path']
91 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'))));
92 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'))));
94 $params['sendmail_path'] = $mailingInfo['sendmail_path'];
95 $params['sendmail_args'] = $mailingInfo['sendmail_args'];
97 $mailer = self
::_createMailer('sendmail', $params);
99 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MAIL
) {
100 $mailer = self
::_createMailer('mail', array());
102 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MOCK
) {
103 $mailer = self
::_createMailer('mock', array());
105 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
) {
106 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'))));
107 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'))));
110 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'))));
111 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'))));
112 CRM_Core_Error
::debug_var('mailing_info', $mailingInfo);
118 * Create a new instance of a PEAR Mail driver.
120 * @param string $driver
121 * 'CRM_Mailing_BAO_Spool' or a name suitable for Mail::factory().
122 * @param array $params
124 * More specifically, a class which implements the "send()" function
126 public static function _createMailer($driver, $params) {
127 if ($driver == 'CRM_Mailing_BAO_Spool') {
128 $mailer = new CRM_Mailing_BAO_Spool($params);
131 $mailer = Mail
::factory($driver, $params);
133 CRM_Utils_Hook
::alterMail($mailer, $driver, $params);
138 * Wrapper function to send mail in CiviCRM. Hooks are called from this function. The input parameter
139 * is an associateive array which holds the values of field needed to send an email. These are:
141 * from : complete from envelope
142 * toName : name of person to send email
143 * toEmail : email address to send to
144 * cc : email addresses to cc
145 * bcc : email addresses to bcc
146 * subject : subject of the email
147 * text : text of the message
148 * html : html version of the message
149 * replyTo : reply-to header in the email
150 * attachments: an associative array of
151 * fullPath : complete pathname to the file
152 * mime_type: mime type of the attachment
153 * cleanName: the user friendly name of the attachmment
155 * @param array $params
159 * TRUE if a mail was sent, else FALSE.
161 public static function send(&$params) {
162 $returnPath = CRM_Core_BAO_MailSettings
::defaultReturnPath();
163 $includeMessageId = CRM_Core_BAO_MailSettings
::includeMessageId();
164 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
165 $from = CRM_Utils_Array
::value('from', $params);
167 $returnPath = self
::pluckEmailFromHeader($from);
169 $params['returnPath'] = $returnPath;
171 // first call the mail alter hook
172 CRM_Utils_Hook
::alterMailParams($params);
174 // check if any module has aborted mail sending
175 if (!empty($params['abortMailSend']) ||
empty($params['toEmail'])) {
179 $textMessage = CRM_Utils_Array
::value('text', $params);
180 $htmlMessage = CRM_Utils_Array
::value('html', $params);
181 $attachments = CRM_Utils_Array
::value('attachments', $params);
184 if (trim(CRM_Utils_String
::htmlToText($htmlMessage)) == '') {
185 $htmlMessage = FALSE;
189 // CRM-10699 support custom email headers
190 if (!empty($params['headers'])) {
191 $headers = array_merge($headers, $params['headers']);
193 $headers['From'] = $params['from'];
194 $headers['To'] = self
::formatRFC822Email(
195 CRM_Utils_Array
::value('toName', $params),
196 CRM_Utils_Array
::value('toEmail', $params),
199 $headers['Cc'] = CRM_Utils_Array
::value('cc', $params);
200 $headers['Bcc'] = CRM_Utils_Array
::value('bcc', $params);
201 $headers['Subject'] = CRM_Utils_Array
::value('subject', $params);
202 $headers['Content-Type'] = $htmlMessage ?
'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
203 $headers['Content-Disposition'] = 'inline';
204 $headers['Content-Transfer-Encoding'] = '8bit';
205 $headers['Return-Path'] = CRM_Utils_Array
::value('returnPath', $params);
207 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
208 $replyTo = CRM_Utils_Array
::value('replyTo', $params, $from);
210 if (!empty($replyTo)) {
211 $headers['Reply-To'] = $replyTo;
213 $headers['Date'] = date('r');
214 if ($includeMessageId) {
215 $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@$emailDomain>";
217 if (!empty($params['autoSubmitted'])) {
218 $headers['Auto-Submitted'] = "Auto-Generated";
221 //make sure we has to have space, CRM-6977
222 foreach (array('From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path') as $fld) {
223 if (isset($headers[$fld])) {
224 $headers[$fld] = str_replace('"<', '" <', $headers[$fld]);
228 // quote FROM, if comma is detected AND is not already quoted. CRM-7053
229 if (strpos($headers['From'], ',') !== FALSE) {
230 $from = explode(' <', $headers['From']);
231 $headers['From'] = self
::formatRFC822Email(
233 substr(trim($from[1]), 0, -1),
238 require_once 'Mail/mime.php';
239 $msg = new Mail_mime("\n");
241 $msg->setTxtBody($textMessage);
245 $msg->setHTMLBody($htmlMessage);
248 if (!empty($attachments)) {
249 foreach ($attachments as $fileID => $attach) {
252 $attach['mime_type'],
258 $message = self
::setMimeParams($msg);
259 $headers = &$msg->headers($headers);
261 $to = array($params['toEmail']);
263 $mailer = \Civi
::service('pear_mail');
265 // Mail_smtp and Mail_sendmail mailers require Bcc anc Cc emails
266 // be included in both $to and $headers['Cc', 'Bcc']
267 if (get_class($mailer) != "Mail_mail") {
268 //get emails from headers, since these are
269 //combination of name and email addresses.
270 if (!empty($headers['Cc'])) {
271 $to[] = CRM_Utils_Array
::value('Cc', $headers);
273 if (!empty($headers['Bcc'])) {
274 $to[] = CRM_Utils_Array
::value('Bcc', $headers);
277 if (is_object($mailer)) {
278 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
279 $result = $mailer->send($to, $headers, $message);
280 if (is_a($result, 'PEAR_Error')) {
281 $message = self
::errorMessage($mailer, $result);
282 // append error message in case multiple calls are being made to
283 // this method in the course of sending a batch of messages.
284 CRM_Core_Session
::setStatus($message, ts('Mailing Error'), 'error');
288 CRM_Utils_Hook
::postEmailSend($params);
300 public static function errorMessage($mailer, $result) {
301 $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(
303 )) . '</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>';
305 if (is_a($mailer, 'Mail_smtp')) {
306 $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>';
309 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
312 $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(
313 1 => CRM_Utils_System
::docURL2('user/advanced-configuration/email-system-configuration', TRUE),
324 public static function logger(&$to, &$headers, &$message) {
326 $toString = implode(', ', $to);
330 $toString = $fileName = $to;
332 $content = "To: " . $toString . "\n";
333 foreach ($headers as $key => $val) {
334 $content .= "$key: $val\n";
336 $content .= "\n" . $message . "\n";
338 if (is_numeric(CIVICRM_MAIL_LOG
)) {
339 $config = CRM_Core_Config
::singleton();
340 // create the directory if not there
341 $dirName = $config->configAndLogDir
. 'mail' . DIRECTORY_SEPARATOR
;
342 CRM_Utils_File
::createDir($dirName);
343 $fileName = md5(uniqid(CRM_Utils_String
::munge($fileName))) . '.txt';
344 file_put_contents($dirName . $fileName,
349 file_put_contents(CIVICRM_MAIL_LOG
, $content, FILE_APPEND
);
354 * Get the email address itself from a formatted full name + address string
358 * @param string $header
359 * The full name + email address string.
362 * the plucked email address
364 public static function pluckEmailFromHeader($header) {
365 preg_match('/<([^<]*)>$/', $header, $matches);
367 if (isset($matches[1])) {
374 * Get the Active outBound email.
377 * TRUE if valid outBound email configuration found, false otherwise.
379 public static function validOutBoundMail() {
380 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
383 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_MAIL
) {
386 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SMTP
) {
387 if (!isset($mailingInfo['smtpServer']) ||
$mailingInfo['smtpServer'] == '' ||
388 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
389 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' ||
$mailingInfo['smtpPassword'] == ''))
395 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_SENDMAIL
) {
396 if (!$mailingInfo['sendmail_path'] ||
!$mailingInfo['sendmail_args']) {
401 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config
::OUTBOUND_OPTION_REDIRECT_TO_DB
) {
409 * @param array $params
413 public static function &setMimeParams(&$message, $params = NULL) {
414 static $mimeParams = NULL;
418 'text_encoding' => '8bit',
419 'html_encoding' => '8bit',
420 'head_charset' => 'utf-8',
421 'text_charset' => 'utf-8',
422 'html_charset' => 'utf-8',
425 $params = $mimeParams;
427 return $message->get($params);
431 * @param string $name
433 * @param bool $useQuote
435 * @return null|string
437 public static function formatRFC822Email($name, $email, $useQuote = FALSE) {
442 // strip out double quotes if present at the beginning AND end
443 if (substr($name, 0, 1) == '"' &&
444 substr($name, -1, 1) == '"'
446 $name = substr($name, 1, -1);
450 // escape the special characters
451 $name = str_replace(array('<', '"', '>'),
452 array('\<', '\"', '\>'),
455 if (strpos($name, ',') !== FALSE ||
458 // quote the string if it has a comma
459 $name = '"' . $name . '"';
465 $result .= "<{$email}>";
470 * Takes a string and checks to see if it needs to be escaped / double quoted
471 * and if so does the needful and return the formatted name
473 * This code has been copied and adapted from ezc/Mail/src/tools.php
475 public static function formatRFC2822Name($name) {
478 // remove the quotes around the name part if they are already there
479 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
480 $name = substr($name, 1, -1);
483 // add slashes to " and \ and surround the name part with quotes
484 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
485 $name = '"' . addcslashes($name, '\\"') . '"';
493 * @param string $fileName
494 * @param string $html
495 * @param string $format
499 public static function appendPDF($fileName, $html, $format = NULL) {
500 $pdf_filename = CRM_Core_Config
::singleton()->templateCompileDir
. CRM_Utils_File
::makeFileName($fileName);
503 //xmlns attribute is required in XHTML but it is invalid in HTML,
504 //Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
505 //and will be added to the <html> tag even if you do not include it.
506 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
508 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils
::html2pdf($html,
514 'fullPath' => $pdf_filename,
515 'mime_type' => 'application/pdf',
516 'cleanName' => $fileName,