PHP Sending emails

  • Post author:
  • Post category:PHP
  • Post comments:0 Comments

PHP provides several ways to send emails, including the mail() function, and various email libraries such as PHPMailer and Swift Mailer.

The mail() function is the simplest way to send an email in PHP. It takes the recipient’s email address, the subject, and the message as arguments. The following code will send an email to “[email protected]” with the subject “Test Email” and the message “Hello, World!”:

$to = "[email protected]";
$subject = "Test Email";
$message = "Hello, World!";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";

mail($to, $subject, $message, $headers);

However, mail() function has some limitations such as it doesn’t support sending emails with attachments, and it doesn’t handle errors very well.

For more advanced features, libraries such as PHPMailer and Swift Mailer can be used. These libraries provide more options for configuring the email, such as adding attachments, setting the sender, and handling errors.

For example, the following code uses PHPMailer to send an email with an attachment:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

$mail = new PHPMailer();
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "[email protected]";
$mail->Password = "password";
$mail->SetFrom("[email protected]");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("[email protected]");
$mail->AddAttachment("path/to/attachment.zip");
$mail->Send();

It’s worth mentioning that when sending emails through PHP, you should always check for errors and handle them appropriately, and also make sure you are using a secure method of sending emails, such as using a SMTP server with SSL/TLS encryption.

Leave a Reply