PHPMailer: Send emails from your site

This time I would like to talk about the library PHPMailer. This library is ideal if you need to send emails from your web site to its users (e.g: for notifying the data suscription, warning about the near account expiration, etc). A very interesting feature offered by this library is allowing us using a GMail account to send emails (of course, we must be the owners of that account). It is true that PHP already includes functions to send emails from your code (the mail() function for instance), but it was always annoying for me to do it this way.

Firstly, in order to use the mail() function in PHP, we must configure the PHP server properly, setting all the parameters related to send emails in the php.ini file. But this does not end here, the worst thing is that we must have a mail server (eg postfix or qmail, or whatever) running on the same machine where you run your application. If we have our app running on an external server hired for that purpose, no problem, but if we have to maintain the machine (for whatever reason), it is not so easy.

In order to install and maintain a mail server it is required, besides fairly advanced knowledge in the subject (operation, configuration, etc.), a very good knowledge about security, since a mail server is a candy for those who like to “steal” some machines, making them “zombies” and using them as spammers. This is why I opted for this library.

Using the library

The first thing we must do is to download the latest version of this library. Once you have unzipped the file and placed the library directory into the web application directory, we can start to use it. If we want to, we can remove the test directory, examples and docs, since they are not necessary for the correct working of the library.

Let’s see an example. Let’s say that we have shown a form to the user, he fills the form (among other data, he provides us an e-mail) and when he sends it we have to process the data and send an e-mail confirming that the information has been processed. We will send the email through a GMail account, using for that secure SMTP protocol, so we have the peace of mind that Google is behind. Well, in our controller that processes the form we have to include the following code:

include(PHPMailer/class.phpmailer.php);

With this, we have already access to library functions. From now on, we only have to create the object, add all the parameters that we have collected from the form previously presented to the user, and send it. For that, we must add the following code:

$mail = new PHPMailer();

$mail->IsSMTP(); // establish we are going to use SMTP
$mail->SMTPAuth   = true; // enable SMTP authentication
$mail->SMTPSecure = "tls";  // establish the secure protocol that we are going to use with the server
$mail->Host       = "smtp.gmail.com";      // GMail is our SMTP server
$mail->Port       = 587;                   // Gmail's secure SMTP port
$mail->Username   = "minombreusuario@gmail.com";  // our email account (we are the owners)
$mail->Password   = "your_Password";   // password for that account

$mail->SetFrom('info@yourdomain.com', 'Your Name');  //Who is sending the email
$mail->AddReplyTo("response@yourdomain.com","Your Name");  //Who will receive the response if the user replies
$mail->Subject    = "Your data was received";  //Subject of the email
 Your form was received correctly.<br />
 <strong>Thank you very much!</strong>";  //HTML body of the message
$mail->AltBody    = "Hi,n
 Your form was received correctly.n
 Thank you very much!";  //Body of the message if the user cannot read HTML emails

$destination = "someuser@somedomain.com";
$mail->AddAddress($address, "John Doe");

$mail->AddAttachment("images/phpmailer.gif");      // add some attachments if necessary
$mail->AddAttachment("images/phpmailer_mini.gif"); // as many as you want

if(!$mail->Send()) {
echo "Error sending the email: " . $mail->ErrorInfo;
} else {
 echo "Email sent successfully!";
}

With this we would have ready our code to send emails to users of our site. Now, I would like to clarify a couple of lines of code above, where we create the message body. For convenience, if we send a HTML body, we could have a HTML template (some file with .html extension) where we put the standard message, which is included later in the mail this way:

$body  = file_get_contents('email_template.html');
$body  = eregi_replace("[]",'',$body);
...
...
$mail->MsgHTML($body);

Now we have completely finished our code to send emails from our website via GMail. Finally, I would like to point out that this code is also valid to send emails using an account at any other mail server, as long as we are the owners of that account and we know its password and the server is enabled to send emails via SMTP.

