PHP sendmail Settings Print

  • 79

Using PHPMailer to Send Emails in PHP

1. Download PHPMailer script
To start, download PHPMailer using the following direct link:

PHPMailer-master.zip

Once downloaded, unzip and extract the contents to your public_html directory. After extraction, you will see a new folder: public_html/PHPMailer-master. The next step involves editing your web pages to incorporate the PHPMailer code.

2. Add the HTML form to your page
Typically, your setup will include a form sent to a PHP script for processing. In this case, we have a basic HTML file, contact_us.html, which contains a feedback form. Set the form's action to "email.php" to enable the PHP script to process it. Here's the necessary code for the form on your page:


<form method="post" action="email.php">
Email: <input name="email" id="email" type="text" /><br />

Message:<br />
<textarea name="message" id="message" rows="15" cols="40"></textarea><br />

<input type="submit" value="Submit" />
</form>

3. Replace the PHP mail() function code
When the form is submitted, the information is sent to "email.php", which initially uses PHP's mail() function to send the message. However, we will replace the PHP code that sends the email from the server with PHPMailer.

4. Add the PHPMailer code to your site
As we're using PHPMailer instead of the generic PHP mail() function, we need to update the "email.php" file. In your PHPMailer folder, you'll find a README file containing sample PHP code. The sample PHP code should look like this:


<?php
require("class.PHPMailer.php");

$mail = new PHPMailer();

$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "smtp1.example.com;smtp2.example.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "jswan"; // SMTP username
$mail->Password = "secret"; // SMTP password

$mail->From = "from@example.com";
$mail->FromName = "Mailer";
$mail->AddAddress("josh@example.net", "Josh Adams");
$mail->AddAddress("ellen@example.com"); // name is optional
$mail->AddReplyTo("info@example.com", "Information");

$mail->WordWrap = 50; // set word wrap to 50 characters
//$mail->AddAttachment("/var/tmp/file.tar.gz"); // add attachments
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional name
$mail->IsHTML(true); // set email format to HTML

$mail->Subject = "Here is the subject";
$mail->Body = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}

echo "Message has been sent";
?>

5. Final Configuration of the PHPMailer code
Here's the final PHP code, which incorporates the email and message data from the HTML form and the PHPMailer script:


<?php

// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;

// When we unzipped PHPMailer, it un

zipped to public_html/PHPMailer-master
require("public_html/PHPMailer-master/src/PHPMailer.php");
require("public_html/PHPMailer-master/src/SMTP.php");

$mail = new PHPMailer();

// set mailer to use SMTP
$mail->IsSMTP();

// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost"; // specify main and backup server

$mail->SMTPAuth = true; // turn on SMTP authentication

// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_PHPMailer@yourdomain.example.com
// pass: password
$mail->Username = "send_from_PHPMailer@yourdomain.example.com"; // SMTP username
$mail->Password = "password"; // SMTP password

// $email is the user's email address they specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
$mail->From = $email;

// below we want to set the email address we will be sending our email to.
$mail->AddAddress("your_email@example.com", "Your Name");

// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);

$mail->Subject = "You have received feedback from your website!";

// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body = $message;
$mail->AltBody = $message;

if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}

echo "Message has been sent";
?>

Now, when a user visits contact_us.html and submits their email address and message, the information is posted to email.php. The email.php script calls PHPMailer and sends the submitted data.

Keep in mind that PHPMailer is highly flexible and offers more features than described here. To explore optional variables and additional functionality, refer to the PHPMailer documentation.

6. Customizing your email content and settings

With PHPMailer, you can easily customize your email content and settings to improve the user experience and enhance email deliverability. Here are some examples of how you can modify the PHPMailer configuration:

a. Setting the email priority

You can set the priority of the email by using the `$mail->Priority` property. The priority can be set to a value from 1 to 5, with 1 being the highest priority and 5 the lowest.


$mail->Priority = 1; // Highest priority

b. Adding CC and BCC recipients

To add CC (carbon copy) and BCC (blind carbon copy) recipients, use the `AddCC()` and `AddBCC()` methods, respectively.


$mail->AddCC('cc@example.com', 'CC Recipient');
$mail->AddBCC('bcc@example.com', 'BCC Recipient');

c. Customizing the email header

You can add custom headers to the email using the `AddCustomHeader()` method.


$mail->AddCustomHeader('X-Custom-Header', 'Custom header value');

d. Enabling SMTP encryption

To improve the security of your email transmission, you can enable encryption using the `SMTPSecure` property. PHPMailer supports TLS and SSL encryption.


$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable SSL encryption

e. Error handling and debugging

PHPMailer provides error handling and debugging features. To display errors and debug messages, set the `SMTPDebug` property to an appropriate level:


$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Show server messages and client-server communication
$mail->SMTPDebug = SMTP::DEBUG_CLIENT; // Show only client messages

With these additional customizations, you can create a more robust and personalized email delivery system using PHPMailer. Remember to consult the PHPMailer documentation for a complete list of properties, methods, and features that you can use in your application.

f. Sending emails with attachments

PHPMailer allows you to send attachments along with your emails. To include attachments, use the `AddAttachment()` method:


$mail->AddAttachment('/path/to/file/file_name.pdf', 'file_name.pdf');
$mail->AddAttachment('/path/to/image/image_name.jpg', 'image_name.jpg');

