Click this widget to change the font size.
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Links | Search | Bio |

Guide to PHP and MySQL (University at Buffalo Version)

Chapter 11: Sending Email with PHP

PHPMailer function provides a set of class objects you can ue to send an email message from your web site. To send email, you must have an account on SMTP (Simple Mail Transfer Protocal) mail server, such as

Using PHPMailer on your localost Server.

To send email from your localhost server via a Gmail account, download the latest version of PHPMailer from GitHub (source code (zip)). Extract the file to your \www\PHPMailer\ folder.

Then you should try sending email. First, copy \www\PHPMailer\examples\gmail.phps to www\PHPMailer\examples\gmail.php. Then, edit this gmail.php file and change these values to your gmail account information:

  // Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "";
// Password to use for SMTP authentication
$mail->Password = "your-mail-password";
// Set who the message is to be sent from
$mail->setFrom('', 'First Last');
// Set an alternative reply-to address
$mail->addReplyTo('', 'First Last');
// Set who the message is to be sent to
$mail->addAddress('', 'John Doe');
Figure 11-1: gmail.php Settings

Sending Email with PHPMailer

See the \www\PHPMailer\examples\ for various examples of sending email using PHPMailer.

Using the PHP mail() function to send email

An easier way to send email is to use the PHP mail() function.

$headers  = "MIME-Version: 1.0\r\n"; // set-up HTML message body
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: put-your-name-here <put-your-email-address-here>\r\n";
$email    = "put-the-email-address-to-send-to-here";
$subject  = "Test send email subject line\r\n";
$message  = "Test email message with <strong>bold text</strong>.\r\n";
$success  = mail($email, $subject, $message, $headers);
if ($success) {
  echo("Message sent to $email");
} else {
  echo("Message not sent: ". error_get_last()['message']);
Figure 11-2: Using the PHP mial() Function

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2023 Jim Gerland