Développement web indépendant à Montpellier

Publié le jeudi 16 février 2012 08:59:22

Symfony2 : SMTP et SwiftMailer

L'envoi de mail est bien souvent nécessaire à la majorité des applications web, cependant, on peut vouloir envoyer des mails à la volée avec des paramètres différents selon la nature du message.

Pré-requis

Il ne faut pas oublier d'activer le bundle livré avec symfony, SwiftMailer dans appKernel.php

public function registerBundles()
{
    $bundles = array(
        new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
    );
}

L'envoi de mail classique

Ce type d'envoi est bien expliqué dans le cookbook symfony2 ( http://symfony.com/doc/2.0/cookbook/email/email.html ), Dans le fichier config.yml, on définit les paramètres par défaut :

# app/config/config.yml
swiftmailer:
    transport:  smtp
    encryption: ssl # ssl, tls
    auth_mode:  login # login, plain ou cram-md5
    host:       smtp.ligams.com
    username:   your_username
    password:   your_password

Pour utiliser cette configuration par défaut et envoyer un email, il suffit d'instancier un objet Swift_Message que l'on enverra avec le service mailer :

namespace Newsfree\EmailBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class FooController extends Controller 
{
    public function indexAction(){
        $message = \Swift_Message::newInstance();
        $message->setSubject("Objet");
        $message->setFrom('ligamsATligams.com');
        $message->setTo('destinataire@domaine.com');
        // pour envoyer le message en HTML
        $message->setBody('Hello world');
        // pour envoyer le message en HTML
        $message->setBody('<p>Hello world</p>','text/html'); 
        //envoi du message
         $this->get('mailer')->send($message);
     }
}

Ainsi, vous utilisez les paramètres par défaut.

Modifier les paramètres d'envoi de mail à la volée

Vous ne pouvez peut être pas utiliser ces paramètres d'envoi systématiquement : vous devez alors changer créer de nouveaux paramètres à la volée : attention, si vous ne passez pas de 3e paramètres (ou null) en instanciant Swift_SmtpTransport, les méthodes setUsername et setPassword seront indéfinies (undefined method setUsernam) car aucune authentification n'est prévue :

namespace Newsfree\EmailBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class FooController extends Controller 
{
    public function indexAction(){
        //création d'un objet transport
        $transport = \Swift_SmtpTransport::newInstance('smtp.ligams.com', 25, 'ssl' )
                        ->setUsername('username')
                        ->setPassword('password');
        //création d'un objet mailer
        $mailer = \Swift_Mailer::newInstance($transport);
        $message = \Swift_Message::newInstance();
        $message->setSubject("Objet");
        $message->setFrom('ligamsATligams.com');
        $message->setTo('destinataire@domaine.com');
        // pour envoyer le message en HTML
        $message->setBody('Hello world');
        // pour envoyer le message en HTML
        $message->setBody('<p>Hello world</p>','text/html'); 
        //envoi du message
        $mailer->send($message);
     }
}

Envoi de mails en masse et personnalisation

C'est bien joli tout ça, mais dans un monde réel, on a besoin de personnaliser les messages et d'envoyer en masse ( bulk mails ), c'est pourquoi je vais aborder l'utilisation des plugins pour SwiftMailer suivants que je trouve particulièrement utiles :

  • Swift_Plugins_DecoratorPlugin : Decorator va servir à personnaliser chaque message que vous allez envoyer dans une boucle, en remplaçant des tags que vous allez définir par des valeurs propres à chaque mails (en général, nom, prénom, identifiant quelconque...)
  • Swift_Plugins_AntiFloodPlugin : comme son nom l'indique... les serveurs smtp se protègent souvent contre l'envoi massif, le plugin antiflood permet d'atténuer volontairement les envois afin de ne pas offenser les serveurs smtp.
  • Swift_Plugins_ThrottlerPlugin : Un petit peu comme antiflood, il permet par exemple de définir un maximum d'envoi par minute, et un maximum de transit par minute.

Utilisons les 3 à la fois dans un exemple, imaginons un tableau $users comparable au résultat d'un findAll() avec fos_user :