g. Sending emails to multiple recipients

You can send emails to multiple recipients by calling the `AddAddress()` method multiple times:


$mail->AddAddress('recipient1@example.com', 'Recipient 1');
$mail->AddAddress('recipient2@example.com', 'Recipient 2');

h. Handling character encoding and localization

PHPMailer supports internationalization and localization. You can set the character encoding and language using the `CharSet` and `SetLanguage()` properties:


$mail->CharSet = 'UTF-8'; // Set character encoding to UTF-8
$mail->SetLanguage('en', 'path/to/language/files/'); // Set the language to English

i. Customizing error messages

PHPMailer allows you to customize error messages to make them more user-friendly. You can do this by modifying the `$ErrorInfo` property:


if (!$mail->Send()) {
echo "Message could not be sent. Please try again later.";
} else {
echo "Message has been sent";
}

j. Sending email using a third-party SMTP service

PHPMailer can also be configured to use third-party SMTP services like SendGrid, Mailgun, or Amazon SES. You can configure the SMTP settings by updating the following properties:


$mail->IsSMTP();
$mail->Host = 'smtp.sendgrid.net';
$mail->SMTPAuth = true;
$mail->Username = 'your_sendgrid_username';
$mail->Password = 'your_sendgrid_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587; // Update the port based on your SMTP provider

As you can see, PHPMailer is a highly customizable and powerful email sending library for PHP. By exploring the various features and settings it offers, you can create a reliable and efficient email delivery system for your applications. Make sure to consult the PHPMailer documentation to learn more about the available options and functionalities.

k. Embedding images in your HTML email

PHPMailer allows you to embed images directly into your HTML email, which can be useful for creating visually appealing content. To embed an image, use the `AddEmbeddedImage()` method:


$mail->AddEmbeddedImage('/path/to/image/logo.png', 'logo', 'logo.png');

Then, in your HTML email body, reference the image using the Content-ID (CID) you specified:


$mail->Body = '<h1>My Company</h1><img src="cid:logo" alt="Company Logo">';

l. Adding inline CSS styles

To style your HTML email content, you can add inline CSS styles directly to your email body:


$mail->Body = '<h1 style="color: #f00; font-size: 24px;">Hello World</h1>';

m. Using an external SMTP server

If your web hosting provider does not allow sending email using the built-in PHP mail function, you can use an external SMTP server to send email. Configure PHPMailer to use an external SMTP server like this:


$mail->IsSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;

n. Setting the email timeout

You can set a timeout for your email sending process using the `Timeout` property:


$mail->Timeout = 30; // Set the timeout to 30 seconds

o. Using an HTML template for your email content

Instead of hardcoding the HTML email content in your PHP script, you can use an external HTML template file. To load an HTML template, use the `msgHTML()` method:


$mail->msgHTML(file_get_contents('path/to/your/template.html'));

By exploring PHPMailer's extensive set of features, you can create a tailored and reliable email sending system for your applications. Be sure to consult the PHPMailer documentation for more detailed information on available properties, methods, and use cases. With the right combination of settings, you can ensure a consistent, high-quality email experience for your users.

p. Conditional email sending based on recipient preferences

In some cases, you may want to send emails to recipients based on their preferences. For example, you might have users who prefer plain text emails or only want specific types of notifications. To implement this, you can use conditional statements in your PHP script:


if ($user_prefers_plain_text) {
$mail->IsHTML(false);
$mail->Body = $plain_text_message;
} else {
$mail->IsHTML(true);
$mail->Body = $html_message;
}

q. Handling failed email deliveries

When sending emails, it's possible that some of them may fail to be delivered due to incorrect email addresses or other issues. To handle these cases, you can use the `getSMTPInstance()->getError()` method to log the failed delivery attempts:


if (!$mail->Send()) {
$error = $mail->getSMTPInstance()->getError();
// Log the error or perform any other action you'd like
}

r. Batch sending emails

To send emails in batches, you can use a loop in your PHP script. This can be particularly useful for sending newsletters or notifications to a large number of recipients:


$recipients = array(
array('email' => 'recipient1@example.com', 'name' => 'Recipient 1'),
array('email' => 'recipient2@example.com', 'name' => 'Recipient 2'),
// ...
);

foreach ($recipients as $recipient) {
$mail->AddAddress($recipient['email'], $recipient['name']);
if (!$mail->Send()) {
// Handle the error, log it, or perform any other action
}
$mail->ClearAddresses(); // Clear the recipient list for the next iteration
}

s. Personalizing email content

To make your emails more engaging, you can personalize the content based on the recipient's information. This can be achieved by replacing placeholders in your email content with the actual recipient data:


$template = "Hello {name},\n\nThis is a personalized message for you.";
$recipient_name = 'John Doe';
$message = str_replace('{name}', $recipient_name, $template);
$mail->Body = $message;

By leveraging the powerful features of PHPMailer, you can create a highly customized email sending system that caters to your application's specific requirements. This ensures an efficient and user-friendly experience for your recipients. Always refer to the PHPMailer documentation for further details on available options and use cases. With the right combination of features, you can build an email delivery system that is both reliable and adaptable to your needs.


Kas see vastus oli kasulik?

« Tagasi