53 bool $isOAuth =
false,
54 bool $isSender =
false
62 if ($item->getCode() < 0)
74 $authError = Loc::getMessage(
'MAIL_MAILBOX_CONNECTOR_CLIENT_IMAP_AUTH_ERR_EXT');
75 if ($isOAuth && Loc::getMessage(
'MAIL_MAILBOX_CONNECTOR_CLIENT_ERR_OAUTH'))
77 $authError = Loc::getMessage(
'MAIL_MAILBOX_CONNECTOR_CLIENT_ERR_OAUTH');
79 if ($isOAuth && $isSender && Loc::getMessage(
'MAIL_MAILBOX_CONNECTOR_CLIENT_ERR_OAUTH_SMTP'))
81 $authError = Loc::getMessage(
'MAIL_MAILBOX_CONNECTOR_CLIENT_ERR_OAUTH_SMTP');
88 $moreDetailsSection =
false;
92 $moreDetailsSection =
true;
97 return $error->getMessage();
100 if($moreDetailsSection)
103 implode(
': ', array_map($reduce,
$messages)),
105 implode(
': ', array_map($reduce, $details))
111 implode(
': ', array_map($reduce,
$messages)),
273 string $storageOauthUid =
'',
274 bool $syncAfterConnection =
true,
275 bool $useSmtp =
true,
276 string $serverSmtp =
'',
278 bool $sslSmtp =
true,
279 string $loginSmtp =
'',
280 string $passwordSMTP =
'',
281 bool $useLimitSmtp =
false,
282 int $limitSmtp =
null,
283 string $mailboxName =
'',
284 string $senderName =
'',
289 $server = trim($server);
291 $currentSite = \CSite::getById(
SITE_ID)->fetch();
294 $this->setIsSmtpAvailable();
296 $service = Mail\MailServicesTable::getList([
299 'SERVICE_TYPE' =>
'imap',
305 $this->setError(self::NO_MAIL_SERVICES_ERROR_KEY);
317 $this->setError(self::LIMIT_ERROR_KEY);
340 'USERNAME' => $senderName ?:
'',
341 'SERVER' =>
$service[
'SERVER'] ?: trim($server),
342 'PORT' =>
$service[
'PORT'] ?: $port,
343 'USE_TLS' =>
$service[
'ENCRYPTION'] ?: $ssl,
346 'NAME' => $mailboxName ??
$login,
347 'PERIOD_CHECK' => 60 * 24,
350 'sync_from' => time(),
351 'crm_sync_from' => time(),
352 'activateSync' =>
false,
357 if (
'N' ==
$service[
'UPLOAD_OUTGOING'] || empty(
$service[
'UPLOAD_OUTGOING']))
359 $mailboxData[
'OPTIONS'][
'flags'][] =
'deny_upload';
365 $oauthHelper->getStoredToken($storageOauthUid);
366 $mailboxData[
'LOGIN'] = $mailboxData[
'EMAIL'];
367 $mailboxData[
'PASSWORD'] = $oauthHelper->buildMeta();
372 $mailboxData[
'LOGIN'] =
$login;
376 if (empty($mailbox[
'EMAIL']))
378 $address =
new Address($mailboxData[
'EMAIL']);
379 if (!$address->validate())
381 $this->setError(self::OAUTH_ERROR_KEY);
385 $mailboxData[
'EMAIL'] = $address->getEmail();
386 $this->email = $mailboxData[
'EMAIL'];
390 $this->email = $mailbox[
'EMAIL'];
395 $mailbox = Mail\MailboxTable::getList([
397 '=EMAIL' => $mailboxData[
'EMAIL'],
398 '=USER_ID' =>
$USER->getId(),
400 '=LID' => $currentSite[
'LID'],
404 if (!empty($mailbox))
406 $this->setError(self::EXISTS_ERROR_KEY);
411 if (empty($mailboxData[
'NAME']))
413 $mailboxData[
'NAME'] = $mailboxData[
'EMAIL'];
416 if (!in_array($mailboxData[
'USE_TLS'],
array(
'Y',
'S')))
418 $mailboxData[
'USE_TLS'] =
'N';
421 $unseen = Mail\Helper::getImapUnseen($mailboxData,
'inbox',
$error,
$errors);
422 if ($unseen ===
false)
437 $useSmtp = $useSmtp || $isSmtpOauthEnabled;
439 if ($this->getSmtpAvailable() && !$useSmtp && !empty($mailbox))
443 'IS_CONFIRMED' =>
true,
444 '=EMAIL' => $mailboxData[
'EMAIL'],
447 while ($item =
$res->fetch())
449 if (!empty($item[
'OPTIONS'][
'smtp'][
'server']))
451 unset($item[
'OPTIONS'][
'smtp']);
455 'OPTIONS' => $item[
'OPTIONS'],
461 Main\Mail\Sender::clearCustomSmtpCache($mailboxData[
'EMAIL']);
464 if ($this->getSmtpAvailable() && $useSmtp)
467 'NAME' => $mailboxData[
'USERNAME'],
468 'EMAIL' => $mailboxData[
'EMAIL'],
469 'USER_ID' =>
$USER->getId(),
470 'IS_CONFIRMED' =>
false,
471 'IS_PUBLIC' =>
false,
473 'source' =>
'mail.client.config',
478 ->setSelect([
'ID',
'OPTIONS'])
479 ->where(
'IS_CONFIRMED',
true)
480 ->where(
'EMAIL', $senderFields[
'EMAIL'])
481 ->where(
'USER_ID', $senderFields[
'USER_ID'])
485 foreach ($mailboxSenders as $sender)
487 if (empty($smtpConfirmed))
489 if (!empty($sender[
'OPTIONS'][
'smtp'][
'server']) && empty($sender[
'OPTIONS'][
'smtp'][
'encrypted']))
491 $smtpConfirmed = $sender[
'OPTIONS'][
'smtp'];
497 if (!empty($senderFields))
500 'server' =>
$service[
'SMTP_SERVER'] ?: trim($serverSmtp),
501 'port' =>
$service[
'SMTP_PORT'] ?: $portSmtp,
502 'protocol' => (
'Y' == (
$service[
'SMTP_ENCRYPTION'] ?: $sslSmtp) ?
'smtps' :
'smtp'),
503 'login' =>
$service[
'SMTP_LOGIN_AS_IMAP'] ==
'Y' ? $mailboxData[
'LOGIN'] : $loginSmtp,
507 if (!empty($smtpConfirmed) && is_array($smtpConfirmed))
510 $smtpConfig = array_filter($smtpConfig) + $smtpConfirmed;
515 $smtpConfig[
'limit'] = $limitSmtp;
518 if (
$service[
'SMTP_PASSWORD_AS_IMAP'] ==
'Y' && (!$storageOauthUid || $isSmtpOauthEnabled))
520 $smtpConfig[
'password'] = $mailboxData[
'PASSWORD'];
521 $smtpConfig[
'isOauth'] = !empty($storageOauthUid) && $isSmtpOauthEnabled;
523 else if ($passwordSMTP <>
'')
525 if (preg_match(
'/^\^/', $passwordSMTP))
527 $this->setError(self::SMTP_PASS_BAD_SYMBOLS_ERROR_KEY);
530 else if (preg_match(
'/\x00/', $passwordSMTP))
532 $this->setError(self::SMTP_PASS_BAD_SYMBOLS_ERROR_KEY);
536 $smtpConfig[
'password'] = $passwordSMTP;
537 $smtpConfig[
'isOauth'] = !empty($storageOauthUid) && $isSmtpOauthEnabled;
542 $regex =
'/^(?:(?:http|https|ssl|tls|smtp):\/\/)?((?:[a-z0-9](?:-*[a-z0-9])*\.?)+)$/i';
543 if (!preg_match($regex, $smtpConfig[
'server'],
$matches) &&
$matches[1] <>
'')
545 $this->setError(self::OAUTH_ERROR_KEY);
549 $smtpConfig[
'server'] =
$matches[1];
551 if (!self::isValidMailHost($smtpConfig[
'server']))
553 $this->setError(self::OAUTH_ERROR_KEY);
560 if ($smtpConfig[
'port'] <= 0 || $smtpConfig[
'port'] > 65535)
562 $this->setError(self::OAUTH_ERROR_KEY);
567 $senderFields[
'OPTIONS'][
'smtp'] = $smtpConfig;
569 if (!empty($smtpConfirmed))
571 $senderFields[
'IS_CONFIRMED'] = !array_diff(
572 array(
'server',
'port',
'protocol',
'login',
'password',
'isOauth'),
573 array_keys(array_intersect_assoc($smtpConfig, $smtpConfirmed))
580 $crmAvailable =
$USER->isAdmin() ||
$USER->canDoOperation(
'bitrix24_config')
581 || \COption::getOptionString(
'intranet',
'allow_external_mail_crm',
'Y',
SITE_ID) ==
'Y';
583 $mailboxData[
'OPTIONS'][
'sync_from'] = strtotime(
'today UTC 00:00'.sprintf(
'-%u days', self::MESSAGE_MAX_AGE));
587 $maxAge = self::CRM_MAX_AGE;
588 $mailboxData[
'OPTIONS'][
'flags'][] =
'crm_connect';
589 $mailboxData[
'OPTIONS'][
'crm_sync_from'] = strtotime(sprintf(
'-%u days', $maxAge));
590 $mailboxData[
'OPTIONS'][
'crm_new_entity_in'] = \CCrmOwnerType::LeadName;
591 $mailboxData[
'OPTIONS'][
'crm_new_entity_out'] = \CCrmOwnerType::ContactName;
592 $mailboxData[
'OPTIONS'][
'crm_lead_source'] =
'EMAIL';
593 $mailboxData[
'OPTIONS'][
'crm_lead_resp'] = [empty($mailbox) ?
$USER->getId() : $mailbox[
'USER_ID']];
597 $mailboxData[
'OPTIONS'][
'version'] = 6;
601 $mailboxData = array_merge([
602 'LID' => $currentSite[
'LID'],
605 'SERVER_TYPE' =>
$service[
'SERVICE_TYPE'],
606 'CHARSET' => $currentSite[
'CHARSET'],
607 'USER_ID' =>
$USER->getId(),
608 'SYNC_LOCK' => time()
611 $result = $mailboxId = \CMailbox::add($mailboxData);
613 addEventToStatFile(
'mail',
'add_mailbox',
$service[
'NAME'], (
$result > 0 ?
'success' :
'failed'));
617 $this->setError(self::EXISTS_ERROR_KEY);
627 if (!empty($senderFields) && empty($senderFields[
'IS_CONFIRMED']))
636 else if (!empty(
$result[
'error']))
641 else if (empty(
$result[
'confirmed']))
643 $this->
addError(
'MAIL_CLIENT_CONFIG_SMTP_CONFIRM');
648 $ownerAccessCode =
'U' . (empty($mailbox) ?
$USER->getId() : $mailbox[
'USER_ID']);
651 foreach (array_unique(
$access) as $item)
654 'MAILBOX_ID' => $mailboxId,
656 'ACCESS_CODE' => $item,
660 $mailboxHelper = Mailbox::createInstance($mailboxId);
661 $mailboxHelper->cacheDirs();
664 'MAILBOX_ID' => $mailboxId,
665 'NAME' => sprintf(
'CRM IMAP %u', $mailboxId),
666 'ACTION_TYPE' =>
'crm_imap',
667 'WHEN_MAIL_RECEIVED' =>
'Y',
668 'WHEN_MANUALLY_RUN' =>
'Y',
675 if ($syncAfterConnection)
677 $this->syncMailbox($mailboxId);
682 'email' => trim($mailboxData[
'EMAIL']),