<?php
namespace Newsfree\EmailBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class FooController extends Controller 
{
    public function indexAction(){
        //...
        //création d'un objet transport
        $transport = \Swift_SmtpTransport::newInstance('smtp.ligams.com', 25, 'ssl' )
                        ->setUsername('username')
                        ->setPassword('password');
        //création d'un objet mailer
        $mailer = \Swift_Mailer::newInstance($transport);
        
        /**
         * Création des objets de plugin
         */
        //maximum 1000 mails par minute
        $throttle = new \Swift_Plugins_ThrottlerPlugin(1000, \Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE);
        //maximum 30 mégas de mails par minute
        $throttle2 = new \Swift_Plugins_ThrottlerPlugin(1024*1024*30, \Swift_Plugins_ThrottlerPlugin::BYTES_PER_MINUTE);
        // une seconde de pause tous les 100 mails
        $antiflood = new \Swift_Plugins_AntiFloodPlugin(100,1); 

        foreach($users as $user)
        {
            $decoratorReplacement[$user->email] = array(
               '#email#' => $user->email,
               '#nom#'   => $user->nom,
               '#prenom#'=> $user->prenom,
           );
            
        }
        
        $decorator = new \Swift_Plugins_DecoratorPlugin($decoratorReplacement);
        //on enregistre les plugins
        $mailer->registerPlugin($antiflood);
        $mailer->registerPlugin($throttle);
        $mailer->registerPlugin($throttle2);
        $mailer->registerPlugin($decorator);
        
        $message = \Swift_Message::newInstance();
        $message->setSubject("Objet : #nom# #prenom#");
        $message->setFrom('ligamsATligams.com');
        $message->setBody('<p>Hello #nom# #prenom# #email#</p>','text/html'); 
        foreach($users as $user){
            $message->setTo($user->email);
            if(!$mailer->send($message)){
              //erreur d'envoi
           }
        }
     }
}

Voilà, ça couvre à peu près tous les besoins, pour l'envoi de masse, il est possible d'utiliser un spooler de mail livré avec symfony2, ou de créer une commande (php app/console ...), il reste malvenu de placer des envois d'email de masse (newsletter) dans un contrôleur.

Articles connexes

Notez cet article !

  • Actuellement 4 sur 5 étoiles
  • 1
  • 2
  • 3
  • 4
  • 5

Note : 4/5 (10 notes attribuées)

Merci d'avoir participé !

Vous avez déjà noté cette page, vous ne pouvez la noter qu'une fois !

Votre note a été changée, merci de votre participation !

Bonne résolution ! j'arrête d'alourdir mes pages avec des boutons de partage, mais vous pouvez continuer de partager :-)

