Sending email via SMTP in PHP

Tr0jan_Horse

Expert
ULTIMATE
Local
Active Member
Joined
Oct 23, 2024
Messages
228
Reaction score
6
Deposit
0$
Sending Email via SMTP in PHP: A Practical Guide

Sending emails programmatically is a common requirement in web development. In this article, we will explore how to send emails using SMTP in PHP. This method is reliable and allows for better control over email delivery.

What is SMTP?

SMTP (Simple Mail Transfer Protocol) is a protocol used for sending emails across the Internet. It is widely supported and allows you to send emails from your PHP applications.

Requirements

Before we start, ensure you have the following:
- A web server with PHP installed.
- Access to an SMTP server (like Gmail, SendGrid, etc.).
- The PHPMailer library, which simplifies sending emails via SMTP.

Step 1: Install PHPMailer

You can install PHPMailer using Composer. If you don’t have Composer installed, you can download it from [here](https://getcomposer.org/).

Run the following command in your terminal:

```
composer require phpmailer/phpmailer
```

Step 2: Sending Email via SMTP

Now, let’s create a PHP script to send an email. Below is a sample code snippet that demonstrates how to do this:

[expand]
```php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
//Server settings
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'your_password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption
$mail->Port = 587; // TCP port to connect to

//Recipients
$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Joe User'); // Add a recipient

// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = '<b>This is the HTML message body</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$mail->send();
echo '<span style="color: green;">Message has been sent</span>';
} catch (Exception $e) {
echo '<span style="color: red;">Message could not be sent. Mailer Error: ' . $mail->ErrorInfo . '</span>';
}
?>
```
[/expand]

Step 3: Testing Your Script

1. Save the script as `send_email.php`.
2. Update the SMTP server details, username, and password.
3. Run the script in your browser.

Conclusion

Sending emails via SMTP in PHP is straightforward with the PHPMailer library. This method provides a robust solution for email delivery in your applications. For more information, check the [PHPMailer documentation](https://github.com/PHPMailer/PHPMailer).

Feel free to experiment with the code and customize it to fit your needs. Happy coding!
 
Register
Top