Send Email From a PHP Script Using SMTP

Send Email From a PHP Script Using SMTP

DWQA QuestionsCategory: cPanelSend Email From a PHP Script Using SMTP
Team Glosting Staff asked 4 years ago

It is recommended to use SMTP authentication for sending emails.  If you are not using any CMS OR a custom coded website, use below steps to enable SMTP authentication in your contact form.

1. Login to your cPanel

2. access option PHP PEAR Packages.

3. Under Find a “PHP Extensions and Applications Package”, find for mail and click on Go.

4. Install Mail which is listed under the Module Name as below.

Once you install the package, create a php file for e.g. sendmail.php file with a following sample code and call it in html file for e.g. contact-us.html

require_once "Mail.php";

$from = "Sandra Sender <[email protected]>";
$to = "Ramona Recipient <[email protected]>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

$host = "ssl://servername or IP";
$port = "465";
$username = "smtp_username";
$password = "smtp_password";

$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");

Replace the details below with the actual ones.

  • from: the email address from which you want the message to be sent
  • to: recipient’s email address.
  • host: outgoing SMTP server name.
  • username: SMTP user name (typically the same as the username used to retrieve mail).
  • password: password for SMTP authentication.

Once done, you can try sending the emails and the emails would be sent using SMTP authentication.