Dec 27

In this tutorial, we’ll see how the PHP server-side scripting language can be used to send email, and explore how to send complex message types such as HTML email or emails with file attachments.

For convenience we will be using PHPMailer in this tutorial.
PHPMailer is a class for PHP that provides a package of functions to send email. The two primary features are sending HTML Email and e-mails with attachments. PHPMailer is an efficient way to send e-mail within PHP.

Step 1: Downloading PHP mailer

  • You can download the latest release from the PHPMailer website: PHPMailer

Before continuing, please be sure that PHPMailer is installed correctly. If you feel uncertain, please read the installion instructions that accompany the package.

Step 2: Sending our first email

In this first example we’ll be sending out a simple email, covering the basics of the PHPMailer package.

We start off by including the PHPMailer libary in our script:

require("class.phpmailer.php"); // First we require the PHPMailer libary in our script

Next we create a new object of this libary (a new object of the class PHPMailer) called $mail.

$mail = new PHPMailer(); // Next we create a new object of the PHPMailer called $mail

Now we enter the address that the e-mail should appear to come from. You can use any address that the SMTP server will accept as valid.

$mail->From = "from@example.com";

Now we give the address an associated name. This will add ‘Your Name’ to the from address, so that the recipient will know the name of the person who sent the e-mail.

$mail->FromName = "Your Name";

Now we add the to address, the address to which the e-mail will be sent. You must use a valid e-mail here, of course, if only so that you can verify that your PHPMailer test worked. It’s best to use your own e-mail address here for this inintial test.

$mail->AddAddress("myfriend@example.net"); // This is the adress to witch the email has to be send.

Now we set the subject of the email.

$mail->Subject = "First PHP Email message"; // This is the subject  of the email message.

Next up is the actual message in the email, this is done by the $mail->body. You can use ‘\n’ for a new line.

$mail->Body = "Hi! \n\n This is my first e-mail sent through PHP."; // This is the actual email message

Finally, we send out the e-mail, once all necessary information has been provided. This is done with $mail->Send();. In this example script, it’s combined with an error message; if Send() fails, it’ll return false and you can catch it and display an error message.

if(!$mail->Send()) // Now we send the email and check if it was send or not.
{
   echo 'Message was not sent.';
   echo 'Mailer error: ' . $mail->ErrorInfo;
}
else
{
   echo 'Message has been sent.';
}

Here is the complete example:

The complete first example

<?php
require("class.phpmailer.php"); // First we require the PHPMailer libary in our script
$mail = new PHPMailer(); // Next we create a new object of the PHPMailer called $mail

$mail->From = "from@example.com"; // this is the From adress (the adress the email came from)
$mail->FromName = "Your Name";

$mail->AddAddress("myfriend@example.net"); // This is the adress to witch the email has to be send.

$mail->Subject = "First PHP Email message"; // This is the subject  of the email message.

$mail->Body = "Hi! \n\n This is my first e-mail sent through PHP."; // This is the actual email message

if(!$mail->Send()) // Now we send the email and check if it was send or not.
{
   echo 'Message was not sent.';
   echo 'Mailer error: ' . $mail->ErrorInfo;
}
else
{
   echo 'Message has been sent.';
}
?>

Step 3: Sending your first HTML email

Sending out HTML e-mail is a easy task with PHPMailer, but it requires knowledge of HTML. Mail clients vary greatly in their support of HTML email, with some refusing to show it. For those mail clients that are not able to display HTML, you can provide an alternate email body containing the message as text.

We start the same way as example 1, but now we use the following changes:

We use the $mail->IsHTML(true) to tell the script that the email that will be sent is an HTML message.

$mail->IsHTML(true); // This tell's the PhPMailer that the messages uses HTML.

Then we create the HTML message the same way we did for the normal text one, using the $mail->Body. But this time we add HTML codes to it.

$mail->Body = "Hello, <b>my friend</b>! \n\n This message uses HTML !";

Now we make sure that people who can’t read HTML emails can also read the message, this is done by providing an Alternative body:

$mail->AltBody = "Hello, my friend! \n\n This message uses HTML, but your email client did not support it !";

Next we send the email on the same way as example 1.

The complete HTML example

<?php

require("class.phpmailer.php");
$mail = new PHPMailer();

$mail->From = "from@example.com";
$mail->FromName = "Your Name";
$mail->AddAddress("myfriend@example.net"); // This is the adress to witch the email has to be send.
$mail->Subject = "An HTML Message";
$mail->IsHTML(true); // This tell's the PhPMailer that the messages uses HTML.
$mail->Body = "Hello, <b>my friend</b>! \n\n This message uses HTML !";
$mail->AltBody = "Hello, my friend! \n\n This message uses HTML, but your email client did not support it !";

