Web20 University

A Complete Guide to Using SwiftMailer for Sending Emails in PHP

Get up to 65% Off Hosting with FREE SSL & FREE Domains!

* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.

When it comes to sending emails in PHP, using a robust and reliable library like SwiftMailer can significantly simplify the process. SwiftMailer is a popular and powerful PHP library designed for sending emails using a wide variety of transport methods such as SMTP, Sendmail, or even through third-party services like Gmail. In this blog post, we will walk through how to send a simple email using SwiftMailer, provide a full example of a web form to send an email, and explore whether SwiftMailer can be used on shared hosting platforms like HostGator.


What is SwiftMailer?

SwiftMailer is an open-source PHP library used to send emails programmatically. It’s much more flexible and feature-rich than PHP’s built-in mail() function, making it an excellent option for more advanced email-sending needs, such as:

  • Using an SMTP server for better deliverability.
  • Attaching files and HTML content to emails.
  • Handling errors and logging.

Unlike PHP’s mail() function, which relies on the server’s mail configuration, SwiftMailer gives you more control by supporting SMTP, Sendmail, and other transports. This makes it a preferred choice for developers needing more control, better performance, and improved reliability.


How to Send a Simple Mail with SwiftMailer

Let’s dive into sending a simple email using SwiftMailer. First, you’ll need to install the SwiftMailer library using Composer, a package manager for PHP.

Step 1: Install SwiftMailer via Composer

If you don’t have Composer installed, follow this link to install it.

Once Composer is ready, run the following command in your project directory to install SwiftMailer:

composer require swiftmailer/swiftmailer

Step 2: Basic Email Example with SwiftMailer

After installation, you can use SwiftMailer in your PHP project. Here’s a simple example to send an email:

<?php
// Include the Composer autoloader
require_once 'vendor/autoload.php';

// Create the Transport (SMTP in this case)
$transport = (new Swift_SmtpTransport('smtp.example.com', 587))
  ->setUsername('your-username')
  ->setPassword('your-password');

// Create the Mailer using the created Transport
$mailer = new Swift_Mailer($transport);

// Create a message
$message = (new Swift_Message('Test Email from SwiftMailer'))
  ->setFrom(['[email protected]' => 'Your Name'])
  ->setTo(['[email protected]'])
  ->setBody('This is a test email sent using SwiftMailer.');

// Send the message
$result = $mailer->send($message);

if ($result) {
    echo "Email sent successfully!";
} else {
    echo "Failed to send email.";
}
?>

In this example:

  • We define the SMTP transport, which specifies the mail server details like host, port, username, and password.
  • We create a mailer instance with this transport.
  • The Swift_Message object represents the email, where we set the subject, sender, recipient, and body of the message.
  • Finally, the send() method attempts to send the email.

This basic setup allows you to send a simple text email using SwiftMailer.


Can SwiftMailer Be Used on Shared Hosting Like HostGator?

Yes, SwiftMailer can be used on shared hosting platforms like HostGator. Since shared hosting platforms typically restrict the use of the PHP mail() function due to email abuse and spam concerns, SwiftMailer’s ability to connect to external SMTP services is a better alternative.

Here are a few tips to ensure it works well on shared hosting:

  1. Use External SMTP Services: It’s common to configure SwiftMailer to use external SMTP services like Gmail, SendGrid, or any other service your host supports.

  2. Check Host Limits: Many shared hosting providers, including HostGator, impose limits on the number of emails that can be sent per hour or per day. Be sure to check these restrictions to avoid your emails being blocked.

  3. SSL/TLS Ports: If you’re using an external SMTP, ensure your server supports the necessary SSL or TLS ports (465/587) for secure email delivery.


Full Web Form Example Sending a Mail Using SwiftMailer

Now, let’s create a more practical example where we send an email using a web form with SwiftMailer.

Step 1: Create the HTML Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form</title>
</head>
<body>
    <h2>Contact Us</h2>
    <form action="send_mail.php" method="POST">
        <label for="name">Name:</label>
        <input type="text" name="name" required><br><br>

        <label for="email">Email:</label>
        <input type="email" name="email" required><br><br>

        <label for="message">Message:</label>
        <textarea name="message" required></textarea><br><br>

        <input type="submit" value="Send Message">
    </form>
</body>
</html>

Step 2: Create the PHP Script to Handle Form Submission (send_mail.php)

<?php
// Include Composer autoloader
require_once 'vendor/autoload.php';

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = htmlspecialchars($_POST['name']);  // Sanitize input
    $email = htmlspecialchars($_POST['email']);  // Sanitize input
    $messageContent = htmlspecialchars($_POST['message']);  // Sanitize input

    // Create the Transport
    $transport = (new Swift_SmtpTransport('smtp.example.com', 587))
      ->setUsername('your-username')
      ->setPassword('your-password');

    // Create the Mailer using the created Transport
    $mailer = new Swift_Mailer($transport);

    // Create a message
    $message = (new Swift_Message("New message from $name via Contact Form"))
      ->setFrom([$email => $name])
      ->setTo(['[email protected]'])
      ->setBody($messageContent);

    // Send the message
    $result = $mailer->send($message);

    if ($result) {
        echo "Message sent successfully!";
    } else {
        echo "Failed to send message.";
    }
} else {
    echo "Invalid request.";
}
?>

In this example:

  • We created a form that allows users to input their name, email, and message.
  • When the form is submitted, the data is passed to a PHP script that uses SwiftMailer to send the message to a specified email address.
  • As with the previous example, SMTP is used to handle the mail transport.

How to Upload to Shared Hosting Like HostGator

Here are the steps to upload your SwiftMailer-based contact form to a shared hosting service like HostGator:

Step 1: Prepare Your Files

Ensure all necessary files are organized:

  • The HTML form file (e.g., index.html).
  • The PHP file handling form submission (e.g., send_mail.php).
  • The vendor folder (generated by Composer).

Step 2: Access Your Hosting Account

  1. Log in to your HostGator cPanel.
  2. Navigate to File Manager under the Files section.

Step 3: Upload the Files

  1. Navigate to your website’s directory (usually /public_html/).
  2. Upload the HTML, PHP, and vendor folder.
  3. Once uploaded, you can access the form from your website’s URL and test the email functionality.

Conclusion

SwiftMailer is a powerful PHP library that provides flexibility, security, and enhanced functionality for sending emails. Compared to PHP’s built-in mail() function, SwiftMailer offers better performance, SMTP support, and additional features like attachments and HTML emails. In this post, we discussed how to send a simple email with SwiftMailer, provided a complete example of a contact form, and explained how to upload it to shared hosting like HostGator.

For more complex email-sending needs, SwiftMailer is a reliable choice that offers much more control and flexibility than the basic mail function.


Resources:

Get up to 65% Off Hosting with FREE SSL & FREE Domains!