PHP Send Mail using SMTP

This tutorial shows you how you can send email using SMTP server’s settings. PHP people generally uses the PHP mail() function to send the mail.

But we can use the other SMTP servers to send the mail from our PHP script.

I will recommodend to use PEAR’s mail package to send the mail using SMTP.

Please refer the below code to send the mails using PHP and SMTP.

PS: Below code assumes that you have correctly included the PEAR and PEAR Mail files.

$subject = "This mail is sent from SMTP."; $mail_body = "This is the body of the mail which is sent using SMTP."; $from = "From: From Name "; $to = "To: To Name "; $receiver = "[email protected]"; // Setting up the headers $headers["From"] = $from; $headers["To"] = $to; $headers["Subject"] = $subject; $headers["Reply-To"] = "[email protected]"; $headers["Content-Type"] = "text/plain; charset=ISO-2022-JP"; $headers["Return-path"] = "[email protected]"; // Setting up the SMTP setting $smtp_info["host"] = "smtp.server.com"; $smtp_info["port"] = "25"; $smtp_info["auth"] = true; $smtp_info["username"] = "smtp_user"; $smtp_info["password"] = "smtp_password"; // Creating the PEAR mail object : $mail_obj =& Mail::factory("smtp", $smtp_info); // Sending the mail now $mail_sent = $mail_obj->send($receiver, $headers, $mail_body); // If any error the see for that here: if (PEAR::isError($mail_sent)) { print($mail_sent->getMessage());}
$subject = "This mail is sent from SMTP.";
$mail_body = "This is the body of the mail which is sent using SMTP.";
$from = "From: From Name <[email protected]>";
$to = "To: To Name <[email protected]>";
$receiver = "[email protected]";

// Setting up the headers
$headers["From"] = $from;
$headers["To"] = $to;
$headers["Subject"] = $subject;
$headers["Reply-To"] = "[email protected]";
$headers["Content-Type"] = "text/plain; charset=ISO-2022-JP";
$headers["Return-path"] = "[email protected]";

// Setting up the SMTP setting
$smtp_info["host"] = "smtp.server.com";
$smtp_info["port"] = "25";
$smtp_info["auth"] = true;
$smtp_info["username"] = "smtp_user";
$smtp_info["password"] = "smtp_password";

// Creating the PEAR mail object :
$mail_obj =& Mail::factory("smtp", $smtp_info);

// Sending the mail now
$mail_sent = $mail_obj->send($receiver, $headers, $mail_body);

// If any error the see for that here:
if (PEAR::isError($mail_sent)) { print($mail_sent->getMessage());}

You can download the PHP PEAR Package from here.

Note: It is recommodend to use PEAR’s Mail Package to send the mail using SMTP.

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: