Code for How to Send Email in PHP Using Mail SMTP with PHPMailer ,2024

Sending emails through PHP is a common task in web development. There are many ways to accomplish this, but one of the most popular is using the PHPMailer library. In this article, we will explore how to use PHPMailer to send emails through SMTP.

Setting up PHPMailer

To start using PHPMailer, you first need to download and install it. You can download PHPMailer from its official website. After downloading, extract the files and copy the PHPMailer folder into your project directory.

Next, create a new PHP file and include the necessary PHPMailer files using the following code:

require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';

Configuring SMTP Settings

To send an email through SMTP, you need to configure the SMTP settings. This includes the SMTP server address, port number, authentication details, and more. You can obtain these details from your email provider or SMTP service provider.

Once you have the SMTP settings, you can use PHPMailer to set them using the following code:

//SMTP Settings
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@gmail.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;

In this example, we are using Gmail’s SMTP server to send emails. You will need to replace the SMTP settings with your own SMTP server details.

Creating and Sending an Email

Now that you have set up PHPMailer and configured the SMTP settings, you can create and send an email using the following code:

//Email content
$mail->isHTML(true);
$mail->Subject = 'Test Email Subject';
$mail->Body = 'Test email content';

//Add recipient
$mail->addAddress('recipient@example.com');

//Send email
if(!$mail->send()){
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
   echo 'Message has been sent';
}

In this example, we have set the email’s subject and body, added a recipient, and sent the email using PHPMailer’s send() method. You can customize the email’s content and recipients based on your requirements.

Conclusion

Sending emails through PHP is an important task in web development. Using a powerful library like PHPMailer can simplify the process of sending emails through SMTP. By following the steps outlined in this article, you can set up and use PHPMailer to send emails through your preferred SMTP server.

Discover more from STRUGGLER KING.COM

Subscribe now to keep reading and get access to the full archive.

Continue Reading