9951 explained code solutions for 126 technologies


php-swiftmailerHow to check if an email was sent using Swiftmailer?


Swiftmailer provides a way to check if an email was sent using its send() method. The send() method returns a Swift_Message object which contains a getId() method that can be used to check if the email was sent.

Example code

$message = Swift_Message::newInstance()
    ->setSubject('Test Email')
    ->setFrom('[email protected]')
    ->setTo('[email protected]')
    ->setBody('This is a test email.');

$sent = $mailer->send($message);

if ($sent) {
    echo $message->getId();
}

Output example

<[email protected]>

Code explanation

  • Swift_Message::newInstance(): creates a new instance of the Swift_Message class.
  • setSubject(): sets the subject of the email.
  • setFrom(): sets the sender of the email.
  • setTo(): sets the recipient of the email.
  • setBody(): sets the body of the email.
  • send(): sends the email and returns a Swift_Message object.
  • getId(): returns the unique ID of the sent email.

Helpful links

Edit this code on GitHub