mailManager = $mailManager; $this->accountService = $accountService; $this->clientFactory = $clientFactory; $this->request = $request; $this->httpClientService = $httpClientService; $this->logger = $logger; $this->currentUserId = $userId; } /** * @NoAdminRequired * @UserRateThrottle(limit=10, period=3600) */ public function unsubscribe(int $id): JsonResponse { try { $message = $this->mailManager->getMessage($this->currentUserId, $id); $mailbox = $this->mailManager->getMailbox($this->currentUserId, $message->getMailboxId()); $account = $this->accountService->find($this->currentUserId, $mailbox->getAccountId()); } catch (DoesNotExistException $e) { return JsonResponse::fail(null, Http::STATUS_NOT_FOUND); } $client = $this->clientFactory->getClient($account); try { $imapMessage = $this->mailManager->getImapMessage( $client, $account, $mailbox, $message->getUid(), true ); $unsubscribeUrl = $imapMessage->getUnsubscribeUrl(); if ($unsubscribeUrl === null || !$imapMessage->isOneClickUnsubscribe()) { return JsonResponse::fail(null, Http::STATUS_FORBIDDEN); } $httpClient = $this->httpClientService->newClient(); $httpClient->post($unsubscribeUrl, [ 'body' => [ 'List-Unsubscribe' => 'One-Click' ] ]); } catch (Exception $e) { $this->logger->error('Could not unsubscribe mailing list', [ 'exception' => $e, ]); return JsonResponse::error('Unknown error'); } finally { $client->logout(); } return JsonResponse::success(); } }