Send email using php script

To send email from your php script either you can use PHP’s built-in mail function or third party library like phpmailer or swiftmailer.

In this article you will find both methods to send email.

Send Mail using php mail function

$to = ""; //mail to
$from = ""; //your email
$subject = "This test mail sent using php mail function"; //mail Subject
$msg = "Your email body will go here"; //your message body
$headers = "MIME-Version: 1.0";
$headers.= "Content-type: text/plain; charset=iso-8859-1";
$headers.= "From: {$from}";
$headers.= "Reply-To: {$from}";
$headers.= "Subject: {$subject}";
$headers.= "X-Mailer: PHP/".phpversion();
if(mail($to, $subject, $msg, $headers))
echo "Mail Sent";
echo "Unable to send mail";

Send mail using phpmailer (recommended method)

You can download phpmailer script from

require_once('../class.phpmailer.php');//include phpmailer class
$mail = new PHPMailer(); // defaults to using php "mail()"
$mail->IsSendmail(); // telling the class to use SendMail transport
$mail->ContentType = 'text/plain';
$mail->Body = "Your email body will go here"; //your message body
$mail->AddReplyTo("","First Last"); //reply to address
$mail->SetFrom('', 'First Last'); //from address
$address = ""; //to address
$mail->AddAddress($address, "John Doe");
$mail->Subject   = "PHPMailer Test Subject via Sendmail, basic"; //mail Subject
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";

phpmailer library is easy to use and highly configurable. Unlike php built-in mail function we can easily send html mail or email with attachments without having to play around with headers.

Published by Sunny

A Mechanical engineer by education and web developer by passion and profession. He lives in Lucknow, India. Currently earning his livings by hitting keyboad. ;)

Leave a comment

Your email address will not be published. Required fields are marked *