Commentaires

  1. ravi | whirlpool service center |

    thanks for sharing this post
    https:/...e.website/

  2. Hema | Whirlpool Home Appliance Service Center in Hyderabad |

    Nice Post.
    Thank you for sharing.
    https:/...ite123.me/

  3. Hema | Samsung Home Appliance Service Center in Hyderabad |

    Nice Post.
    Thank you for sharing.
    https:/...ite123.me/

  4. ravi | whirlpool home appliances service center in hyderabad |

    thanks for sharing this post
    https:/...bself.net/

  5. Hemanth | Whirlpool Home appliances Service center in Hyderabad |

    Great post. Thanks for sharing...

  6. Hema | LG Home Appliance Service Center in Hyderabad |

    Nice Post.
    Thank you for sharing.
    https:/...ite123.me/

  7. This is what I want to find. Thank you so much!
    http://...login.com/

  8. ravi | Kenstar Ac Service Center In Hyderabad |

    Thanks for sharing this post
    <a href=”http://...hyderabad/ “>kenstar ac service center in hyderabad

  9. ravi | Whirlpool Ac Service Center In Hyderabad |

    thanks for sharing this post
    <ahref="http://...hyderabad/ ">whirlpool ac service center in hyderabad</a>

  10. Your work is very good and I appreciate you and hopping for some more informative posts. Thank you for sharing great information to us.
    http://...iday-mean/

  11. ravi | Haer Refrigerator Service Center in hyderabad |

    thanks for sharing this post
    <a href=”http://...hyderabad/ “>haier refrigerator service center in hyderabad</a>

  12. Hema | Electrolux Refrigerator Service Center in Hyderabad |

    Nice Article.
    Thank you for sharing.
    http://...hyderabad/

  13. ravi | Godrej Microwave oven Service Center In Hyderabad |

    thanks for sharing this post
    <a href=” http://...hyderabad/“>godrej microwave oven service center in hyderabad</a>

  14. Hema | LG Microwave Oven Service Center in Hyderabad |

    Nice Article.
    Thank you for sharing.
    http://...hyderabad/

  15. Hemanth | Samsung Refrigerator Service center in hyderabad |

    Nice post...

  16. Hema | Godrej Washing Machine Service Center in Hyderabad |

    Nice Article.
    Thank you for sharing.
    http://...hyderabad/

  17. I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy.
    http://...-craft.com

  18. I am happy to find this post very useful for me. as it contains lot of information. I always prefer to read the quality content and this thing I found in you post.

  19. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.
    http://...from-home/

  20. Thank you for taking the time to publish this information very useful!
    http://...pecial.com

  21. Meilleur offre Abonnement iptv sur mega-iptv.com

  22. lesa.prom... | strategic management assignment help |

    Thank you for the wonderful blog post. The strategic management assignment help expert is really happy to find this blog.

  23. lesa.prom... | chemistry assignment help |

    Thank you for the fantastic blog. I am really pleased to see this content. As chemistry assignment help expert, i am excited to see this blog.

  24. Installation/Un-Installation of Webroot antivirus
    Re-installation of Webroot antivirus
    Upgradation of Webroot antivirus
    Activation of Webroot Antivirus product
    Repair of Webroot antivirus
    All kinds of software installations and programme updates
    Maintenance checks for all computers
    Compatibility checks with various software and programmes
    Reinstallation or update of your operating system
    Verification of protection and security
    Computer scans for the threats to analyse the virus infections
    Configure Webroot antivirus settings as per system requirements
    Security settings for complete protection

  25. Webroot Antivirus Installation Guide
    Antivirus and cyber security products from this brand are easy to use and install and can be done in a simple manner by following a few steps. The security package offered by this brand is incredibly easy to setup and install. You can easily install and upgrade any of the Webroot SecureAnywhere Antivirus products that help you handle cyber security in the best possible manner.

    Here is how you can do it in three simple steps:

    1. Start with setup and install at webroot.com/safe by downloading the software that you can do without a CD or DVD. All you need is a good internet connection for the purpose.

    2. You will find a 20 character alpha-numeric code (xxxx-xxxx-xxxx-xxxx) which is your product key. If you buy retail card, you will find this unique code on the backside of the card that you need to enter.

    3. Install Webroot with this Product Key by entering this unique product key to complete the installation process and clicking on the ‘Submit’ button.

    With the Webroot.com/Setup Product Key, you can complete the installation process all by yourself. Here are a few troubleshooting tips for a smooth Webroot installation.

    If the automatic download fails, you can call the helpline for assistance. Slow internet connections can lead to problems in downloading.

    If you already have an anti-virus installed on your device, you will have to uninstall that first and remove it completely from your system.

    Ensure that the latest updates are installed on your operating system so that it is compatible with the Webroot antivirus.

  26. Webroot Antivirus Installation Guide
    Antivirus and cyber security products from this brand are easy to use and install and can be done in a simple manner by following a few steps. The security package offered by this brand is incredibly easy to setup and install. You can easily install and upgrade any of the Webroot SecureAnywhere Antivirus products that help you handle cyber security in the best possible manner.

    Here is how you can do it in three simple steps:

    1. Start with setup and install at webroot.com/safe by downloading the software that you can do without a CD or DVD. All you need is a good internet connection for the purpose.

    2. You will find a 20 character alpha-numeric code (xxxx-xxxx-xxxx-xxxx) which is your product key. If you buy retail card, you will find this unique code on the backside of the card that you need to enter.

    3. Install Webroot with this Product Key by entering this unique product key to complete the installation process and clicking on the ‘Submit’ button.

    With the Webroot.com/Setup Product Key, you can complete the installation process all by yourself. Here are a few troubleshooting tips for a smooth Webroot installation.

    If the automatic download fails, you can call the helpline for assistance. Slow internet connections can lead to problems in downloading.

    If you already have an anti-virus installed on your device, you will have to uninstall that first and remove it completely from your system.

    Ensure that the latest updates are installed on your operating system so that it is compatible with the Webroot antivirus.

  27. Visit www.norton.com/setup for setup, download, reinstall, enter and activate your norton product key to setup your account.Step-by-Step guide for Norton setup key, Download &amp; installation from norton.com/setup website.

  28. welcome to avg.com/retail website With the development of the digital world, online protection is crucial. It is extremely important to protect your PCs, Mac, computers as well as mobile devices and tablets with avg.com/retail. This can be done with the help of effective internet security and anti-virus products from avg.com/retail that safeguards all devices used on digital platforms.

  29. xmodgames is an application to download http://...esios.com/ the number of games and create their mods

  30. Rooting gives you the root access to your android phone. We are drafting this post about Root Genius apk.
    http://...usapp.com/

  31. You will certainly discover a pop up box on your left. Select the alternative Enroll for Online Access. You will certainly be guided to a brand-new web page

  32. Generate Unlimited Resources with Our Newly Released Online Resources Generator Tool its 100% Working and also Free Tool, This is one of the best method.You should try this!. Enjoy it!

    https:/...mor-blitz/

  33. The efficiency relatively much better compared to expected player not sustaining most recent updated version leapdroid emulator readily available in both version.

  34. All the blog works are astonishing. The more I read, the more fall under the spell of them.

  35. Android tools to get some actual as well as spam totally free sort on your Facebook blog posts. Are you a follower of using.

  36. qwertyu | qwerty |

    This is very informative post
    https:/...ndeonline/
    https:/...astonline/
    https:/...alchapter/
    http://...rd-online/
    https:/...valonline/
    http://...ts-online/
    http://...ll-online/
    https:/...seaonline/
    http://...my-online/
    https:/...ingonline/
    http://...ie-online/
    http://...me-online/
    http://...ng-online/
    https:/...essonline/
    http://...ip-online/
    http://...ty-online/
    https:/...aribbean5/
    https:/...tchonline/
    http://...le-online/
    https:/...ifeonline/
    https:/...hegalaxy2/
    http://...nd-online/
    http://...nd-online/
    http://...-3-online/
    http://...rs-online/
    https:/...oldonline/
    http://...ge-online/
    http://...er-online/
    https:/...ftimewalk/
    https:/...ersonline/
    http://...nt-online/
    https:/...fthesword/
    https:/...ofindthem/
    https:/...eenonline/
    https:/...cleonline/
    https:/...deronline/
    http://...ch-online/
    http://...it-online/
    https:/...veronline/
    http://...ht-online/
    http://...ht-online/
    http://...es-online/
    https:/...manonline/
    https:/...ireonline/
    http://...er-online/
    http://...ge-online/
    https:/...me3online/
    https:/...ganonline/
    http://...ge-online/
    http://...by-online/
    http://...ht-online/
    http://...ck-online/
    http://...us-online/
    http://...rk-online/
    https:/...nmeonline/
    https:/...antonline/
    https:/...oneonline/
    http://...er-online/
    https:/...vergoback/
    https:/...utyonline/
    http://...er-online/
    https:/...andercage/
    http://...ls-online/
    https:/...anaonline/
    https:/...rs5online/
    https:/...ndplanets/
    http://...ll-online/
    https:/...andonline/
    https:/...rnoonline/
    https:/...ingonline/
    http://...ea-online/
    https:/...abyonline/
    http://...ne-online/
    https:/...riponline/
    https:/...andonline/
    https:/...oseonline/
    https:/...vieonline/
    http://...se-online/
    https:/...arsonline/
    http://...ed-online/
    http://...ck-online/
    http://...-2-online/
    https:/...nusonline/
    https:/...domonline/
    https:/...llsonline/
    http://...ld-online/
    http://...ls-online/
    https:/...allonline/
    https:/...llsonline/
    https:/...litonline/
    http://...an-online/
    https:/...ghtonline/
    http://...om-online/
    https:/...keronline/
    http://...us-online/
    http://...lk-online/
    https:/...vieonline/
    http://...rs-online/
    https:/...oftheapes/
    https:/...ngeonline/
    https:/...irkonline/
    http://...no-online/
    https:/...mmyonline/
    http://...ed-online/
    https:/...rs3online/
    http://...nt-online/
    http://...al-online/
    http://...em-online/
    https:/...ersonline/
    http://...ie-online/
    http://...fe-online/
    http://...an-online/
    http://...re-online/
    http://...ss-online/
    https:/...tedonline/
    https:/...stvillage/
    http://...-3-online/
    https:/...ackonline/
    http://...en-online/
    https:/...eedonline/
    http://...st-online/
    http://...na-online/
    https:/...er2online/
    https:/...ellonline/
    https:/...ousonline/
    http://...de-online/
    https:/...antonline/
    http://...rs-online/
    https:/...ntsonline/
    http://...-2-online/
    http://...es-online/
    http://...ng-online/
    https:/...ghtonline/
    http://...ts-online/
    This article is really good

  37. Whatsapp... | Whatsapp for samsung galaxy |

    we can have it active only on your cell phone and have the WhatsApp active on your phone to keep it affiliated

  38. Welcome to QuickBooks Support. Which version of QuickBooks are you using? ... QuickBooks Desktop Pro, QuickBooks Desktop Premier, QuickBooks Desktop ...

  39. I was thinking that same thing

  40. I just might use this

  41. Merci pour ces informations

  42. Pretty instructive....look ahead to coming back again.

    http://...eview.org/

    http://...nline.com/

    http://...umbai.com/

  43. Mail transfer protocol and swift mailer are always helping the web designing part. They will get the good features to improve the ability for making their work in a proper channel. This will help to improve the communication part also.

  44. Bonjour,

    L'environnement ou est hébergé votre application ne change pas grand chose dans votre cas. Pour se logguer à votre application symphony, vous faites sans doute appel à un controleur de cette même appli, si l'authentification est un succès, envoyez un mail, c'est tout ;)

  45. Bonjour a tous
    Mon application symfony2 est sur debian
    Mes utilisateurs s'y Logge a travers AD server 2003

    Voila mon problème :
    Dans l'application quand l'utilisateur valide un formulaire, je veux qu'un mail lui soit automatiquement envoyé par l'application.

    Quelqu'un peut m'aider sur ce cas

    Merci à vous!