if(!$mail->Send()) // Now we send the email and check if it was send or not.
{
   echo 'Message was not sent.';
   echo 'Mailer error: ' . $mail->ErrorInfo;
}
else
{
   echo 'Message has been sent.';
}
?>

Step 4: Sending an email with attachements

Perhaps you need to attach something to your email, such as an image or an word document. Or perhaps you need to attach multiple files.

There are two ways of attaching something to your mail:

  • You can simply attach a file from the filesystem
  • or you can attach (binary) data stored in a variable.

The last one is called a Stringattachment. This makes it possible put extract data from a database and attach it to an e-mail, without having to save it as a file.

The command to attach a file can be placed anywhere between $mail = new PHPMailer() and $mail->Send() and it’s called AddAttachment($path);. This line will add an attachment to your email.

$path is the path of the filename. It can be a relative one or a full path to the file you want to attach.

If you want more options or you want to specify encoding and the MIME type of the file, then you can use 3 more parameters, all of which are optional:

AddAttachment($path,$name,$encoding,$type);

$name is an optional parameter, used to set the name of the file that will be embedded within the e-mail. The person who recieved your email will only see this name, rather than the original filename.

$encoding with this parameter you can set the type of encoding of the attachment. The default is base64.

$type is the MIME type of the attached file. This parameter makes it possible change the MIME type (MIME = Multipurpose Internet Mail Extensions) of an attachment from the default value of application/octet-stream (works with every kind of file) to a more specific MIME type, such as image/jpeg for a .jpg image.

String attachments work much like AddAttachment(), and is called with AddStringAttachment($string,$filename,$encoding,$type). The string data is passed to the method with the first parameter, $string. Because the string will become a standard file (which is what the attachment will be when received via email), the $filename parameter is required, it’s used to provide the filename for the string data.

So, why use AddStringAttachment instead of AddAttachment? Is it for text-only files? No, not at all. It’s primarily for databases. Data stored in a database is always stored as a string (or as a BLOB: Binary Large OBject). You could query your database for an image stored as a BLOG and pass the result to the AddStringAttachment.

If you want to attach multiple files (or strings), just call AddAttachment() or AddStringAttachment() multiple times.

Here is an example of howto attach a file to an email (using the HTML example above)

<?php

require("class.phpmailer.php");
$mail = new PHPMailer();

$mail->From = "from@example.com";
$mail->FromName = "Your Name";
$mail->AddAddress("myfriend@example.net"); // This is the adress to witch the email has to be send.
$mail->Subject = "An HTML Message";
$mail->IsHTML(true); // This tell's the PhPMailer that the messages uses HTML.
$mail->Body = "Hello, <b>my friend</b>! \n\n This message uses HTML !";
$mail->AltBody = "Hello, my friend! \n\n This message uses HTML, but your email client did not support it !";

$mail->AddAttachment("c:/temp/projectresults.zip", "results-october.zip")// attaching a file to the email

if(!$mail->Send()) // Now we send the email and check if it was send or not.
{
   echo 'Message was not sent.';
   echo 'Mailer error: ' . $mail->ErrorInfo;
}
else
{
   echo 'Message has been sent.';
}
?>

If you require additional information about sending emails using PHPMailer, or Emails in general you can find alot of usefull information about the subject here:

