Comment configurer SMTP par programmation
3 réponses
- votes
-
- 2012-12-13
Tout d'abord,sinousexaminons l'implémentation de lafonction
wp_mail
,nous verrons que cettefonction utilise <PHPMailer
pourenvoyer dese-mails. Nouspourrions également remarquer qu'ilexiste un appel defonction codéen dur$phpmailer->IsMail();
,qui utilise lafonctionmail()
de PHP. Cela signifie quenousne pouvonspas utiliser lesparamètres SMTP avec. Nous devons appeler lafonctionisSMTP
de la classePHPMailer
. Etnous devons également définirnosparamètres SMTP.Pour yparvenir,nous devons avoir accès à la variable
$phpmailer
. Etnous arrivonsici à l'actionphpmailer_init
quiest appelée avant d'envoyer une-mail. Nouspouvons doncfaire ce dontnous avonsbesoinen écrivantnotregestionnaire d'actions:add_action( 'phpmailer_init', 'wpse8170_phpmailer_init' ); function wpse8170_phpmailer_init( PHPMailer $phpmailer ) { $phpmailer->Host = 'your.smtp.server.here'; $phpmailer->Port = 25; // could be different $phpmailer->Username = '[email protected]'; // if required $phpmailer->Password = 'yourpassword'; // if required $phpmailer->SMTPAuth = true; // if required // $phpmailer->SMTPSecure = 'ssl'; // enable if required, 'tls' is another possible value $phpmailer->IsSMTP(); }
Et c'esttout.
First of all, if we take a look at implementation of
wp_mail
function, we will see that this function usesPHPMailer
class to send emails. Also we could notice that there is hard coded function call$phpmailer->IsMail();
, which sets to use PHP'smail()
function. It means that we can't use SMTP settings with it. We need to callisSMTP
function ofPHPMailer
class. And also we need to set our SMTP settings as well.To achieve it we need to get access to
$phpmailer
variable. And here we come tophpmailer_init
action which is called before sending an email. So we can do what we need by writing our action handler:add_action( 'phpmailer_init', 'wpse8170_phpmailer_init' ); function wpse8170_phpmailer_init( PHPMailer $phpmailer ) { $phpmailer->Host = 'your.smtp.server.here'; $phpmailer->Port = 25; // could be different $phpmailer->Username = '[email protected]'; // if required $phpmailer->Password = 'yourpassword'; // if required $phpmailer->SMTPAuth = true; // if required // $phpmailer->SMTPSecure = 'ssl'; // enable if required, 'tls' is another possible value $phpmailer->IsSMTP(); }
And that's all.
-
Beautruc,Eugene,merci!Je suppose que ces 10 lignes de codepeuvent remplacer unplugin SMTPentier ... (?)Nice stuff, Eugene, thx! I guess this 10 lines of code can substitute an entire SMTP plugin...(?)
- 0
- 2012-12-13
- brasofilo
-
@brasofilothx!Jepense qu'ilne peutpas remplacer unplugin SMTP,car leplugin vouspermet de configurer lesparamètres dans lepanneau d'administration.Cetextrait de coden'est que lameilleurepratique sur "commentmodifier lesparamètres demessagerieparprogramme" sans casser lesfichiersprincipaux ou sans réécrire lafonction `wp_mail`.@brasofilo thx! I think it can't substitute a SMTP plugin, because the plugin allows you to configure settings at admin panel. This snippet is just best practice about "how to change email settings programmatically" without breaking core files or without rewriting `wp_mail` function.
- 0
- 2012-12-13
- Eugene Manuilov
-
Peut-être un [lien vers lenoyau] (http://core.trac.wordpress.org/browser/tags/3.5/wp-includes/class-phpmailer.php)?Nous venons detrouver quenous devons utiliser cecipour SSL: `$phpmailer-> SMTPSecure='ssl';`,ou `'tls'` si c'est le cas.::: * Encore unefois:,* ** supertruc! **Maybe a [link to the core](http://core.trac.wordpress.org/browser/tags/3.5/wp-includes/class-phpmailer.php)? Just found that we need to use this for SSL: `$phpmailer->SMTPSecure = 'ssl';`, or `'tls'` if that's the case. ::: *Again:,* **great stuff!**
- 0
- 2013-01-15
- brasofilo
-
@brasofilo oui,d'accord.N'hésitezpas àmodifier la réponse si vous le souhaitez.Mercipour l'aide.@brasofilo yes, agree. Feel free to edit the answer if you want. Thanks for help.
- 0
- 2013-01-15
- Eugene Manuilov
-
Où ce code doit-il êtreplacé?Je souhaite quetousmesthèmes utilisent lesmêmes serveurs SMTP.Where should this code be placed? I want to make all my themes use the same SMTP servers.
- 2
- 2014-01-10
- Anjan
-
@Anjan crée votre [propreplugin] (http://codex.wordpress.org/Writing_a_Plugin).@Anjan create your [own plugin](http://codex.wordpress.org/Writing_a_Plugin).
- 0
- 2014-01-10
- Eugene Manuilov
-
WPtrès étrangene rendpas celaplusfacile car onpourraitpenser qu'il serait courant demodifier cela.Very strange WP does not make this easier as you would think it would be a common to modify this.
- 1
- 2015-04-30
- Carson Reinke
-
Celane sembleplusfonctionner.This doesn't seems to work anymore.
- 0
- 2015-11-02
- Etienne Dupuis
-
Quelqu'unpeut-il confirmer que celafonctionnetoujours?Can anyone confirm this still works?
- 0
- 2015-11-09
- Jack
-
celafonctionnepourmoi,@JackNicholson vous devriez le vérifier de votre côté aussi.it works for me, @JackNicholson you should check it on your end too.
- 1
- 2015-11-09
- Eugene Manuilov
-
J'ai utilisé ce codemais wordpressenvoie viaphpmail () commentforcer wordpress àenvoyer uniquement SMTP? Quandj'utilise wp_mail ("[email protected]","test","test"); ilne l'envoiepas via SMTPI used this code but wordpress sends via php mail() how to force wordpress to send just SMTP? When I use wp_mail("[email protected]", "test", "test"); it doesn't send it via SMTP
- 0
- 2017-01-27
- Hossein Hashemi
-
- 2013-06-22
Ajout à la réponse @EugeneManuilov.
Paramètres SMTP
Par défaut,ceux-cine peuvent obtenir - comme @EugeneManuilov déjà répondu - être définispar lors d'un rappel attaché à un
do_action_ref_array()
. Source/core .<?php defined( 'ABSPATH' ) OR exit; /** * Plugin Name: (WCM) PHPMailer SMTP Settings * Description: Enables SMTP servers, SSL/TSL authentication and SMTP settings. */ add_action( 'phpmailer_init', 'phpmailerSMTP' ); function phpmailerSMTP( $phpmailer ) { # $phpmailer->IsSMTP(); # $phpmailer->SMTPAuth = true; // Authentication # $phpmailer->Host = ''; # $phpmailer->Username = ''; # $phpmailer->Password = ''; # $phpmailer->SMTPSecure = 'ssl'; // Enable if required - 'tls' is another possible value # $phpmailer->Port = 26; // SMTP Port - 26 is for GMail }
Exceptions SMTP
Par défaut,WordPressne vous donne aucune sortie de débogage. Au lieu de cela,il renvoie simplement
FALSE
si uneerreur s'estproduite. Voici unpetit pluginpour résoudre ceproblème:<?php defined( 'ABSPATH' ) OR exit; /** * Plugin Name: (WCM) PHPMailer Exceptions & SMTP * Description: WordPress by default returns <code>FALSE</code> instead of an <code>Exception</code>. This plugin fixes that. */ add_action( 'phpmailer_init', 'WCMphpmailerException' ); function WCMphpmailerException( $phpmailer ) { if ( ! defined( 'WP_DEBUG' ) OR ! WP_DEBUG ) { $phpmailer->SMTPDebug = 0; $phpmailer->debug = 0; return; } if ( ! current_user_can( 'manage_options' ) ) return; // Enable SMTP # $phpmailer->IsSMTP(); $phpmailer->SMTPDebug = 2; $phpmailer->debug = 1; // Use `var_dump( $data )` to inspect stuff at the latest point and see // if something got changed in core. You should consider dumping it during the // `wp_mail` filter as well, so you get the original state for comparison. $data = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ); current_user_can( 'manage_options' ) AND print htmlspecialchars( var_export( $phpmailer, true ) ); $error = null; try { $sent = $phpmailer->Send(); ! $sent AND $error = new WP_Error( 'phpmailerError', $sent->ErrorInfo ); } catch ( phpmailerException $e ) { $error = new WP_Error( 'phpmailerException', $e->errorMessage() ); } catch ( Exception $e ) { $error = new WP_Error( 'defaultException', $e->getMessage() ); } if ( is_wp_error( $error ) ) return printf( "%s: %s", $error->get_error_code(), $error->get_error_message() ); }
Référentiel
Lesplugins sonttous deux disponibles dans ce Gist sur GitHub ,alorspensez à vérifier cesplugins àpartir de làpour récupérer lesmises àjour.
Addition to @EugeneManuilov answer.
SMTP settings
By default those can only get - as @EugeneManuilov already answered - be set by during a callback attached to an
do_action_ref_array()
. Source/core.<?php defined( 'ABSPATH' ) OR exit; /** * Plugin Name: (WCM) PHPMailer SMTP Settings * Description: Enables SMTP servers, SSL/TSL authentication and SMTP settings. */ add_action( 'phpmailer_init', 'phpmailerSMTP' ); function phpmailerSMTP( $phpmailer ) { # $phpmailer->IsSMTP(); # $phpmailer->SMTPAuth = true; // Authentication # $phpmailer->Host = ''; # $phpmailer->Username = ''; # $phpmailer->Password = ''; # $phpmailer->SMTPSecure = 'ssl'; // Enable if required - 'tls' is another possible value # $phpmailer->Port = 26; // SMTP Port - 26 is for GMail }
SMTP Exceptions
Per default WordPress doesn't give you any debug output. Instead it just returns
FALSE
if an error occurred. Here's small plugin to fix this:<?php defined( 'ABSPATH' ) OR exit; /** * Plugin Name: (WCM) PHPMailer Exceptions & SMTP * Description: WordPress by default returns <code>FALSE</code> instead of an <code>Exception</code>. This plugin fixes that. */ add_action( 'phpmailer_init', 'WCMphpmailerException' ); function WCMphpmailerException( $phpmailer ) { if ( ! defined( 'WP_DEBUG' ) OR ! WP_DEBUG ) { $phpmailer->SMTPDebug = 0; $phpmailer->debug = 0; return; } if ( ! current_user_can( 'manage_options' ) ) return; // Enable SMTP # $phpmailer->IsSMTP(); $phpmailer->SMTPDebug = 2; $phpmailer->debug = 1; // Use `var_dump( $data )` to inspect stuff at the latest point and see // if something got changed in core. You should consider dumping it during the // `wp_mail` filter as well, so you get the original state for comparison. $data = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ); current_user_can( 'manage_options' ) AND print htmlspecialchars( var_export( $phpmailer, true ) ); $error = null; try { $sent = $phpmailer->Send(); ! $sent AND $error = new WP_Error( 'phpmailerError', $sent->ErrorInfo ); } catch ( phpmailerException $e ) { $error = new WP_Error( 'phpmailerException', $e->errorMessage() ); } catch ( Exception $e ) { $error = new WP_Error( 'defaultException', $e->getMessage() ); } if ( is_wp_error( $error ) ) return printf( "%s: %s", $error->get_error_code(), $error->get_error_message() ); }
Repository
The plugins are both available in this Gist on GitHub, so consider checking those plugins out from there to grab any updates.
-
- 2017-08-10
Les autres réponses à cet article,touten fournissant une solutionfonctionnelle,n'abordentpas leproblème de sécurité du stockage de vosinformations d'identification SMTP dans unfichierplugin oufunctions.php. Dans certains cas,celapeut être acceptable,mais lesmeilleurespratiquesimposent de stocker cesinformations demanièreplus sécurisée. Iln'y a vraiment aucunebonne raison dene pas suivre lesmeilleurespratiquesen matière deprotection de vosidentifiants.
Certains suggéreraient de l'enregistrer dans labase de donnéesen option,maisprésentent également lesmêmesproblèmes de sécuritéen fonction dunombre d'utilisateurs administratifs de votre siteet de lapossibilitépour ces utilisateurs de voir cesinformations de connexion. C'est aussi lamême raisonpourne pas utiliser depluginpour cela.
Lameilleurefaçon defaireest de définir des constantespour lesinformationsphpmailer dans votrefichier wp-config.php. Cela aen fait été discutéen tant quefonctionnalité dans le composant demessagerie ,maisn'apas été acceptée comme une amélioration réellepour lemoment. Mais vouspouvez lefaire vous-mêmeen ajoutant ce qui suit à wp-config.php:
/** * Set the following constants in wp-config.php * These should be added somewhere BEFORE the * constant ABSPATH is defined. */ define( 'SMTP_USER', '[email protected]' ); // Username to use for SMTP authentication define( 'SMTP_PASS', 'smtp password' ); // Password to use for SMTP authentication define( 'SMTP_HOST', 'smtp.example.com' ); // The hostname of the mail server define( 'SMTP_FROM', '[email protected]' ); // SMTP From email address define( 'SMTP_NAME', 'e.g Website Name' ); // SMTP From name define( 'SMTP_PORT', '25' ); // SMTP port number - likely to be 25, 465 or 587 define( 'SMTP_SECURE', 'tls' ); // Encryption system to use - ssl or tls define( 'SMTP_AUTH', true ); // Use SMTP authentication (true|false) define( 'SMTP_DEBUG', 0 ); // for debugging purposes only set to 1 or 2
Unefois qu'ils sont définis dans wp-config.php,ilspeuvent être utilisésn'importe oùen utilisant la constante définie. Vouspouvez donc les utiliser dans unfichierplugin ou dans votrefunctions.php. (Spécifique à l'OP,utilisez unfichierplugin.)
/** * This function will connect wp_mail to your authenticated * SMTP server. Values are constants set in wp-config.php */ add_action( 'phpmailer_init', 'send_smtp_email' ); function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = SMTP_HOST; $phpmailer->SMTPAuth = SMTP_AUTH; $phpmailer->Port = SMTP_PORT; $phpmailer->Username = SMTP_USER; $phpmailer->Password = SMTP_PASS; $phpmailer->SMTPSecure = SMTP_SECURE; $phpmailer->From = SMTP_FROM; $phpmailer->FromName = SMTP_NAME; }
Il y a unpeuplus de détails sur ce dans cet article et l'essentiel surgithubici .
The other answers to this post, while providing a working solution, don't address the security issue of storing your SMTP credentials in a plugin file or functions.php. In some cases that may be OK, but best practices would dictate storing this information in a more secure fashion. There's really not a good reason to not follow best practices when it comes to protecting your credentials.
Some would suggest saving it to the DB as an option, but also provides the same security issues depending on the number of administrative users your site has and whether those users should be able to see these login credentials. This is also the same reason to not use a plugin for this.
The best way to do this is to define constants for the phpmailer info in your wp-config.php file. This actually has been discussed as a feature in the Mail Component, but hasn't been accepted as an actual enhancement at this time. But you can do it yourself by adding the following to wp-config.php:
/** * Set the following constants in wp-config.php * These should be added somewhere BEFORE the * constant ABSPATH is defined. */ define( 'SMTP_USER', '[email protected]' ); // Username to use for SMTP authentication define( 'SMTP_PASS', 'smtp password' ); // Password to use for SMTP authentication define( 'SMTP_HOST', 'smtp.example.com' ); // The hostname of the mail server define( 'SMTP_FROM', '[email protected]' ); // SMTP From email address define( 'SMTP_NAME', 'e.g Website Name' ); // SMTP From name define( 'SMTP_PORT', '25' ); // SMTP port number - likely to be 25, 465 or 587 define( 'SMTP_SECURE', 'tls' ); // Encryption system to use - ssl or tls define( 'SMTP_AUTH', true ); // Use SMTP authentication (true|false) define( 'SMTP_DEBUG', 0 ); // for debugging purposes only set to 1 or 2
Once these are defined in wp-config.php, they can be used anywhere by using the defined constant. So you could use those in a plugin file or in your functions.php. (Specific to the OP, use a plugin file.)
/** * This function will connect wp_mail to your authenticated * SMTP server. Values are constants set in wp-config.php */ add_action( 'phpmailer_init', 'send_smtp_email' ); function send_smtp_email( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = SMTP_HOST; $phpmailer->SMTPAuth = SMTP_AUTH; $phpmailer->Port = SMTP_PORT; $phpmailer->Username = SMTP_USER; $phpmailer->Password = SMTP_PASS; $phpmailer->SMTPSecure = SMTP_SECURE; $phpmailer->From = SMTP_FROM; $phpmailer->FromName = SMTP_NAME; }
There is a little more detail on this in this post and a gist on github here.
-
Unetrèsbonne solution!A really good solution!
- 0
- 2017-09-08
- Phill Healey
-
Petit ajout:il va sans dire quene stockezpas lesinformations d'identification dans le contrôle de version.Utilisezplutôt lefichiergitignored `.env`.Maispersonne quimet quelque chose de sensible dans `wp-config.php`n'utilise le contrôle de version,detoutefaçon ...Small addition: Needless to say, don't store credentials in version control. Use gitignored `.env` file instead. But nobody who puts anything sensitive into `wp-config.php` is using version control, anyway…
- 1
- 2018-08-29
- jsphpl
Supposons quenous ayons un site WP viergeet quenous souhaitons configurer lesparamètres SMTPparprogrammation dansnotreplugin outhème.Quelleest lafaçon laplus simple de lefaire sansmodifier lesfichiersprincipaux?