PHP: Easily send email with PHPMailer

PHPMailer is a PHP class for PHP that provides a package of functions to send email. It is an efficient way to send e-mail within PHP. The following are some features of PHPMailer:-

– Sending HTML email
– Sending email with attachments
– Sending email to multiple recepients via to, CC, BCC, etc
– Supports nearly all possiblities to send email: mail(), Sendmail, qmail & direct to SMTP server

Download PHPMailer

For PHP 4 | For PHP 5 and above

Sample Code Example

Note isMail() function in the code. This indicates that email is to be sent through mail() function of php.

Sending email using mail() function


require_once('phpmailer/class.phpmailer.php');

$mail = new PHPMailer(); // defaults to using php "mail()"

// this indicates that mail() function is to be used to send email
$mail->IsMail();

$body = "Test body message";
$mail->AddAddress("yourname@example.com", "John Doe");
$mail->Subject    = "PHPMailer Test Subject via mail(), basic";
$mail->MsgHTML($body);

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!"; 
}

Sending email using SMTP

Along with using SMTP to send email, other functions are also being used. Like, adding reply-to address and from address. Also, notice that multiple reply-to address and multiple to-address are being added. Attachment function is also being included in the below code. You can add multiple attachment.


require_once('phpmailer/class.phpmailer.php');

$mail = new PHPMailer(); // defaults to using php "mail()"

$mail->IsSMTP();
$mail->Host = "smtp.example.com";

/**
 * optional
 * used only when SMTP requires authentication
 * if no authentication required then
 * you can set below as: SMTPAuth = false
 */
$mail->SMTPAuth = true;
$mail->Username = 'smtp_username';
$mail->Password = 'smtp_password';

$mail->AddReplyTo("name@yourdomain.com","First Last");
$mail->AddReplyTo("name2@yourdomain.com","First Last2");

$mail->SetFrom('name@yourdomain.com', 'First Last');

$body = "Test body message";

$mail->AddAddress("yourname@example.com", "John Doe");
$mail->AddAddress("yourname2@example.com", "John Doe2");

$mail->Subject    = "PHPMailer Test Subject via mail(), basic";
$mail->MsgHTML($body);

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!"; 
}

Download PHPMailer

For PHP 4 | For PHP 5 and above

Hope it helps. Thanks.