php-swiftmailerHow to log emails sent with Swiftmailer?
Swiftmailer is a popular library for sending emails in PHP. To log emails sent with Swiftmailer, you can use the Swift_Plugins_LoggerPlugin
class. This class implements the Swift_Events_EventListener
interface and allows you to log all emails sent with Swiftmailer.
Example code
<?php
// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.example.org', 25))
->setUsername('your username')
->setPassword('your password')
;
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// Create a logger
$logger = new Swift_Plugins_LoggerPlugin(
new Swift_Plugins_Loggers_ArrayLogger()
);
// Register the logger
$mailer->registerPlugin($logger);
// Create a message
$message = (new Swift_Message('Wonderful Subject'))
->setFrom(['[email protected]' => 'John Doe'])
->setTo(['[email protected]', '[email protected]' => 'A name'])
->setBody('Here is the message itself')
;
// Send the message
$result = $mailer->send($message);
// Dump the log contents
echo $logger->dump();
Output example
== START LOGGING ==
Sending message to: [email protected]
Sending message to: [email protected]
Sent 1 messages
== END LOGGING ==
Code explanation
- Create the Transport: This creates the transport layer for sending emails.
- Create the Mailer: This creates the mailer object using the transport layer.
- Create a logger: This creates a logger object for logging emails sent with Swiftmailer.
- Register the logger: This registers the logger with the mailer object.
- Create a message: This creates a message object with the necessary details.
- Send the message: This sends the message using the mailer object.
- Dump the log contents: This dumps the log contents to the screen.
Helpful links
More of Php Swiftmailer
- How to set timeout with Swiftmailer?
- How to use SMTP with Swiftmailer?
- How to use TLS 1.2 with Swiftmailer?
- How to get the response code when using Swiftmailer?
- How to use Swiftmailer to send RFC 2822 compliant emails?
- How to configure Swiftmailer for Postfix?
- How to send emails in UTF8 using Swiftmailer?
- How to send emails to multiple recipients with Swiftmailer?
- How to set the port for Swiftmailer?
- How to enable TLS with Swiftmailer?
See more codes...