Related Posts

  1. it2051229 Said,

    useful!

  2. mk Said,

    great!

  3. xcvbcvb Said,

    sfgvs

  4. Sending emails with php - php tutorial « PHP Net Said,

    […] entry was written by admin. Bookmark the permalink. Follow any comments here with the RSS feed for this post.Content related […]

  5. cvxv Said,

    bvbc

  6. richard Said,

    Hi Admin, im really new with php as in 0% knowledge.Do I have to save every php document with php file extension?
    I have a ftp and smtp server but I dont know how to install the php file I downloaded from http://phpmailer.codeworxtech.com/ can you please enlighten me with this one. Thank you!

  7. woodjewe Said,

    http://arcmb.info/replica-watches/patek-philippe-replica-watches.php

  8. Mary Said,

    above this latter price, it was, by this statute, subjected to a purchasing money, but money can serve no other purpose besides

  9. sds Said,

    ddfds

  10. vnbnbnvnfjjjfjr Said,

    audi so”

    nnvnvnvufyyyfhfnCCvnvnvnvjffFDDDflvlvllvCCVvvmvmvmCCC

  11. Des The Worlds Worst Poker Player! Said,

    @ADMIN

    How about one of your tutorials about sending multiple emails with phpmailer.

    I am confy with linear PHP, but OOP is something I have steered cleared of thinking it will slow down my progession as a php programmer.

    How wrong was I!

    It would seem that OOP is the way of the future!

    So, hows about helping an old dog learn another new practical OOP imlementation?

    Des ;)

  12. brown Said,

    4KHOv8 sd80347yv35t8574dcu0r

  13. asd dad Said,

    adsa

  14. sss Said,

    aa

  15. djmuz Said,

    У тебя суперский сайт, мне он очень понравился! Продолжай в том же стиле! Добавил его в Избранное, да и всем советую. Предлагаю посетить на мою страничку

  16. vsemuz Said,

    Юзая по инету нашел на твой сайт, ох и офигенный же он!!! А посмотри мой

  17. Valentin Said,

    Сайт, да нет это целый портал - супер. Буду теперь постоянно посещать…. и всем советую… Кстати посмотри мой сайт

  18. mladci Said,

    Медицинская служба новостей поможет вам в мире медицины

  19. findusi Said,

    Мне понравился твой портал, конечно же я его внесу к себе в закладки и теперь каждый раз буду его посещать. Твой портал достойнный внимания с не только с части контента, но и просто с веселого дизайна. Предлагаю посетить мой портал

  20. worive Said,

    Благодарен за интересную информацию и твой сайт! Буду посещать!!! А чуть не забыл, my портал …..

  21. Valentina Said,

    Ну не фига себе, и интересный же твой портал!!! Твой в избранное добавил! Я буду рад, Заходи на сайт

  22. kotenok Said,

    Твой классный сайт,много видел сайтов, но этот меня зацепил. Добавлю пожалуй сайт в избранное. Верный курс держишь! Буду постоянно посещать этот сайт.
    Предлагаю посетить мой сайт

  23. strahs Said,

    Привет!У тебя суперский сайт, мне он очень понравился! Следуй этим же путем! Добавил его в Закладки, да и знакомым рекомендую. Да и тебе предлагаюзайти на мой сайт

  24. Anutka Said,

    Ох, и популярный же у тебя портал!!! Приглашаю на мой сайт

  25. rastorman Said,

    Привет! ты реальный молодец, что запустил такой портал! Уважуха тебе. Очень полезен он людям. Посмотри мой первыйпортал

  26. propiar Said,

    Влезая на гостевуху, решил оставить положительный отзыв тебе!!! гостевуха классная. Забегай на мой сайт

  27. pitermania Said,

    Привет! Твой Сайт, да нет это целый порталище - классный. Буду теперь каждый раз постоянно заходить…. И всем рекомендовать… Уже парочку друзьям в аську скинул. Кстати посмотри мой портальчик

  28. Gulzara Said,

    Хозяину респект! Прежде всего хочу поблагодаритьВас за создание этого портала , за проделанную работу. Портал заслуживает обязательного интереса! Приглашаю на мой портал

  29. transa Said,

    Я постоянно просматриваю сайты в инете и хочу поставить вам 5 за сделанную работу. Действительно интересный и суперский сайт. Спасибо автору. Большое человеческое. Нашел все что искал. Как повесить баннер? Так держать ребята. Если бы продавали сайт, то почем? А, чуть не забыл…. Глянька мой сайтик

  30. Olenka Said,

    Молодцы, ребята! Ваш сайт очень красив и удобен!!! Удачи вам ребята! Только бы почаще обновлялась целом, хотя и так нормально, очень интересный портал. И большое спасибо за ваше отношение к нам. Посмотри мой сайт

  31. lifeso Said,

    Здравствуйте!Мне Очень понравился этот сайт! Великолепно!. Как у вас хватило сил на такую кропотливую работу для публикаций текстов и вообще подбора всего материала?! Желаю вам “Так Держать!” и не останавливаться на достигнутом, у Вас хороший потенциал! Предлагаю заглянуть так же мой сайт.

  32. fatanito Said,

    Хороший сайтик, да и гостевая прикольная :) .

  33. kolanito Said,

    Зачётный сайтик, движок амописный? :) .

  34. svetiana Said,

    Хорошо на этом сайте пишут.

  35. Valentinka Said,

    Сайт, да нет это целый портал - с фишкой. Буду теперь постоянно посещать…. и всем советую...

  36. Dominges Said,

    Мимо такого сайта не пройдешь, и уж тем более не забудешь оставить отличный отзыв, как делают это все! сайта и я в правду нужный!

  37. Pusikis Said,

    Автору респект! Сайт заслуживает интереса!

Add A Comment