9 thoughts on “PHPMailer: Send emails from your site

  • Hello Agustin – I have a Flash game program the sends email notifications to winners. It uses server side email capability with the file sendEmail.php.

    I am developing a desktop version of this game and want to integrate PHPMail into the program to send emails with SMTP servers like gmail.

    My Flash developer works mostly with server side applications and is unable to integrate PHPMail’s SMTP function into the game program.

    Do you know if this can be done? I can send more details if you think you can help with this problem.

    Thanks for any help you can give.

    • Hi Thomas,

      If I did not misunderstand, your desktop version will try to connect to the server script sendEmail.php, right? Because if this correct, it should work like I explained in my articule.

      Please, could you clarify this point?

      Cheers!

  • Hi Agustin,

    No, I want the desktop version to connect with SMTP servers like smtp.gmail.com or smtp.live.com. I want the game users to supply their mail server instead of using my domain server.

    Here is the current working sendEmail.php file. This is for use on my website, my mail server.

    I want to change this to a version for buyers of the game to use their own smtp mail servers:

    <?php

    $user_name = $_POST['name'];
    $user_number = $_POST['number'];
    $emailFrom = $_POST['email'];
    $massage = $_POST['msg'];

    //to me
    $to = "info@xxxxx.com";
    $subject = 'Prize Wheel Result';
    $bound_text = "jimmyP123";
    $bound = "–".$bound_text."rn";
    $bound_last = "–".$bound_text."–rn";

    $headers = "From: $emailFromrn";
    $headers .= "MIME-Version: 1.0rn"
    ."Content-Type: multipart/mixed; boundary="$bound_text"";

    $message .= "If you can see this MIME than your client doesn't accept MIME types!rn"
    .$bound;

    $message .= "Content-Type: text/html; charset="charset=utf-8"rn"
    ."Content-Transfer-Encoding: 8bitrnrn"
    ."User Name : “.$user_name.”rn”
    .”Member Number : “.$user_number.”rn”
    .”Email : “.$emailFrom.”rn”
    .”Prize Result : “.$massage.”rn”
    .$bound_last;

    //for customer
    $subject2 = ‘Prize Wheel Result’;
    $bound1_text = “jimmyP123”;
    $bound1 = “–“.$bound1_text.”rn”;
    $bound1_last = “–“.$bound1_text.”–rn”;

    $header2 = “From: info@xxxx.comnReply-To: tk@xxxxx.comrn“;
    $header2 .= “MIME-Version: 1.0rn”
    .”Content-Type: multipart/mixed; boundary=”$bound_text””;

    $body2 .= “If you can see this MIME than your client doesn’t accept MIME types!rn”
    .$bound1;

    $body2 .= “Content-Type: text/html; charset=”charset=utf-8″rn”
    .”Content-Transfer-Encoding: 8bitrnrn”
    .”User Name : “.$user_name.”rn”
    .”Member Number : “.$user_number.”rn”
    .”Prize Result : “.$massage.”rn”
    .$bound1_last;

    if(mail($to, $subject, $message, $headers) && mail($emailFrom, $subject2, $body2, $header2))
    {
    echo ( “result=Successful” );
    } else {
    echo ( “result=Unsuccessful” );
    }

    ?>

    • Hi Thomas,

      If I am not wrong, you are expecting that your game buyers provide you their email account in order to send emails using their email accounts, right? In that case, your users will have to provide you their password for their account in gmail, thus you will be able to login with their email account and their password and send the email using their smtp servers.

      The rest of the process to connect to GMail and send email is described in the article.

      Cheers!

      • Hi Agustin,

        This is a downloadable game. Buyer buys the game downloads/installs to their computer and the game is used entirely on their desktop. It is not necessary for them to give me their email log in creds. The game should send out notification emails to the game winner, using their mail server for their own players.

        I have a version of the game for use on my website that will send emails using server side email. But I’m asking about a version that is not used on the web, except to send smtp emails users game players.

      • Hi Agustin,

        Here is a follow-up with more information about my question. The Flash game writes the winners email and prize won the the sendEmail.php file for automatic notification emails. The buyer configures the game GUI with their smtp server with their username and password, message, etc. prior to running the game.

Leave a Reply

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