Site icon techieswiki

How to send email from PHP through SMTP server?

Sending mail with PHP mail() function is very simple and easy… well if it works!!!

Recently I faced the same issue in one of my projects, mail() function didn’t work as expected. I hosted the Website in Hostgator server, and I got to know from them that the mail() function won’t work in the server instead I need to use PHP script with SMTP.  I thought of sharing the solution with you all. I am using PHP mailer here, this will be already installed in most of the servers.

require("class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP();
$mail->Host = "yourhostname.com";
$mail->SMTPAuth = true;
//$mail->SMTPSecure = "ssl";
$mail->Port = 587;
$mail->Username = "support@yourhostname.com";
$mail->Password = "password";

$mail->From = "support@yourhostname.com";
$mail->FromName = "Sample";
$mail->AddAddress($_POST['email']);
//$mail->AddReplyTo("mail@mail.com");

$mail->IsHTML(true);

$mail->Subject = "Test message from server";
$mail->Body = 'Body of your EMAIL';
//$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

if(!$mail->Send())
{
$message="Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}

$message="E-Receipt send to your mail id";

 

 

Exit mobile version