From ccda7186233c02073ae48b508296bd61f0694197 Mon Sep 17 00:00:00 2001
From: Daniel Ziegenberg <daniel@ziegenberg.at>
Date: Sat, 17 Sep 2022 20:53:00 +0200
Subject: [PATCH] MDL-75466 core: Upgrade PHPmailer to 6.6.5

Signed-off-by: Daniel Ziegenberg <daniel@ziegenberg.at>
---
 lib/phpmailer/README.md                      |   3 +
 lib/phpmailer/VERSION                        |   2 +-
 lib/phpmailer/language/phpmailer.lang-ch.php |  27 ----
 lib/phpmailer/language/phpmailer.lang-da.php |  10 +-
 lib/phpmailer/language/phpmailer.lang-el.php |  41 +++---
 lib/phpmailer/language/phpmailer.lang-fr.php |   2 +-
 lib/phpmailer/language/phpmailer.lang-mn.php |  27 ++++
 lib/phpmailer/language/phpmailer.lang-pl.php |  13 +-
 lib/phpmailer/readme_moodle.txt              |   4 +-
 lib/phpmailer/src/OAuth.php                  |   2 +-
 lib/phpmailer/src/OAuthTokenProvider.php     |  44 ++++++
 lib/phpmailer/src/PHPMailer.php              | 144 ++++++++++++-------
 lib/phpmailer/src/SMTP.php                   |  11 +-
 lib/thirdpartylibs.xml                       |   2 +-
 14 files changed, 221 insertions(+), 111 deletions(-)
 delete mode 100644 lib/phpmailer/language/phpmailer.lang-ch.php
 create mode 100644 lib/phpmailer/language/phpmailer.lang-mn.php
 create mode 100644 lib/phpmailer/src/OAuthTokenProvider.php

diff --git a/lib/phpmailer/README.md b/lib/phpmailer/README.md
index 81b0897637d..56f971a4998 100644
--- a/lib/phpmailer/README.md
+++ b/lib/phpmailer/README.md
@@ -1,3 +1,5 @@
+[![SWUbanner](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/banner2-direct.svg)](https://supportukrainenow.org/)
+
 ![PHPMailer](https://raw.github.com/PHPMailer/PHPMailer/master/examples/images/phpmailer.png)
 
 # PHPMailer – A full-featured email creation and transfer class for PHP
@@ -8,6 +10,7 @@
 [![Total Downloads](https://poser.pugx.org/phpmailer/phpmailer/downloads)](https://packagist.org/packages/phpmailer/phpmailer)
 [![License](https://poser.pugx.org/phpmailer/phpmailer/license.svg)](https://packagist.org/packages/phpmailer/phpmailer)
 [![API Docs](https://github.com/phpmailer/phpmailer/workflows/Docs/badge.svg)](https://phpmailer.github.io/PHPMailer/)
+[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/PHPMailer/PHPMailer/badge)](https://api.securityscorecards.dev/projects/github.com/PHPMailer/PHPMailer)
 
 ## Features
 - Probably the world's most popular code for sending email from PHP!
diff --git a/lib/phpmailer/VERSION b/lib/phpmailer/VERSION
index 73092f345e5..653877f1f9b 100644
--- a/lib/phpmailer/VERSION
+++ b/lib/phpmailer/VERSION
@@ -1 +1 @@
-6.5.3
\ No newline at end of file
+6.6.5
\ No newline at end of file
diff --git a/lib/phpmailer/language/phpmailer.lang-ch.php b/lib/phpmailer/language/phpmailer.lang-ch.php
deleted file mode 100644
index 500c952676d..00000000000
--- a/lib/phpmailer/language/phpmailer.lang-ch.php
+++ /dev/null
@@ -1,27 +0,0 @@
-<?php
-
-/**
- * Chinese PHPMailer language file: refer to English translation for definitive list
- * @package PHPMailer
- * @author LiuXin <http://www.80x86.cn/blog/>
- */
-
-$PHPMAILER_LANG['authenticate']         = 'SMTP 错误:身份验证失败。';
-$PHPMAILER_LANG['connect_host']         = 'SMTP 错误: 不能连接SMTP主机。';
-$PHPMAILER_LANG['data_not_accepted']    = 'SMTP 错误: 数据不可接受。';
-//$PHPMAILER_LANG['empty_message']        = 'Message body empty';
-$PHPMAILER_LANG['encoding']             = '未知编码:';
-$PHPMAILER_LANG['execute']              = '不能执行: ';
-$PHPMAILER_LANG['file_access']          = '不能访问文件:';
-$PHPMAILER_LANG['file_open']            = '文件错误:不能打开文件:';
-$PHPMAILER_LANG['from_failed']          = '下面的发送地址邮件发送失败了: ';
-$PHPMAILER_LANG['instantiate']          = '不能实现mail方法。';
-//$PHPMAILER_LANG['invalid_address']      = 'Invalid address: ';
-$PHPMAILER_LANG['mailer_not_supported'] = ' 您所选择的发送邮件的方法并不支持。';
-$PHPMAILER_LANG['provide_address']      = '您必须提供至少一个 收信人的email地址。';
-$PHPMAILER_LANG['recipients_failed']    = 'SMTP 错误: 下面的 收件人失败了: ';
-//$PHPMAILER_LANG['signing']              = 'Signing Error: ';
-//$PHPMAILER_LANG['smtp_connect_failed']  = 'SMTP Connect() failed.';
-//$PHPMAILER_LANG['smtp_error']           = 'SMTP server error: ';
-//$PHPMAILER_LANG['variable_set']         = 'Cannot set or reset variable: ';
-//$PHPMAILER_LANG['extension_missing']    = 'Extension missing: ';
diff --git a/lib/phpmailer/language/phpmailer.lang-da.php b/lib/phpmailer/language/phpmailer.lang-da.php
index 1edba1d7a4e..8b7b38a6ee5 100644
--- a/lib/phpmailer/language/phpmailer.lang-da.php
+++ b/lib/phpmailer/language/phpmailer.lang-da.php
@@ -14,16 +14,22 @@ $PHPMAILER_LANG['data_not_accepted']    = 'SMTP fejl: Data blev ikke accepteret.
 $PHPMAILER_LANG['empty_message']        = 'Meddelelsen er uden indhold';
 $PHPMAILER_LANG['encoding']             = 'Ukendt encode-format: ';
 $PHPMAILER_LANG['execute']              = 'Kunne ikke afvikle: ';
+$PHPMAILER_LANG['extension_missing']    = 'Udvidelse mangler: ';
 $PHPMAILER_LANG['file_access']          = 'Kunne ikke tilgå filen: ';
 $PHPMAILER_LANG['file_open']            = 'Fil fejl: Kunne ikke åbne filen: ';
 $PHPMAILER_LANG['from_failed']          = 'Følgende afsenderadresse er forkert: ';
 $PHPMAILER_LANG['instantiate']          = 'Email funktionen kunne ikke initialiseres.';
 $PHPMAILER_LANG['invalid_address']      = 'Udgyldig adresse: ';
+$PHPMAILER_LANG['invalid_header']       = 'Ugyldig header navn eller værdi';
+$PHPMAILER_LANG['invalid_hostentry']    = 'Ugyldig hostentry: ';
+$PHPMAILER_LANG['invalid_host']         = 'Ugyldig vært: ';
 $PHPMAILER_LANG['mailer_not_supported'] = ' mailer understøttes ikke.';
 $PHPMAILER_LANG['provide_address']      = 'Indtast mindst en modtagers email adresse.';
-$PHPMAILER_LANG['recipients_failed']    = 'SMTP fejl: Følgende modtagere er forkerte: ';
+$PHPMAILER_LANG['recipients_failed']    = 'SMTP fejl: Følgende modtagere fejlede: ';
 $PHPMAILER_LANG['signing']              = 'Signeringsfejl: ';
+$PHPMAILER_LANG['smtp_code']            = 'SMTP kode: ';
+$PHPMAILER_LANG['smtp_code_ex']         = 'Yderligere SMTP info: ';
 $PHPMAILER_LANG['smtp_connect_failed']  = 'SMTP Connect() fejlede.';
+$PHPMAILER_LANG['smtp_detail']          = 'Detalje: ';
 $PHPMAILER_LANG['smtp_error']           = 'SMTP server fejl: ';
 $PHPMAILER_LANG['variable_set']         = 'Kunne ikke definere eller nulstille variablen: ';
-$PHPMAILER_LANG['extension_missing']    = 'Udvidelse mangler: ';
diff --git a/lib/phpmailer/language/phpmailer.lang-el.php b/lib/phpmailer/language/phpmailer.lang-el.php
index b3d5ca94bd7..339ee5753b7 100644
--- a/lib/phpmailer/language/phpmailer.lang-el.php
+++ b/lib/phpmailer/language/phpmailer.lang-el.php
@@ -5,22 +5,29 @@
  * @package PHPMailer
  */
 
-$PHPMAILER_LANG['authenticate']         = 'SMTP Σφάλμα: Αδυναμία πιστοποίησης (authentication).';
-$PHPMAILER_LANG['connect_host']         = 'SMTP Σφάλμα: Αδυναμία σύνδεσης στον SMTP-Host.';
-$PHPMAILER_LANG['data_not_accepted']    = 'SMTP Σφάλμα: Τα δεδομένα δεν έγιναν αποδεκτά.';
-$PHPMAILER_LANG['empty_message']        = 'Το E-Mail δεν έχει περιεχόμενο .';
-$PHPMAILER_LANG['encoding']             = 'Αγνωστο Encoding-Format: ';
-$PHPMAILER_LANG['execute']              = 'Αδυναμία εκτέλεσης ακόλουθης εντολής: ';
-$PHPMAILER_LANG['file_access']          = 'Αδυναμία προσπέλασης του αρχείου: ';
-$PHPMAILER_LANG['file_open']            = 'Σφάλμα Αρχείου: Δεν είναι δυνατό το άνοιγμα του ακόλουθου αρχείου: ';
-$PHPMAILER_LANG['from_failed']          = 'Η παρακάτω διεύθυνση αποστολέα δεν είναι σωστή: ';
-$PHPMAILER_LANG['instantiate']          = 'Αδυναμία εκκίνησης Mail function.';
-$PHPMAILER_LANG['invalid_address']      = 'Το μήνυμα δεν εστάλη, η διεύθυνση δεν είναι έγκυρη: ';
+$PHPMAILER_LANG['authenticate']         = 'Σφάλμα SMTP: Αδυναμία πιστοποίησης.';
+$PHPMAILER_LANG['buggy_php']            = 'Η έκδοση PHP που χρησιμοποιείτε παρουσιάζει σφάλμα που μπορεί να έχει ως αποτέλεσμα κατεστραμένα μηνύματα. Για να το διορθώσετε, αλλάξτε τον τρόπο αποστολής σε SMTP, απενεργοποιήστε την επιλογή mail.add_x_header στο αρχείο php.ini, αλλάξτε λειτουργικό σε MacOS ή Linux ή αναβαθμίστε την PHP σε έκδοση 7.0.17+ ή 7.1.3+.';
+$PHPMAILER_LANG['connect_host']         = 'Σφάλμα SMTP: Αδυναμία σύνδεσης με τον φιλοξενητή SMTP.';
+$PHPMAILER_LANG['data_not_accepted']    = 'Σφάλμα SMTP: Μη αποδεκτά δεδομένα.';
+$PHPMAILER_LANG['empty_message']        = 'Η ηλεκτρονική επιστολή δεν έχει περιεχόμενο.';
+$PHPMAILER_LANG['encoding']             = 'Άγνωστη μορφή κωδικοποίησης: ';
+$PHPMAILER_LANG['execute']              = 'Αδυναμία εκτέλεσης: ';
+$PHPMAILER_LANG['extension_missing']    = 'Απουσία επέκτασης: ';
+$PHPMAILER_LANG['file_access']          = 'Αδυναμία πρόσβασης στο αρχείο: ';
+$PHPMAILER_LANG['file_open']            = 'Σφάλμα Αρχείου: Αδυναμία ανοίγματος αρχείου: ';
+$PHPMAILER_LANG['from_failed']          = 'Η ακόλουθη διεύθυνση αποστολέα δεν είναι σωστή: ';
+$PHPMAILER_LANG['instantiate']          = 'Αδυναμία εκκίνησης συνάρτησης Mail.';
+$PHPMAILER_LANG['invalid_address']      = 'Μη έγκυρη διεύθυνση: ';
+$PHPMAILER_LANG['invalid_header']       = 'Μη έγκυρο όνομα κεφαλίδας ή τιμή';
+$PHPMAILER_LANG['invalid_hostentry']    = 'Μη έγκυρη εισαγωγή φιλοξενητή: ';
+$PHPMAILER_LANG['invalid_host']         = 'Μη έγκυρος φιλοξενητής: ';
 $PHPMAILER_LANG['mailer_not_supported'] = ' mailer δεν υποστηρίζεται.';
-$PHPMAILER_LANG['provide_address']      = 'Παρακαλούμε δώστε τουλάχιστον μια e-mail διεύθυνση παραλήπτη.';
-$PHPMAILER_LANG['recipients_failed']    = 'SMTP Σφάλμα: Οι παρακάτω διευθύνσεις παραλήπτη δεν είναι έγκυρες: ';
+$PHPMAILER_LANG['provide_address']      = 'Δώστε τουλάχιστον μια ηλεκτρονική διεύθυνση παραλήπτη.';
+$PHPMAILER_LANG['recipients_failed']    = 'Σφάλμα SMTP: Οι παρακάτω διευθύνσεις παραλήπτη δεν είναι έγκυρες: ';
 $PHPMAILER_LANG['signing']              = 'Σφάλμα υπογραφής: ';
-$PHPMAILER_LANG['smtp_connect_failed']  = 'Αποτυχία σύνδεσης στον SMTP Server.';
-$PHPMAILER_LANG['smtp_error']           = 'Σφάλμα από τον SMTP Server: ';
-$PHPMAILER_LANG['variable_set']         = 'Αδυναμία ορισμού ή αρχικοποίησης μεταβλητής: ';
-//$PHPMAILER_LANG['extension_missing']    = 'Extension missing: ';
+$PHPMAILER_LANG['smtp_code']            = 'Κώδικάς SMTP: ';
+$PHPMAILER_LANG['smtp_code_ex']         = 'Πρόσθετες πληροφορίες SMTP: ';
+$PHPMAILER_LANG['smtp_connect_failed']  = 'Αποτυχία σύνδεσης SMTP.';
+$PHPMAILER_LANG['smtp_detail']          = 'Λεπτομέρεια: ';
+$PHPMAILER_LANG['smtp_error']           = 'Σφάλμα με τον διακομιστή SMTP: ';
+$PHPMAILER_LANG['variable_set']         = 'Αδυναμία ορισμού ή επαναφοράς μεταβλητής: ';
diff --git a/lib/phpmailer/language/phpmailer.lang-fr.php b/lib/phpmailer/language/phpmailer.lang-fr.php
index 979e44b5156..38a7a8e7e5b 100644
--- a/lib/phpmailer/language/phpmailer.lang-fr.php
+++ b/lib/phpmailer/language/phpmailer.lang-fr.php
@@ -10,7 +10,7 @@
  */
 
 $PHPMAILER_LANG['authenticate']         = 'Erreur SMTP : échec de l’authentification.';
-$PHPMAILER_LANG['buggy_php']            = 'Votre version de PHP est affectée par un bogue qui peut entraîner des messages corrompus. Pour résoudre ce problème, passez à l’envoi par SMTP, désactivez l’option mail.add_x_header dans le fichier php.ini, passez à MacOS ou Linux, ou passez PHP à la version 7.0.17+ ou 7.1.3+.';
+$PHPMAILER_LANG['buggy_php']            = 'Votre version de PHP est affectée par un bug qui peut entraîner des messages corrompus. Pour résoudre ce problème, passez à l’envoi par SMTP, désactivez l’option mail.add_x_header dans le fichier php.ini, passez à MacOS ou Linux, ou passez PHP à la version 7.0.17+ ou 7.1.3+.';
 $PHPMAILER_LANG['connect_host']         = 'Erreur SMTP : impossible de se connecter au serveur SMTP.';
 $PHPMAILER_LANG['data_not_accepted']    = 'Erreur SMTP : données incorrectes.';
 $PHPMAILER_LANG['empty_message']        = 'Corps du message vide.';
diff --git a/lib/phpmailer/language/phpmailer.lang-mn.php b/lib/phpmailer/language/phpmailer.lang-mn.php
new file mode 100644
index 00000000000..04d262c7243
--- /dev/null
+++ b/lib/phpmailer/language/phpmailer.lang-mn.php
@@ -0,0 +1,27 @@
+<?php
+
+/**
+ * Mongolian PHPMailer language file: refer to English translation for definitive list
+ * @package PHPMailer
+ * @author @wispas
+ */
+
+$PHPMAILER_LANG['authenticate']         = 'Алдаа SMTP: Холбогдож чадсангүй.';
+$PHPMAILER_LANG['connect_host']         = 'Алдаа SMTP: SMTP- сервертэй холбогдож болохгүй байна.';
+$PHPMAILER_LANG['data_not_accepted']    = 'Алдаа SMTP: зөвшөөрөгдсөнгүй.';
+$PHPMAILER_LANG['encoding']             = 'Тодорхойгүй кодчилол: ';
+$PHPMAILER_LANG['execute']              = 'Коммандыг гүйцэтгэх боломжгүй байна: ';
+$PHPMAILER_LANG['file_access']          = 'Файлд хандах боломжгүй байна: ';
+$PHPMAILER_LANG['file_open']            = 'Файлын алдаа: файлыг нээх боломжгүй байна: ';
+$PHPMAILER_LANG['from_failed']          = 'Илгээгчийн хаяг буруу байна: ';
+$PHPMAILER_LANG['instantiate']          = 'Mail () функцийг ажиллуулах боломжгүй байна.';
+$PHPMAILER_LANG['provide_address']      = 'Хүлээн авагчийн имэйл хаягийг оруулна уу.';
+$PHPMAILER_LANG['mailer_not_supported'] = ' — мэйл серверийг дэмжсэнгүй.';
+$PHPMAILER_LANG['recipients_failed']    = 'Алдаа SMTP: ийм хаягийг илгээж чадсангүй: ';
+$PHPMAILER_LANG['empty_message']        = 'Хоосон мессэж';
+$PHPMAILER_LANG['invalid_address']      = 'И-Мэйл буруу форматтай тул илгээх боломжгүй: ';
+$PHPMAILER_LANG['signing']              = 'Гарын үсгийн алдаа: ';
+$PHPMAILER_LANG['smtp_connect_failed']  = 'SMTP сервертэй холбогдоход алдаа гарлаа';
+$PHPMAILER_LANG['smtp_error']           = 'SMTP серверийн алдаа: ';
+$PHPMAILER_LANG['variable_set']         = 'Хувьсагчийг тохируулах эсвэл дахин тохируулах боломжгүй байна: ';
+$PHPMAILER_LANG['extension_missing']    = 'Өргөтгөл байхгүй: ';
diff --git a/lib/phpmailer/language/phpmailer.lang-pl.php b/lib/phpmailer/language/phpmailer.lang-pl.php
index 23caa71bee4..b0469fdb7a8 100644
--- a/lib/phpmailer/language/phpmailer.lang-pl.php
+++ b/lib/phpmailer/language/phpmailer.lang-pl.php
@@ -9,19 +9,18 @@ $PHPMAILER_LANG['authenticate']         = 'Błąd SMTP: Nie można przeprowadzi
 $PHPMAILER_LANG['connect_host']         = 'Błąd SMTP: Nie można połączyć się z wybranym hostem.';
 $PHPMAILER_LANG['data_not_accepted']    = 'Błąd SMTP: Dane nie zostały przyjęte.';
 $PHPMAILER_LANG['empty_message']        = 'Wiadomość jest pusta.';
-$PHPMAILER_LANG['encoding']             = 'Nieznany sposób kodowania znaków: ';
+$PHPMAILER_LANG['encoding']             = 'Błędny sposób kodowania znaków: ';
 $PHPMAILER_LANG['execute']              = 'Nie można uruchomić: ';
 $PHPMAILER_LANG['file_access']          = 'Brak dostępu do pliku: ';
 $PHPMAILER_LANG['file_open']            = 'Nie można otworzyć pliku: ';
-$PHPMAILER_LANG['from_failed']          = 'Następujący adres Nadawcy jest nieprawidłowy: ';
+$PHPMAILER_LANG['from_failed']          = 'Następujący adres nadawcy jest nieprawidłowy lub nie istnieje: ';
 $PHPMAILER_LANG['instantiate']          = 'Nie można wywołać funkcji mail(). Sprawdź konfigurację serwera.';
-$PHPMAILER_LANG['invalid_address']      = 'Nie można wysłać wiadomości, ' .
-    'następujący adres Odbiorcy jest nieprawidłowy: ';
-$PHPMAILER_LANG['provide_address']      = 'Należy podać prawidłowy adres email Odbiorcy.';
+$PHPMAILER_LANG['invalid_address']      = 'Nie można wysłać wiadomości, ' . 'następujący adres odbiorcy jest nieprawidłowy lub nie istnieje: ';
+$PHPMAILER_LANG['provide_address']      = 'Należy podać prawidłowy adres email odbiorcy.';
 $PHPMAILER_LANG['mailer_not_supported'] = 'Wybrana metoda wysyłki wiadomości nie jest obsługiwana.';
-$PHPMAILER_LANG['recipients_failed']    = 'Błąd SMTP: Następujący odbiorcy są nieprawidłowi: ';
+$PHPMAILER_LANG['recipients_failed']    = 'Błąd SMTP: Następujący odbiorcy są nieprawidłowi lub nie istnieją: ';
 $PHPMAILER_LANG['signing']              = 'Błąd podpisywania wiadomości: ';
-$PHPMAILER_LANG['smtp_connect_failed']  = 'SMTP Connect() zakończone niepowodzeniem.';
+$PHPMAILER_LANG['smtp_connect_failed']  = 'Wywołanie funkcji SMTP Connect() zostało zakończone niepowodzeniem.';
 $PHPMAILER_LANG['smtp_error']           = 'Błąd SMTP: ';
 $PHPMAILER_LANG['variable_set']         = 'Nie można ustawić lub zmodyfikować zmiennej: ';
 $PHPMAILER_LANG['extension_missing']    = 'Brakujące rozszerzenie: ';
diff --git a/lib/phpmailer/readme_moodle.txt b/lib/phpmailer/readme_moodle.txt
index 175b88d9028..5fca17cecb9 100644
--- a/lib/phpmailer/readme_moodle.txt
+++ b/lib/phpmailer/readme_moodle.txt
@@ -1,9 +1,9 @@
-Description of PHPMailer 6.5.3 library import into Moodle
+Description of PHPMailer 6.6.5 library import into Moodle
 
 We now use a vanilla version of phpmailer and do our customisations in a
 subclass.
 
-For more information on this version of PHPMailer, check out https://github.com/PHPMailer/PHPMailer/releases/tag/v6.5.3
+For more information on this version of PHPMailer, check out https://github.com/PHPMailer/PHPMailer/releases/tag/v6.6.5
 
 To upgrade this library:
 1. Download the latest release of PHPMailer in https://github.com/PHPMailer/PHPMailer/releases.
diff --git a/lib/phpmailer/src/OAuth.php b/lib/phpmailer/src/OAuth.php
index c93d0be1b55..c1d5b77623c 100644
--- a/lib/phpmailer/src/OAuth.php
+++ b/lib/phpmailer/src/OAuth.php
@@ -33,7 +33,7 @@ use League\OAuth2\Client\Token\AccessToken;
  *
  * @author  Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  */
-class OAuth
+class OAuth implements OAuthTokenProvider
 {
     /**
      * An instance of the League OAuth Client Provider.
diff --git a/lib/phpmailer/src/OAuthTokenProvider.php b/lib/phpmailer/src/OAuthTokenProvider.php
new file mode 100644
index 00000000000..1155507435b
--- /dev/null
+++ b/lib/phpmailer/src/OAuthTokenProvider.php
@@ -0,0 +1,44 @@
+<?php
+
+/**
+ * PHPMailer - PHP email creation and transport class.
+ * PHP Version 5.5.
+ *
+ * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
+ *
+ * @author    Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
+ * @author    Jim Jagielski (jimjag) <jimjag@gmail.com>
+ * @author    Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
+ * @author    Brent R. Matzelle (original founder)
+ * @copyright 2012 - 2020 Marcus Bointon
+ * @copyright 2010 - 2012 Jim Jagielski
+ * @copyright 2004 - 2009 Andy Prevost
+ * @license   http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
+ * @note      This program is distributed in the hope that it will be useful - WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+namespace PHPMailer\PHPMailer;
+
+/**
+ * OAuthTokenProvider - OAuth2 token provider interface.
+ * Provides base64 encoded OAuth2 auth strings for SMTP authentication.
+ *
+ * @see     OAuth
+ * @see     SMTP::authenticate()
+ *
+ * @author  Peter Scopes (pdscopes)
+ * @author  Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
+ */
+interface OAuthTokenProvider
+{
+    /**
+     * Generate a base64-encoded OAuth token ensuring that the access token has not expired.
+     * The string to be base 64 encoded should be in the form:
+     * "user=<user_email_address>\001auth=Bearer <access_token>\001\001"
+     *
+     * @return string
+     */
+    public function getOauth64();
+}
diff --git a/lib/phpmailer/src/PHPMailer.php b/lib/phpmailer/src/PHPMailer.php
index 20972c4a4f1..7e6c88ff14e 100644
--- a/lib/phpmailer/src/PHPMailer.php
+++ b/lib/phpmailer/src/PHPMailer.php
@@ -350,17 +350,17 @@ class PHPMailer
     public $Password = '';
 
     /**
-     * SMTP auth type.
-     * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified.
+     * SMTP authentication type. Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2.
+     * If not specified, the first one from that list that the server supports will be selected.
      *
      * @var string
      */
     public $AuthType = '';
 
     /**
-     * An instance of the PHPMailer OAuth class.
+     * An implementation of the PHPMailer OAuthTokenProvider interface.
      *
-     * @var OAuth
+     * @var OAuthTokenProvider
      */
     protected $oauth;
 
@@ -750,7 +750,7 @@ class PHPMailer
      *
      * @var string
      */
-    const VERSION = '6.5.3';
+    const VERSION = '6.6.5';
 
     /**
      * Error severity: message only, continue processing.
@@ -1066,8 +1066,8 @@ class PHPMailer
      * Addresses that have been added already return false, but do not throw exceptions.
      *
      * @param string $kind    One of 'to', 'cc', 'bcc', or 'ReplyTo'
-     * @param string $address The email address to send, resp. to reply to
-     * @param string $name
+     * @param string $address The email address
+     * @param string $name    An optional username associated with the address
      *
      * @throws Exception
      *
@@ -1075,9 +1075,11 @@ class PHPMailer
      */
     protected function addOrEnqueueAnAddress($kind, $address, $name)
     {
-        $address = trim($address);
-        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
-        $pos = strrpos($address, '@');
+        $pos = false;
+        if ($address !== null) {
+            $address = trim($address);
+            $pos = strrpos($address, '@');
+        }
         if (false === $pos) {
             //At-sign is missing.
             $error_message = sprintf(
@@ -1094,8 +1096,14 @@ class PHPMailer
 
             return false;
         }
+        if ($name !== null && is_string($name)) {
+            $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
+        } else {
+            $name = '';
+        }
         $params = [$kind, $address, $name];
         //Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
+        //Domain is assumed to be whatever is after the last @ symbol in the address
         if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) {
             if ('Reply-To' !== $kind) {
                 if (!array_key_exists($address, $this->RecipientsQueue)) {
@@ -1185,6 +1193,7 @@ class PHPMailer
      *
      * @param string $addrstr The address list string
      * @param bool   $useimap Whether to use the IMAP extension to parse the list
+     * @param string $charset The charset to use when decoding the address list string.
      *
      * @return array
      */
@@ -1279,7 +1288,7 @@ class PHPMailer
      */
     public function setFrom($address, $name = '', $auto = true)
     {
-        $address = trim($address);
+        $address = trim((string)$address);
         $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
         //Don't validate now addresses with IDN. Will be done in send().
         $pos = strrpos($address, '@');
@@ -1546,17 +1555,17 @@ class PHPMailer
 
             //Validate From, Sender, and ConfirmReadingTo addresses
             foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
-                $this->$address_kind = trim($this->$address_kind);
-                if (empty($this->$address_kind)) {
+                $this->{$address_kind} = trim($this->{$address_kind});
+                if (empty($this->{$address_kind})) {
                     continue;
                 }
-                $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
-                if (!static::validateAddress($this->$address_kind)) {
+                $this->{$address_kind} = $this->punyencodeAddress($this->{$address_kind});
+                if (!static::validateAddress($this->{$address_kind})) {
                     $error_message = sprintf(
                         '%s (%s): %s',
                         $this->lang('invalid_address'),
                         $address_kind,
-                        $this->$address_kind
+                        $this->{$address_kind}
                     );
                     $this->setError($error_message);
                     $this->edebug($error_message);
@@ -1656,13 +1665,13 @@ class PHPMailer
                 default:
                     $sendMethod = $this->Mailer . 'Send';
                     if (method_exists($this, $sendMethod)) {
-                        return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
+                        return $this->{$sendMethod}($this->MIMEHeader, $this->MIMEBody);
                     }
 
                     return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
             }
         } catch (Exception $exc) {
-            if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true) {
+            if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true && $this->smtp->connected()) {
                 $this->smtp->reset();
             }
             $this->setError($exc->getMessage());
@@ -1742,7 +1751,7 @@ class PHPMailer
                 fwrite($mail, $header);
                 fwrite($mail, $body);
                 $result = pclose($mail);
-                $addrinfo = static::parseAddresses($toAddr, true, $this->charSet);
+                $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet);
                 $this->doCallback(
                     ($result === 0),
                     [[$addrinfo['address'], $addrinfo['name']]],
@@ -1797,7 +1806,13 @@ class PHPMailer
      */
     protected static function isShellSafe($string)
     {
-        //Future-proof
+        //It's not possible to use shell commands safely (which includes the mail() function) without escapeshellarg,
+        //but some hosting providers disable it, creating a security problem that we don't want to have to deal with,
+        //so we don't.
+        if (!function_exists('escapeshellarg') || !function_exists('escapeshellcmd')) {
+            return false;
+        }
+
         if (
             escapeshellcmd($string) !== $string
             || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
@@ -1848,7 +1863,7 @@ class PHPMailer
         if (!static::isPermittedPath($path)) {
             return false;
         }
-        $readable = file_exists($path);
+        $readable = is_file($path);
         //If not a UNC path (expected to start with \\), check read permission, see #2069
         if (strpos($path, '\\\\') !== 0) {
             $readable = $readable && is_readable($path);
@@ -1876,7 +1891,14 @@ class PHPMailer
         foreach ($this->to as $toaddr) {
             $toArr[] = $this->addrFormat($toaddr);
         }
-        $to = implode(', ', $toArr);
+        $to = trim(implode(', ', $toArr));
+
+        //If there are no To-addresses (e.g. when sending only to BCC-addresses)
+        //the following should be added to get a correct DKIM-signature.
+        //Compare with $this->preSend()
+        if ($to === '') {
+            $to = 'undisclosed-recipients:;';
+        }
 
         $params = null;
         //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
@@ -1905,7 +1927,7 @@ class PHPMailer
         if ($this->SingleTo && count($toArr) > 1) {
             foreach ($toArr as $toAddr) {
                 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
-                $addrinfo = static::parseAddresses($toAddr, true, $this->charSet);
+                $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet);
                 $this->doCallback(
                     $result,
                     [[$addrinfo['address'], $addrinfo['name']]],
@@ -2079,6 +2101,9 @@ class PHPMailer
         $this->smtp->setDebugLevel($this->SMTPDebug);
         $this->smtp->setDebugOutput($this->Debugoutput);
         $this->smtp->setVerp($this->do_verp);
+        if ($this->Host === null) {
+            $this->Host = 'localhost';
+        }
         $hosts = explode(';', $this->Host);
         $lastexception = null;
 
@@ -2154,7 +2179,8 @@ class PHPMailer
                     }
                     if ($tls) {
                         if (!$this->smtp->startTLS()) {
-                            throw new Exception($this->lang('connect_host'));
+                            $message = $this->getSmtpErrorMessage('connect_host');
+                            throw new Exception($message);
                         }
                         //We must resend EHLO after TLS negotiation
                         $this->smtp->hello($hello);
@@ -2185,6 +2211,11 @@ class PHPMailer
         if ($this->exceptions && null !== $lastexception) {
             throw $lastexception;
         }
+        if ($this->exceptions) {
+            // no exception was thrown, likely $this->smtp->connect() failed
+            $message = $this->getSmtpErrorMessage('connect_host');
+            throw new Exception($message);
+        }
 
         return false;
     }
@@ -2630,16 +2661,15 @@ class PHPMailer
             $result .= $this->headerLine('X-Priority', $this->Priority);
         }
         if ('' === $this->XMailer) {
+            //Empty string for default X-Mailer header
             $result .= $this->headerLine(
                 'X-Mailer',
                 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
             );
-        } else {
-            $myXmailer = trim($this->XMailer);
-            if ($myXmailer) {
-                $result .= $this->headerLine('X-Mailer', $myXmailer);
-            }
-        }
+        } elseif (is_string($this->XMailer) && trim($this->XMailer) !== '') {
+            //Some string
+            $result .= $this->headerLine('X-Mailer', trim($this->XMailer));
+        } //Other values result in no X-Mailer header
 
         if ('' !== $this->ConfirmReadingTo) {
             $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
@@ -3694,20 +3724,21 @@ class PHPMailer
      * These differ from 'regular' attachments in that they are intended to be
      * displayed inline with the message, not just attached for download.
      * This is used in HTML messages that embed the images
-     * the HTML refers to using the $cid value.
+     * the HTML refers to using the `$cid` value in `img` tags, for example `<img src="cid:mylogo">`.
      * Never use a user-supplied path to a file!
      *
      * @param string $path        Path to the attachment
      * @param string $cid         Content ID of the attachment; Use this to reference
      *                            the content when using an embedded image in HTML
-     * @param string $name        Overrides the attachment name
-     * @param string $encoding    File encoding (see $Encoding)
-     * @param string $type        File MIME type
-     * @param string $disposition Disposition to use
-     *
-     * @throws Exception
+     * @param string $name        Overrides the attachment filename
+     * @param string $encoding    File encoding (see $Encoding) defaults to `base64`
+     * @param string $type        File MIME type (by default mapped from the `$path` filename's extension)
+     * @param string $disposition Disposition to use: `inline` (default) or `attachment`
+     *                            (unlikely you want this – {@see `addAttachment()`} instead)
      *
      * @return bool True on successfully adding an attachment
+     * @throws Exception
+     *
      */
     public function addEmbeddedImage(
         $path,
@@ -4085,12 +4116,8 @@ class PHPMailer
             //Is it a valid IPv4 address?
             return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
         }
-        if (filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false) {
-            //Is it a syntactically valid hostname?
-            return true;
-        }
-
-        return false;
+        //Is it a syntactically valid hostname (when embeded in a URL)?
+        return filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false;
     }
 
     /**
@@ -4121,6 +4148,26 @@ class PHPMailer
         return $key;
     }
 
+    /**
+     * Build an error message starting with a generic one and adding details if possible.
+     *
+     * @param string $base_key
+     * @return string
+     */
+    private function getSmtpErrorMessage($base_key)
+    {
+        $message = $this->lang($base_key);
+        $error = $this->smtp->getError();
+        if (!empty($error['error'])) {
+            $message .= ' ' . $error['error'];
+            if (!empty($error['detail'])) {
+                $message .= ' ' . $error['detail'];
+            }
+        }
+
+        return $message;
+    }
+
     /**
      * Check if an error occurred.
      *
@@ -4433,6 +4480,7 @@ class PHPMailer
             'ics' => 'text/calendar',
             'xml' => 'text/xml',
             'xsl' => 'text/xml',
+            'csv' => 'text/csv',
             'wmv' => 'video/x-ms-wmv',
             'mpeg' => 'video/mpeg',
             'mpe' => 'video/mpeg',
@@ -4540,7 +4588,7 @@ class PHPMailer
     public function set($name, $value = '')
     {
         if (property_exists($this, $name)) {
-            $this->$name = $value;
+            $this->{$name} = $value;
 
             return true;
         }
@@ -5021,9 +5069,9 @@ class PHPMailer
     }
 
     /**
-     * Get the OAuth instance.
+     * Get the OAuthTokenProvider instance.
      *
-     * @return OAuth
+     * @return OAuthTokenProvider
      */
     public function getOAuth()
     {
@@ -5031,9 +5079,9 @@ class PHPMailer
     }
 
     /**
-     * Set an OAuth instance.
+     * Set an OAuthTokenProvider instance.
      */
-    public function setOAuth(OAuth $oauth)
+    public function setOAuth(OAuthTokenProvider $oauth)
     {
         $this->oauth = $oauth;
     }
diff --git a/lib/phpmailer/src/SMTP.php b/lib/phpmailer/src/SMTP.php
index 676dba2923b..312f753cea6 100644
--- a/lib/phpmailer/src/SMTP.php
+++ b/lib/phpmailer/src/SMTP.php
@@ -35,7 +35,7 @@ class SMTP
      *
      * @var string
      */
-    const VERSION = '6.5.3';
+    const VERSION = '6.6.5';
 
     /**
      * SMTP line break constant.
@@ -187,6 +187,7 @@ class SMTP
         'SendGrid' => '/[\d]{3} Ok: queued as (.*)/',
         'CampaignMonitor' => '/[\d]{3} 2.0.0 OK:([a-zA-Z\d]{48})/',
         'Haraka' => '/[\d]{3} Message Queued \((.*)\)/',
+        'Mailjet' => '/[\d]{3} OK queued as (.*)/',
     ];
 
     /**
@@ -482,7 +483,7 @@ class SMTP
      * @param string $username The user name
      * @param string $password The password
      * @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2)
-     * @param OAuth  $OAuth    An optional OAuth instance for XOAUTH2 authentication
+     * @param OAuthTokenProvider $OAuth An optional OAuthTokenProvider instance for XOAUTH2 authentication
      *
      * @return bool True if successfully authenticated
      */
@@ -681,7 +682,6 @@ class SMTP
      */
     public function close()
     {
-        $this->setError('');
         $this->server_caps = null;
         $this->helo_rply = null;
         if (is_resource($this->smtp_conn)) {
@@ -1036,7 +1036,10 @@ class SMTP
             return false;
         }
 
-        $this->setError('');
+        //Don't clear the error store when using keepalive
+        if ($command !== 'RSET') {
+            $this->setError('');
+        }
 
         return true;
     }
diff --git a/lib/thirdpartylibs.xml b/lib/thirdpartylibs.xml
index c87c766eb56..95d59b3abfe 100644
--- a/lib/thirdpartylibs.xml
+++ b/lib/thirdpartylibs.xml
@@ -155,7 +155,7 @@
     <location>phpmailer</location>
     <name>PHPMailer</name>
     <description>Class for sending email using either sendmail, PHP mail(), or SMTP. Methods are based upon the standard AspEmail(tm) classes.</description>
-    <version>6.5.3</version>
+    <version>6.6.5</version>
     <license>LGPL</license>
     <licenseversion>2.1</licenseversion>
     <repository>https://github.com/PHPMailer/PHPMailer</repository>