PHPMailer tutorial
페이지 정보
작성자 차동박 쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 댓글 0건 조회 49,677회 작성일 11-09-13 19:30본문
December 14th, 2006 This is meant to be an improved version of the article written by PHPFreaks founder, Eric Rosebrock on the PHPFreaks site HERE, simply because I noticed the URL for that tutorial often was down, so I rewrote it (close to verbatim) for my own personal use. PHPMailer is by far the BEST way to add email functionality to your web site. Tutorials, Guides, Documentation, and HowTos
Other PHPMailer links
Some handy in-page links to help you navigate:IntroductionSending E-Mail through PHP can be simple, or it can be very complex depending on what you want to do. A standard plain-text E-Mail is what most developers resort to because building the MIME headers for HTML mail can be a difficult process. Those days have been over for quite some time with the amazing PHPMailer library that is available for free! In this tutorial, I will discuss in detail the features and possibilities you have when dealing with PHPMailer. RequirementsThe requirements of this tutorial are very limited. You only need PHP and the ability to send mail() function or an SMTP connection. You should also have a basic understanding of dealing with Object Oriented Programming (OOP) or at least how to follow the examples we'll use in this tutorial. Don't sweat it, this is going to be an easy tutorial for you to follow! About PHPMailerPHPMailer is a fully featured email transfer class for PHP that I would put above all of the other E-Mail handlers that I've used. It's popularity has grown rapidly over the past years that is has been around. Announced on the PHPMailer website on December 7, 2004, it has reached over 100,000 downloads! I hope you will want to increment that counter by reading this tutorial, and more importantly, learn how to enable E-Mail features you have only dreamed of! PHPMailer FeaturesAt the time this tutorial was written, here is a list of features currently available:
PHPMailer ContributorsThe following contributors to PHPMailer are:
I give these folks great respect for what they have done to speed up my development time on various projects in the past, including PHPFreaks.com! Preparing PHPMailer for UseLet's download, unpack and prepare PHPMailer! Downloading and UnpackingThe first thing you have to do is of course, download PHPMailer! You can get it at: http://phpmailer.sourceforge.net/ . Once you have the files downloaded, simply extract them into a directory. In this tutorial, we'll assume that your website is setup for this directory structure: /home/mywebsite/public_html/. Now, what you want to do is create a couple of directories for structuring your web area. I usually put libraries under 'lib' and then their name. So, we'll extract PHPMailer into /home/mywebsite/public_html/lib/phpmailer and the contents of this directory looks like this with the files in place: /home/mywebsite/public_html/lib /home/mywebsite/public_html/lib/phpmailer /home/mywebsite/public_html/lib/phpmailer/docs /home/mywebsite/public_html/lib/phpmailer/docs/extending.html /home/mywebsite/public_html/lib/phpmailer/docs/faq.html /home/mywebsite/public_html/lib/phpmailer/docs/timeoutfix.diff /home/mywebsite/public_html/lib/phpmailer/language /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-br.php /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-cz.php /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-de.php /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-en.php /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-es.php /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-fr.php /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-it.php /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-nl.php /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-no.php /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-se.php /home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-tr.php /home/mywebsite/public_html/lib/phpmailer/phpdoc /home/mywebsite/public_html/lib/phpmailer/phpdoc/allclasses-frame.html /home/mywebsite/public_html/lib/phpmailer/phpdoc/deprecated-list.html /home/mywebsite/public_html/lib/phpmailer/phpdoc/help-doc.html /home/mywebsite/public_html/lib/phpmailer/phpdoc/index-all.html /home/mywebsite/public_html/lib/phpmailer/phpdoc/index.html /home/mywebsite/public_html/lib/phpmailer/phpdoc/overview-tree.html /home/mywebsite/public_html/lib/phpmailer/phpdoc/packages.html /home/mywebsite/public_html/lib/phpmailer/phpdoc/phpmailer.html /home/mywebsite/public_html/lib/phpmailer/phpdoc/serialized-form.html /home/mywebsite/public_html/lib/phpmailer/phpdoc/stylesheet.css /home/mywebsite/public_html/lib/phpmailer/test /home/mywebsite/public_html/lib/phpmailer/test/phpmailer_test.php /home/mywebsite/public_html/lib/phpmailer/test/phpunit.php /home/mywebsite/public_html/lib/phpmailer/test/rocks.png /home/mywebsite/public_html/lib/phpmailer/ChangeLog.txt /home/mywebsite/public_html/lib/phpmailer/class.phpmailer.php /home/mywebsite/public_html/lib/phpmailer/class.smtp.php /home/mywebsite/public_html/lib/phpmailer/LICENSE /home/mywebsite/public_html/lib/phpmailer/README Now that we have those files in place, let's move on to creating our site configuration file! Creating and Using a Site Configuration FileOne of the things I like to do when I build a site is to create a configuration file that handles miscellaneous settings that I may need over and over again. So, I create a file called config.php in /home/mywebsite/public_html/config.php and I set it up with an array called $site with my keys and values the settings I use in the site. In this tutorial, I will cover how to define some settings we will use for the PHPMailer extender class. Here's a view of my configuration file: config.php <?php // Configuration settings for My Site // Email Settings $site['from_name'] = 'My Name'; // from email name $site['from_email'] = 'email@mywebsite.com'; // from email address // Just in case we need to relay to a different server, // provide an option to use external mail server. $site['smtp_mode'] = 'disabled'; // enabled or disabled $site['smtp_host'] = null; $site['smtp_port'] = null; $site['smtp_username'] = null; ?> The previous example should be very self explanatory, so we'll move on and cover those settings later on when we start to use them. The PHPMailer Extender ClassFirst, I want to emphasize, you do not need to create an extender class, but to make life easier for us, I'm going to show you how to anyways. The extender class will basically call the PHPMailer() class and then setup the basic values for you such as the Email address you want to send from, mail server settings and etc. Each of these settings are inherited by the config.php by default, but you may also overwrite them when you call our extender class. For example, if you do not define the settings in the extender class, they will be set by default and this in turn, allows you to setup the basic values without actually going through the motions every time. That's the beauty of it! Here's a look at our extender class: MailClass.inc <?php require_once($_SERVER['DOCUMENT_ROOT'].'/lib/phpmailer/class.phpmailer.php'); class FreakMailer extends PHPMailer { var $priority = 3; var $to_name; var $to_email; var $From = null; var $FromName = null; var $Sender = null; function FreakMailer() { global $site; // Comes from config.php $site array if($site['smtp_mode'] == 'enabled') { $this->Host = $site['smtp_host']; $this->Port = $site['smtp_port']; if($site['smtp_username'] != '') { $this->SMTPAuth = true; $this->Username = $site['smtp_username']; $this->Password = $site['smtp_password']; } $this->Mailer = "smtp"; } if(!$this->From) { $this->From = $site['from_email']; } if(!$this->FromName) { $this-> FromName = $site['from_name']; } if(!$this->Sender) { $this->Sender = $site['from_email']; } $this->Priority = $this->priority; } } ?> The PHP Mail ClassFreakMailer Class Code BreakdownThe FreakMailer class previously displayed is pretty simple. You only need a very basic understanding of Object Oriented Programming to use it, so let's break it down now. First, we are going to call the class.phpmailer.php file from within our phpmailer lib directory under the document root. This allows us to extend the PHPMailer class because it makes that object available. You could include this elsewhere, but this is a good place to do so. require_once($_SERVER['DOCUMENT_ROOT'].'/lib/phpmailer/class.phpmailer.php'); Class Control StructureNext, we define the class control structure and give our new class a name while extending the PHPMailer class. class FreakMailer extends PHPMailer { Class VariablesMoving along, we now setup the internal variables. Most of these are set to null by default so that we can do some triggering later on to determine if you want to overwrite the default values from the config.php file. var $priority = 3; var $to_name; var $to_email; var $From = null; var $FromName = null; var $Sender = null; Let's take a look at these values now:
Now that we have those variables defined, we can discuss the FreakMailer() function FreakMailer() FunctionThis is the function that basically sets up the default values for the PHPMailer to send E-Mail with. In other words, it's the whole reason we are using this class. First, we call the $site array from our config.php so that it can be used within this function and class. There are a couple of ways we can do this, we could point to it from outside of the class, or we can just global it. Using the global call is the easiest method and it works, so let's just do that! function FreakMailer() { global $site; // Comes from config.php $site array Next, we start the bulk of the operations here and start passing in values to the PHPMailer class. There's not much to explain here, if the internal value ($this->setting) of the setting is not defined after you instantiate the class, it basically calls it from the config.php and we'll use that instead. I mentioned earlier that you can override the values in the config.php and this is where those checks come into play. if($site['smtp_mode'] == 'enabled') { $this->Host = $site['smtp_host']; $this->Port = $site['smtp_port']; if($site['smtp_username']) { $this->SMTPAuth = true; $this->Username = $site['smtp_username']; $this->Password = $site['smtp_password']; } $this->Mailer = "smtp"; } if(!$this->From) { $this->From = $site['from_email']; } if(!$this->FromName) { $this->FromName = $site['from_name']; } if(!$this->Sender) { $this->Sender = $site['from_email']; } $this->Priority = $this->priority; } The most important thing you need to understand is that all of the functionality in the PHPMailer is still present and can be used even though we've extended the class. The only thing we've done here is created an extension (hence extends) that takes care of the repetitive stuff we don't want to do every time we need to send an E-Mail Now that we have a good understanding of the extender class, let's move along and start sending some E-Mail! Sending E-Mail with PHP Sending E-Mail with PHPMailerWe've done our work and we've got everything ready to go to start sending E-Mail with PHPMailer. Let's give it a go and see how everything works! Basic TestThis test is very important to this tutorial because we will be referring to this basic test code throughout the tutorial when I show you how to use different features with PHPMailer. If this test does not work for you, read through the tutorial again and keep trying until it does work, othewise you will be lost later on! Our first code example is going to be a file looks like this: <?php // Grab our config settings require_once($_SERVER['DOCUMENT_ROOT'].'/config.php'); // Grab the FreakMailer class require_once($_SERVER['DOCUMENT_ROOT'].'/lib/MailClass.inc'); // instantiate the class $mailer = new FreakMailer(); // Set the subject $mailer->Subject = 'This is a test'; // Body $mailer->Body = 'This is a test of my mail system!'; // Add an address to send to. $mailer->AddAddress('foo@host.com', 'Eric Rosebrock'); if(!$mailer->Send()) { echo 'There was a problem sending this mail!'; } else { echo 'Mail sent!'; } $mailer->ClearAddresses(); $mailer->ClearAttachments(); ?> Let's break down this file so that we have a good understanding of what it does. First, we are going to include our config.php file within the Document Root so that we have the $site settings available. // Grab our config settings require_once($_SERVER['DOCUMENT_ROOT'].'/config.php'); You could do this next step within the config.php file, but to make things easier, I chose not to. // Grab the FreakMailer class require_once($_SERVER['DOCUMENT_ROOT'].'/lib/MailClass.inc'); Next, we are going to call up our FreakMailer class and when we do this, we'll also initialize the PHPMailer class as well by the extends definition in the FreakMailer class. // instantiate the class $mailer = new FreakMailer(); Ok, so now we have PHPMailer ready to go with all of our default settings, let's go ahead and define a subject: // Set the subject $mailer->Subject = 'This is a test'; Now let's define the body of the message: // Body $mailer->Body = 'This is a test of my mail system!'; NOTE: Now, add an address to send to. The AddAddress accepts two inputs. The first is the E-mail address to send to and the second is the Name of the person you are sending to. // Add an address to send to. $mailer->AddAddress('foo@host.com', 'Eric Rosebrock'); Next, we send the message and look for an error: if(!$mailer->Send()) { echo 'There was a problem sending this mail!'; } else { echo 'Mail sent!'; } Obviously, if an error is detected, you will see There was a problem sending this mail!, otherwise you will see: Mail sent! Finally, we will clear the attatchment list and the Address list. This is primarily for sending Mailing lists, but I do it anyways as a (bad?) habit. $mailer->ClearAddresses(); $mailer->ClearAttachments(); ?> If you have just sent yourself an E-Mail with PHPMailer, then congratulations, you're on your way to sending E-Mail with PHP the easy way! Common ProblemsHere's a list of some common problems you may have with sending E-Mail through PHPMailer (these problems would probably be the same with the standard mail() function as well.).
Alright! If you haven't had any problems, let's move along to sending E-Mail with additional features. Let's move on to using some additional features in PHPMailer! Email with PHP - BCC, CC, Reply-TO, Multiple Recipients Using PHPMailer's Additional FeaturesIf you're at this point and you have not read the entire tutorial yet, please go back and read. We will be extending on the Basic Example from this point forward. PHPMailer has many features such as adding attachments, the ability to send a mailing list, multiple recipients, and much more. In this section of the tutorial, we're going to show you how to do most of those. Handling E-Mail AddressesPHPMailer supports many E-Mail address features, such as TO and FROM, multiple recipients, Carbon Copy (BCC), Reply-To addresses and more. Let's review how to utilize these features. Remember, we are building upon the Basic Example presented earlier in this tutorial, however you can generally apply these methods into any PHPMailer usage because these functions are in the main class. Adding the FROM AddressIn our file and our extender class, however you can override that at any time. Here's an example: $mailer->FromName = 'Your Name'; $mailer->From = 'You@yourdomain.com'; That was pretty simple! If you do not define the FromName by default in the class, it will show up as the E-Mail address in most clients. Adding a Reply-To AddressBy default the Reply-To address will be the FROM address unless you specify otherwise. That is simply E-Mail client intelligence. However, you can have the E-Mail come from one E-Mail address and any replies go to a different one. Here's how: $mailer->AddReplyTo('billing@yourdomain.com', 'Billing Department'); NOTE: Adding Multiple RecipientsThis method allows you to add multiple recipients to a single E-Mail address. I would not recommend this for anonymous mailing lists, or sending mailing lists. See later in this tutorial for a mailing list example. To add multiple Recipients, all you have to do is call the AddAddress function once for each E-Mail address you want to send to. Here's an example of three E-Mail addresses: NOTE: $mailer->AddAddress('recipient1@domain.com', 'First Person'); $mailer->AddAddress('recipient2@domain.com', 'Second Person'); $mailer->AddAddress('recipient3@domain.com', 'Third Person'); NOTE: Adding Carbon Copy CC RecipientsTo carbon copy (CC) recipients you can add them to the E-Mail going out by using the following methods. Just like the Adding Multiple Recipients example, you can add multiple CC recipients as well. $mailer->AddCC('recipient1@domain.com', 'First Person'); // More than one CC, just keep adding them! $mailer->AddCC('recipient2@domain.com', 'Second Person'); $mailer->AddCC('recipient3@domain.com', 'Third Person'); Adding Blind Carbon Copy BCC RecipientsThe "invisible" recipients or BCC can be added to an E-Mail going out by using the following methods. Just like the Adding Multiple Recipients example, you can add multiple BCC recipients as well. $mailer->AddBCC('recipient1@domain.com', 'First Person'); // More than one BCC, just keep adding them! $mailer->AddBCC('recipient2@domain.com', 'Second Person'); $mailer->AddBCC('recipient3@domain.com', 'Third Person'); Adding a Reply-To AddressBy default the Reply-To address will be the FROM address unless you specify otherwise. That is simply E-Mail client intelligence. However, you can have the E-Mail come from one E-Mail address and any replies go to a different one. Here's how: $mailer->AddReplyTo('billing@yourdomain.com', 'Billing Department'); NOTE: Adding Multiple RecipientsThis method allows you to add multiple recipients to a single E-Mail address. I would not recommend this for anonymous mailing lists, or sending mailing lists. See later in this tutorial for a mailing list example. To add multiple Recipients, all you have to do is call the AddAddress function once for each E-Mail address you want to send to. Here's an example of three E-Mail addresses: NOTE: $mailer->AddAddress('recipient1@domain.com', 'First Person'); $mailer->AddAddress('recipient2@domain.com', 'Second Person'); $mailer->AddAddress('recipient3@domain.com', 'Third Person'); NOTE: Requesting a Read ReceiptIf you want to request a Read Receipt from the person who receives the E-Mail, you can use the following setting: $mailer->ConfirmReadingTo = 'you@youdomain.com'; Now that we've covered E-Mail addresses, let's move along to sending the beloved HTML Mail! HTML Mail with PHP Sending HTML Mail with PHP and PHPMailerHTML Mail has proven to be one of the more complicated tasks when sending E-Mail through PHP. Setting the MIME types and building the boundaries of an HTML body are not easy to do and it takes some considerable research to get it right. However, PHPMailer has made life easy for us and I will show you how to do this now. Important Notes on HTML MailBefore we go to far into sending HTML mail, I want you to understand that it is important to know how images and files such as CSS and etc should be handled. A simple rule is to store them on the web server and file on the web server in your HTML that will be compiled and sent through the HTML Mail. If you go crazy and add a bunch of files to an E-Mail and try to call them within the E-Mail itself, you're in for one huge headache. An example of my HTML body would be something like: <html> <head> <title>My HTML Email</title> </head> <body> <br /> <h2>PHP Freaks Rules!</h2> <p>We invite you to visit <a href="http://www.phpfreaks.com" title="PHP Freaks">PHP Freaks.com</a> for a loving community of PHP Developers who enjoy helping each other learn the language!</p> <p>Sincerely,<br /> PHP Freaks Staff</p> In the previous example, I made every link a full URL and not a shortcut relative to my document root. If you do not do this, then your images and URLs will be broken! Moving along, now we are going to send the HTML mail by setting the body and a the isHTML setting in PHPMailer. Once again, this example expands upon the Basic Example earlier in this tutorial. $htmlBody = '<html> <head> <title>My HTML Email</title> </head> <body> <br /> <h2>PHP Freaks Rules!</h2> <p>We invite you to visit <a href="http://www.phpfreaks.com" title="PHP Freaks">PHP Freaks.com</a> for a loving community of PHP Developers who enjoy helping each other learn the language!</p> <p>Sincerely,<br /> PHP Freaks Staff</p>'; $mailer->Body($htmlBody); $mailer->isHTML(true); // Send the E-Mail Alternate Text Bodies For HTML MailYou should never rely on HTML only E-Mails if your message is important. Instead, you should do your recipient a favor and send a text-only version of the E-Mail along with the HTML body in case their E-Mail client cannot display the HTML version. We can accomplish this by defining the AltBody setting of the PHPMailer class. This setting will be the plain text version of your E-Mail and if it is set or Not Empty, the ContentType of the E-Mail is automatically set to multipart/alternative. Here's how you would do this: // setup the $mailer class $htmlBody = 'My HTML Body....'; $textBody = 'My text-only body....'; $mailer->Body($htmlBody); $mailer->isHTML(true); $mailer->AltBody($textBody); // Send the mail... Now two formats of E-Mail will be sent to the recipient. Let's move along to File Attachments with PHPMailer PHP File Attachements File Attachments in PHP Mail with PHPMailerSending file attachments is really easy to do. You simply add them to the attachment just like you would an address, cc, bcc or reply-to, except using the proper function. See the example below: // Setup mail class, recipients and body $mailer->AddAttachment('/home/mywebsite/public_html/file.zip', 'file.zip'); The AddAttachment function has four arguments: AddAttachment(PATH_TO_FILE, FILENAME, ENCODING, HEADER_TYPE) The PATH_TO_FILE is naturally the full path of the header you want to send. Application/octet-stream is default. That was pretty easy! Let's move along to using SMTP servers and utilizing diferent types of local E-mail SMTP servers. SMTP Servers with PHP Mail Using External SMTP Server(s) with PHP MailFirst, let's discuss using external SMTP servers instead of localhost. In this tutorial, we setup a config.php file. Inside this file, we have a few options for SMTP servers. If you want to simply enable one more more SMTP servers, you can do so through this configuration file by setting $site['smtp_enabled'] = 'enabled'; In the $site['smtp_host'] setting you can have a list of SMTP servers to send through delimited by a semicolon: From my understanding of this SMTP setting, PHPMailer will send E-Mail through the main host first and if it cannot connect, it will go to the next one in the list. NOTE: One important thing to note about sending through SMTP is that instead of using the standard Send() function, you will use SMTPSend(); Example: // Class and mail body setup here.... // See basic Example. // Non SMTP Mode: // $mailer->Send(); // SMTP Mode: $mailer->SmtpSend(); SMTP Mail ProblemsThere are many things that can go wrong with sending mail through SMTP and most of the problems come from permission issues.
NOTE: Taking Advantage of qmail and Sendmail with PHP MailIf you want to bypass the PHP Mail server and then PHPMailer will execute that Binary which could possibly speed things up quite a bit. qmail Example: // Setup Mail class and features $mailer->IsQmail(); $mailer->Send(); Sendmail Example: // Setup Mail class and features $mailer->IsSendmail(); $mailer->Send(); That was pretty easy! Let's move along to creating a simple Mailing list with PHPMailer! PHP Mailing List Example PHP Mailing List ExampleNow that you have a good understanding of the PHPMailer and how it works, let's discuss some Mailing List features. A few considerations you may have about sending mailing lists are customizable subjects, bodies and possibly even content. More importantly, is the ability to hide the E-Mail addresses of everyone else on the list from each other. This example assumes that you already have some sort of database setup for mailing list users and you know how to connect to MySQL and query data. If you don't know how to do that, then there's some tutorials on this site that can help you get to this point. For now, we'll assume that we have something of the following table structure:
Let's assume that you have 50 users in your database and you want to E-Mail them all a customizable E-Mail. The following code will accomplish this for you: <?php // Grab our config settings require_once($_SERVER['DOCUMENT_ROOT'].'/config.php'); // Grab the FreakMailer class require_once($_SERVER['DOCUMENT_ROOT'].'/lib/MailClass.inc'); // Setup body $textBody = "Dear {MEMBER_NAME},\n\nCheck out PHP Freaks: http://www.phpfreaks.com\n\nSincerely,\nAdmin"; $htmlBody = "Dear {MEMBER_NAME},<br /><br />Check out PHP Freaks: http://www.phpfreaks.com<br /><br />Sincerely,<br />Admin"; // instantiate the class $mailer = new FreakMailer(); // Get the user's Email $sql = mysql_query("SELECT FirstName,LastName,EmailAddress,MailType FROM users WHERE 1"); while($row = mysql_fetch_object($sql)) { // Send the emails in this loop. $member_name = $row->FirstName; if(!empty($row->LastName)) { $member_name .= ' '.$row->LastName; } if($row->MailType == 'html') { $mailer->Body = str_replace('{MEMBER_NAME}', $member_name, $htmlBody); $mailer->IsHTML(true); $mailer->AltBody = str_replace('{MEMBER_NAME}', $member_name, $textBody); } else { $mailer->Body = str_replace('{MEMBER_NAME}', $member_name, $textBody); $mailer->isHTML(false); } $mailer->Send(); $mailer->ClearAddresses(); $mailer->ClearAttachments(); $mailer->IsHTML(false); echo "Mail sent to: $member_name<br />"; } ?> PHP Mailing List Code BreakdownLet's break this code down for further understanding. The first portion is just like our basic example earlier in this tutorial. It includes the scripts we need to instantiate the class. <?php // Grab our config settings require_once($_SERVER['DOCUMENT_ROOT'].'/config.php'); // Grab the FreakMailer class require_once($_SERVER['DOCUMENT_ROOT'].'/lib/MailClass.inc'); Next, we will go ahead and file_get_contents() function to read these into the script, but to keep it simple here, we just use a small string instead. Notice the {MEMBER_NAME} placeholders that I have put into these examples. Later when we loop through the users, we'll str_replace() this with their actual information. // Setup body $textBody = "Dear {MEMBER_NAME},\n\nCheck out PHP Freaks: http://www.phpfreaks.com\n\nSincerely,\nAdmin"; $htmlBody = "Dear {MEMBER_NAME},<br /><br />Check out PHP Freaks: http://www.phpfreaks.com<br /><br />Sincerely,<br />Admin"; Next, we will go ahead and get our Mail class ready: // instantiate the class $mailer = new FreakMailer(); Now, this is where you will have to create your own tables and get your own data. This is a simple mysql_fetch_object() // Get the user's Email $sql = mysql_query("SELECT FirstName,LastName,EmailAddress,MailType FROM users WHERE 1"); while($row = mysql_fetch_object($sql)) { Now, this is where the heart of the E-Mail sending occurs. This is extremely important for you to pay attention here. The first portion of the code will basically create the $member_name string which will contain this specific user's information for this portion of the loop. $member_name = $row->FirstName; if(!empty($row->LastName)) { $member_name .= ' '.$row->LastName; } Our Mail preferences. If the user's MailType is set to 'html' in the database, then we'll send them an HTML E-Mail with a plaintext alternative body. Otherwise (else) we'll send them just a plain text E-Mail. if($row->MailType == 'html') { $mailer->Body = str_replace('{MEMBER_NAME}', $member_name, $htmlBody); $mailer->IsHTML(true); $mailer->AltBody = str_replace('{MEMBER_NAME}', $member_name, $textBody); } else { $mailer->Body = str_replace('{MEMBER_NAME}', $member_name, $textBody); $mailer->isHTML(false); } Please analyze the code above until you understand it. This information was previously discussed in this tutorial and you should be familiar with how to send Plain Text and HTML E-Mails. Finally, we send out the E-Mail and then clear the addresses from the $mailer object as well as any attachments you may have. $mailer->Send(); $mailer->ClearAddresses(); $mailer->ClearAttachments(); $mailer->IsHTML(false); echo "Mail sent to: $member_name<br />"; NOTE: SummaryThis tutorial should have given you a good push in the right direction to making life easier with sending E-Mail through PHP. Thanks to the excellent PHPMailer class and the developers of it, we can now send E-Mail without memorizing or constantly looking up headers when we need to send more complexe E-Mails. If you set this Mail portions and move on to more complicating things without wasting your time. PHPMailer ResourcesI hope you take the PHPMailer FAQ. It is important to understand this class and read what the Developers have said about it. In addition, there is another great tutorial and some examples for PHPMailer on their website. Good luck!-phpfreak Tags: Username, admin, GET, Examples, Port, HTTPS SSL, Scripts, server, HTTP Headers, tutorial
|
첨부파일
- PHPMailer_5.2.0.zip (235.9K) 28회 다운로드 | DATE : 2011-09-13 19:56:18
관련링크
댓글목록
등록된 댓글이 없습니다.