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

<?php
$to = "some@one.com"; //mail to
$from = "you@domain.com"; //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";
}
else
{
echo "Unable to send mail";
}
?>

Send mail using phpmailer (recommended method)

You can download phpmailer script from http://phpmailer.worxware.com/

<?
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("name@yourdomain.com","First Last"); //reply to address
$mail->SetFrom('name@yourdomain.com', 'First Last'); //from address
$address = "whoto@otherdomain.com"; //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 *