Skip to main content
How to Send mail via PHP script using PHPMailer
Rapyd Team avatar
Written by Rapyd Team
Updated over a week ago

Email communication is a crucial aspect of web applications, and PHPMailer is a popular choice among developers to send emails from PHP scripts. While Rapyd Hosting currently does not support this feature, there is a possibility of it being implemented in the future. This article provides an insight into how it can be done once the feature becomes available.

Introduction to PHPMailer:

PHPMailer is a code library that allows you to send emails safely and easily via PHP code without requiring sendmail or mail() functions. It supports attachments, inline images, SMTP authentication, and more, making it highly versatile.

Prerequisites for PHPMailer:

  • A functioning PHP environment

  • SMTP server details (this will come into play when Rapyd Hosting supports PHPMailer)

  • Composer (for installing PHPMailer)

Setting Up PHPMailer:

  • Install PHPMailer via Composer with the command composer require phpmailer/phpmailer.

  • Once installed, you can incorporate it into your script using an include or require statement.

Creating a Basic Email Script with PHPMailer:

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

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
//Server settings
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.yourdomain.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-email-password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

//Recipients
$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Receiver Name');

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

$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>

Best Practices and Recommendations:

  • Always sanitize and validate email content and addresses to protect against email injection attacks.

  • For large-scale email deliveries, consider using third-party services to manage your emails.

  • Regularly update the PHPMailer library to ensure you have the latest security patches.

Conclusion:

PHPMailer provides a reliable way to send emails via PHP, and while it's currently not supported at Rapyd Hosting, it promises a seamless integration when the time comes. Always adhere to best practices to maintain email integrity and safety. If you need further assistance once this becomes available at Rapyd, reach out to the support team for guidance.

Did this answer your question?