PHP Send Emails with Examples

Hey friend! 👋 So, you want to learn how to send emails using PHP? Awesome! Whether you're building a contact form, sending newsletters, or just automating some notifications, sending emails is a super useful skill to have. And guess what? PHP makes it pretty easy to do. Let’s dive in together, step by step, and I’ll show you how to send emails using PHP 8. Don’t worry I’ll keep it simple and fun!

 

 

php send emails with examples

 

 

 

Why Send Emails with PHP?

 

Before we get into the code, let’s talk about why you’d want to send emails with PHP. Maybe you’re building a website and need to send a confirmation email when someone signs up. Or perhaps you want to notify yourself when someone fills out a contact form. Whatever the reason, PHP has got your back.

 

 

The Basics: PHP’s mail() Function

 

PHP has a built-in function called mail() that lets you send emails. It’s super straightforward, but it has some limitations (we’ll talk about those later). Here’s the basic syntax:

 

mail($to, $subject, $message, $headers);
  • $to: The email address of the recipient.
  • $subject: The subject line of the email.
  • $message: The body of the email.
  • $headers: Additional headers like From, Cc, Bcc, etc.

 

Example 1: Sending a Simple Email

 

Let’s start with a simple example. Imagine you want to send an email to your friend saying, "Hey, PHP is awesome!"

 

<?php
$to = "friend@example.com";
$subject = "Hey, check this out!";
$message = "Hey, PHP is awesome!";
$headers = "From: you@example.com";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully!";
} else {
    echo "Oops, something went wrong.";
}
?>

 

That’s it! If everything is set up correctly, your friend will receive an email with the message "Hey, PHP is awesome!"

 

 

Example 2: Sending HTML Emails

 

Plain text emails are cool, but sometimes you want to send something fancier, like an email with HTML formatting. No problem! You just need to tweak the $headers and $message a bit.

 

<?php
$to = "friend@example.com";
$subject = "Welcome to My Website!";
$message = "
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Hello there!</h1>
    <p>Thanks for signing up. We're excited to have you on board.</p>
    <p><a href='https://example.com'>Visit our website</a></p>
</body>
</html>
";

// To send HTML email, the Content-type header must be set
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: you@example.com";

if (mail($to, $subject, $message, $headers)) {
    echo "HTML email sent successfully!";
} else {
    echo "Oops, something went wrong.";
}
?>

 

Now your email will look much prettier with HTML formatting!

 

The Limitations of mail()

 

While the mail() function is easy to use, it has some downsides:

 

  1. No Error Handling: If the email fails to send, you won’t get detailed error messages.
  2. Spam Issues: Emails sent with mail() often end up in spam folders.
  3. No SMTP Authentication: It doesn’t support SMTP authentication, which is often required by email providers.

 

So, what’s the solution? Use a library like PHPMailer!

 

Using PHPMailer for Better Emails

 

PHPMailer is a popular library that makes sending emails in PHP way more powerful and reliable. It supports SMTP authentication, HTML emails, attachments, and more. Let’s install it and try it out.

 

Step 1: Install PHPMailer

 

You can install PHPMailer using Composer (if you don’t have Composer, install it first).

Run this command in your project folder:

 

composer require phpmailer/phpmailer

 

Step 2: Send an Email with PHPMailer

 

Here’s an example of how to send an email using PHPMailer:

 

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Load Composer's autoloader

$mail = new PHPMailer(true); // Passing `true` enables exceptions

try {
    // Server settings
    $mail->isSMTP(); // Use SMTP
    $mail->Host = 'smtp.example.com'; // Your SMTP server
    $mail->SMTPAuth = true; // Enable SMTP authentication
    $mail->Username = 'you@example.com'; // SMTP username
    $mail->Password = 'yourpassword'; // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption
    $mail->Port = 587; // TCP port to connect to

    // Recipients
    $mail->setFrom('you@example.com', 'Your Name');
    $mail->addAddress('friend@example.com', 'Friend'); // Add a recipient

    // Content
    $mail->isHTML(true); // Set email format to HTML
    $mail->Subject = 'Welcome to My Website!';
    $mail->Body = '<h1>Hello there!</h1><p>Thanks for signing up.</p>';
    $mail->AltBody = 'Hello there! Thanks for signing up.'; // Plain text for non-HTML clients

    $mail->send();
    echo 'Email has been sent!';
} catch (Exception $e) {
    echo "Oops, something went wrong: {$mail->ErrorInfo}";
}
?>

 

Why Use PHPMailer?

 

  • SMTP Support: You can use your email provider’s SMTP server (e.g., Gmail, Outlook).
  • Error Handling: You’ll get detailed error messages if something goes wrong.
  • Attachments: You can easily attach files to your emails.
  • HTML Emails: It handles HTML emails beautifully.

 

Done.!

 

And there you have it, friend! You now know how to send emails using PHP 8. Whether you’re using the simple mail() function or the powerful PHPMailer library, you’re all set to start sending emails from your PHP applications.

 

Remember, sending emails is a powerful feature, so use it wisely. Don’t spam people, and always test your code before deploying it to production.

 

Happy coding! 🚀

chandrakumar

Hi, Am Chandra Kumar, I have completed my graduation in B.E computer science and Engineering. I am the founder of Dailyaspirants and I have been doing blogging and website design and development .since 2018 and 8+experience gained in this field.

*

Post a Comment (0)
Previous Post Next Post