keepcalculator

06 Numbers and Powers

Swift Mailer: Send Email & What to Use Instead

Card No. 06·40332 · Updated · Standard formula, shown below

This guide walks you through sending emails with Swift Mailer, a popular PHP library for building and sending messages. You’ll learn the core steps—from installation to sending—and then see why many developers now choose its successor, Symfony Mailer, along with a modern alternative like PHPMailer. By the end, you’ll be able to send a basic email and know which tool fits your current project.

What You’ll Need

  • A PHP environment (PHP 7.2 or later for Swift Mailer 6.x; older versions may work with PHP 5.3+).
  • Composer installed to manage dependencies.
  • Access to an SMTP server (e.g., your hosting provider’s mail server, Gmail SMTP, or a service like Mailtrap for testing). You’ll need the hostname, port, username, and password.
  • Basic familiarity with PHP and command-line operations.

Step-by-Step

  1. Install Swift Mailer via Composer. In your project directory, run:
    composer require swiftmailer/swiftmailer

    This installs the library and its dependencies. If you don’t have Composer, download it from getcomposer.org first.

  2. Require the autoloader. In your PHP script, add:
    require_once 'vendor/autoload.php';

    This loads all classes automatically.

  3. Create the transport. The transport is how Swift Mailer sends the message. For SMTP, use:
    $transport = (new Swift_SmtpTransport('smtp.example.com', 587, 'tls'))
        ->setUsername('your@email.com')
        ->setPassword('your-password');

    Replace the host, port, and security (tls or ssl) with your SMTP server’s details. Port 587 with TLS is common; some servers use 465 with SSL.

  4. Create the mailer. The mailer uses the transport to send:
    $mailer = new Swift_Mailer($transport);
  5. Build the message. Use Swift_Message to set the subject, from, to, and body:
    $message = (new Swift_Message('Test Subject'))
        ->setFrom(['sender@example.com' => 'Sender Name'])
        ->setTo(['recipient@example.com' => 'Recipient Name'])
        ->setBody('This is a plain text message.');

    For HTML, add ->setContentType('text/html') and pass the HTML as the body. You can also add attachments with ->attach(Swift_Attachment::fromPath('file.pdf')).

  6. Send the message. Call the send method and check the result:
    $result = $mailer->send($message);
    if ($result) {
        echo "Email sent successfully.\n";
    } else {
        echo "Failed to send.\n";
    }

    The $result is the number of recipients who received the message. If it’s 0, something went wrong.

  7. Handle errors (optional but recommended). Wrap the send in a try-catch block to catch exceptions like authentication failures:
    try {
        $mailer->send($message);
    } catch (Swift_TransportException $e) {
        echo 'Error: ' . $e->getMessage();
    }

Common Mistakes

  • Wrong SMTP port or security. Using port 25 (often blocked) or mixing up TLS/SSL. Check your provider’s documentation.
  • Forgetting to set the “From� address. Some servers reject emails without a valid sender.
  • Using the wrong autoload path. If you don’t include vendor/autoload.php, classes won’t be found.
  • Not escaping special characters in the body. If you’re sending HTML, ensure it’s properly structured.
  • Assuming send() returns true on success. It returns the number of successful recipients; 0 means failure.

Tips

  • Use a dedicated email testing service (like Mailtrap or Mailhog) in development to avoid spamming real inboxes.
  • Set a timeout on the transport to avoid long hangs: $transport->setTimeout(10);
  • For bulk emails, reuse the same mailer instance and loop over recipients to improve performance.
  • Always use a secure connection (TLS/SSL) for SMTP to protect credentials.
  • If you need to send attachments, use Swift_Attachment and ensure the file path is correct.

Troubleshooting

  • Authentication failure: Double-check username and password. Some providers require an app-specific password (e.g., Gmail).
  • Connection refused: Verify the hostname and port. Try connecting with a telnet client to see if the server is reachable.
  • Email goes to spam: Ensure your domain has proper SPF and DKIM records. For testing, use a service that accepts all mail.
  • Script times out: Increase the timeout on the transport or check if your firewall blocks outbound SMTP.
  • No error but no email: Check your spam folder. Also, confirm the “From� address matches the authenticated user on some servers.

What to Use Instead

Swift Mailer is now in maintenance mode; its official successor is Symfony Mailer. It offers a cleaner API, better performance, and support for modern PHP versions. To migrate, install with composer require symfony/mailer and use the Mailer class. For example:

use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;

$transport = new EsmtpTransport('smtp.example.com', 587, 'tls');
$transport->setUsername('user');
$transport->setPassword('pass');
$mailer = new Mailer($transport);

$email = (new Email())
    ->from('sender@example.com')
    ->to('recipient@example.com')
    ->subject('Test')
    ->text('Hello!');

$mailer->send($email);

Another popular alternative is PHPMailer, which is actively maintained and has a similar feature set. It’s a good choice if you prefer a standalone library without Symfony dependencies.

Frequently Asked Questions

Is Swift Mailer still supported?

Swift Mailer is no longer actively developed; it receives only critical security fixes. Symfony Mailer is the recommended replacement.

Can I send email without SMTP?

Yes, you can use the Swift_SendmailTransport to send via the local sendmail binary, but SMTP is more reliable and portable.

How do I send an HTML email with Swift Mailer?

Set the content type to text/html and pass the HTML string to setBody(). You can also use addPart() for a plain-text fallback.

Why does my email go to spam?

Common reasons include missing SPF/DKIM records, a “From� domain that differs from the SMTP server, or content that triggers spam filters. Authenticate properly and use a reputable sending domain.

What is the difference between Swift Mailer and PHPMailer?

Both are PHP mail libraries. Swift Mailer is older and being phased out; PHPMailer is actively maintained and widely used. Symfony Mailer is the modern successor to Swift Mailer.

Can I use Swift Mailer with PHP 8?

Swift Mailer 6.x works with PHP 8, but you may encounter deprecation warnings. Symfony Mailer is fully compatible with PHP 8+.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →