Search code examples
phpphpmailer

Instancing PhpMailer


I was looking for functions to send email messages, and decided to use PhpMailer, as it's quite simple to use. But i got this question about it (and wasn't been able to resolve it reading manuals) - is PhpMailer should be instanced like PDO, representing one general handler, or one instance represents one email message?


Solution

  • I found PHPMailer a bit confusing in that regard too, as you can configure things like SMTP (which is more of a transport matter), but also the message itself. So PHPMailer has two concerns to manage: the message and how to send it.

    That said: I would indeed use a new instance of PHPMailer for each message but have a factory create it to take care of the transport (e.g. SMTP) and/ or things that might not change like the sender of the message.

    (That way you can send different messages with the same configuration for transport and sender. Another benefit of this approach is: you can change the transport for the entire site in one location: the factory.)