Php mail error catch

php mail error catch

I've been using the PHP mail() function. If the mail doesn't send for any reason, I'd like to echo the error message. How would I do that? mail() returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise. It is important to note that just because the mail was accepted for. then, the most probably your SELinux is preventing PHP or the webserver from sending emails. This problem is mostly with Linux based machines.

Php mail error catch - thank

How to Test and Fix the php mail() Function

 

 

Test php mail() on your Web Server

1. Create a php test file using a text editor and save it e.g. as test.php:

 

<?PHP
$sender = '[email protected]';
$recipient = '[email protected]';

$subject = "php mail test";
$message = "php test message";
$headers = 'From:' . $sender;

if (mail($recipient, $subject, $message, $headers))
{
    echo "Message accepted";
}
else
{
    echo "Error: Message not accepted";
}
?>

 

2. Change the $sender and $recipient in the code.

3. Upload the php file to your webserver.

4. Open the uploaded php file in your browser to execute the php script.

5. The output show either "Message accepted" or "Error: Message not accepted".

chevron_right  Message accepted:

Open your mail client to see if the message was delivered to the specified email address.
(also check your spam folder!)

 

If the message was delivered:

  • Everything is fine - php mail is working.

 

If the message was not delivered:

  • Some provider don't allow external recipients when using php mail. Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.tld then the recipient's email should be [email protected]
  • Upload the modified php file and retry.
  • If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient).
  • Upload the modified php file and retry.
  • Contact your provider if it still does not work.
    Tell your provider that the standard php "mail()" function returns TRUE, but not mail will be sent.
    It's recommended to include the used php test script to show your provider, that the problem is not caused by the php script used.

 

chevron_right  Error: Message not accepted

 

php mail might not be enabled:

  • Login to your webserver configuration and check the php settings.
    Some php installations require that you setup a default sender in the php configuration first.

 

Some provider don't allow external recipients when using php mail:

  • Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.tld then the recipient's email should be [email protected]
  • Upload the modified php file and retry.
  • If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient).
  • Upload the modified php file and retry.

 

If you have checked the php settings, tried a local recipient and it's still not working:

  • Contact your provider if you are unable to enable php mail().
    Tell your provider that the standard php "mail()" function returns FALSE.
    It's recommended to include the used php test script to show your provider, that the problem is not caused by the php script used.
Disclaimer: The information on this page is provided "as is" without warranty of any kind. Further, Arclab Software does not warrant, guarantee, or make any representations regarding the use, or the results of use, in terms of correctness, accuracy, reliability, currentness, or otherwise. See: License Agreement
string[] $to, string $subject, string $message, string

Mail

Introduction

Laravel provides a clean, simple API over the popular SwiftMailer library. Laravel provides drivers for SMTP, Mailgun, Mandrill, Amazon SES, PHP's function, and , allowing you to quickly get started sending mail through a local or cloud based service of your choice.

Driver Prerequisites

The API based drivers such as Mailgun and Mandrill are often simpler and faster than SMTP servers. All of the API drivers require that the Guzzle HTTP library be installed for your application. You may install Guzzle to your project by adding the following line to your file:

Mailgun Driver

To use the Mailgun driver, first install Guzzle, then set the option in your configuration file to . Next, verify that your configuration file contains the following options:

Mandrill Driver

To use the Mandrill driver, first install Guzzle, then set the option in your configuration file to . Next, verify that your configuration file contains the following options:

SES Driver

To use the Amazon SES driver, install the Amazon AWS SDK for PHP. You may install this library by adding the following line to your file's section:

Next, set the option in your configuration file to . Then, verify that your configuration file contains the following options:

Sending Mail

Laravel allows you to store your e-mail messages in views. For example, to organize your e-mails, you could create an directory within your directory:

To send a message, use the method on the facade. The method accepts three arguments. First, the name of a view that contains the e-mail message. Secondly, an array of data you wish to pass to the view. Lastly, a callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message:

Since we are passing an array containing the key in the example above, we could display the user's name within our e-mail view using the following PHP code:

Note: A variable is always passed to e-mail views, and allows the inline embedding of attachments. So, you should avoid passing a variable in your view payload.

Building The Message

As previously discussed, the third argument given to the method is a allowing you to specify various options on the e-mail message itself. Using this Closure you may specify other attributes of the message, such as carbon copies, blind carbon copies, etc:

Here is a list of the available methods on the message builder instance:

Note: The message instance passed to a Closure extends the SwiftMailer message class, allowing you to call any method on that class to build your e-mail messages.

Mailing Plain Text

By default, the view given to the method is assumed to contain HTML. However, by passing an array as the first argument to the method, you may specify a plain text view to send in addition to the HTML view:

Or, if you only need to send a plain text e-mail, you may specify this using the key in the array:

Mailing Raw Strings

You may use the method if you wish to e-mail a raw string directly:

Attachments

To add attachments to an e-mail, use the method on the object passed to your Closure. The method accepts the full path to the file as its first argument:

When attaching files to a message, you may also specify the display name and / or MIME type by passing an as the second argument to the method:

Inline Attachments

Embedding An Image In An E-Mail View

Embedding inline images into your e-mails is typically cumbersome; however, Laravel provides a convenient way to attach images to your e-mails and retrieving the appropriate CID. To embed an inline image, use the method on the variable within your e-mail view. Remember, Laravel automatically makes the variable available to all of your e-mail views:

Embedding Raw Data In An E-Mail View

If you already have a raw data string you wish to embed into an e-mail message, you may use the method on the variable:

Queueing Mail

Queueing A Mail Message

Since sending e-mail messages can drastically lengthen the response time of your application, many developers choose to queue e-mail messages for background sending. Laravel makes this easy using its built-in unified queue API. To queue a mail message, use the method on the facade:

This method will automatically take care of pushing a job onto the queue to send the mail message in the background. Of course, you will need to configure your queues before using this feature.

Delayed Message Queueing

If you wish to delay the delivery of a queued e-mail message, you may use the method. To get started, simply pass the number of seconds by which you wish to delay the sending of the message as the first argument to the method:

Pushing To Specific Queues

If you wish to specify a specific queue on which to push the message, you may do so using the and methods:

Mail & Local Development

When developing an application that sends e-mail, you probably don't want to actually send e-mails to live e-mail addresses. Laravel provides several ways to "disable" the actual sending of e-mail messages.

Log Driver

One solution is to use the mail driver during local development. This driver will write all e-mail messages to your log files for inspection. For more information on configuring your application per environment, check out the configuration documentation.

Universal To

Another solution provided by Laravel is to set a universal recipient of all e-mails sent by the framework. This way, all the emails generated by your application will be sent to a specific address, instead of the address actually specified when sending the message. This can be done via the option in your configuration file:

Mailtrap

Finally, you may use a service like Mailtrap and the driver to send your e-mail messages to a "dummy" mailbox where you may view them in a true e-mail client. This approach has the benefit of allowing you to actually inspect the final e-mails in Mailtrap's message viewer.

Events

Laravel fires the event just before sending mail messages. Remember, this event is fired when the mail is sent, not when it is queued. You may register an event listener in your :

string[] $attachments Paths to files to attach. * } */ $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ); /** * Filters whether to preempt sending an email. * * Returning a non-null value will short-circuit {@see wp_mail()}, returning * that value instead. A boolean return value should be used to indicate whether * the email was successfully sent. * * @since 5.7.0 * * @param null

How to Send Emails in PHP?

We see numerous requests for guides on sending emails with some popular frameworks and libraries using an SMTP server, so we are launching a series of “how to” posts aimed at helping you painlessly configure the mail function in your application.

Today we are starting with PHP, one of the most popular web development languages.

PHP built-in mail function ()

There are two basic ways of sending emails with PHP: a built-in mail function and external mail packages.

PHP’s built-in mail function () is very simple, but it provides limited functionality for sending emails. You won’t be able to add attachments to your email, and building a beautiful HTML template with embedded images will be a tricky task as well. 

The other side of the PHP mail function () is that the email is sent from your web server, which may cause issues with deliverability due to security concerns such as suspicion of spam and blacklisting. The best way to overcome this problem is sending messages via an SMTP server, however, this functionality is limited as well. PHP mail() does not usually allow you to use the external SMTP server and it does not support SMTP authentication.

Here’s what you can do with PHP’s built-in mail function(): 

  • create simple HTML/text messages without attachments and images
  • send emails via localhost and Xmapp 
  • include several recipients with “$to” parameter. 

It is suitable for simple, mostly text-based notifications in your local environment. If you need to communicate with your app’s users, it is better to install an external mailer package.

If you are still committed to the PHP built-in mail function() and are ready to accept the challenge, let’s take a look at the basic code and its main parameters. 

Syntax and parameters

The PHP mail syntax is pretty simple:

It uses the following parameters: 

  • “$to” = your message recipient(s). The email address format may be [email protected] or User <[email protected]>. In general, it needs to comply with RFC 2822.
  • “$subject” = your message’s subject
  • “$message” = the body of your message. Lines should be separated with a CRLF (\r\n). Each line should not exceed 70 characters.
  • “[$headers]” = additional recipients of your message, which can be included in CC or BCC. 

Note that headers are optional, except for the “from” header: it must be specified, otherwise, you will receive an error message like Warning: mail(): “sendmail_from” not set in php.ini or custom “From:” header missing.
You can use additional headers to change the mail “From” address and set the “Reply to” address.

For more details and additional parameters, refer to the PHP documentation.  

Sending HTML email using PHP mail() function

The body of the message can be written in HTML. However, as we’ve mentioned above, it should be simple. In the PHP mail function(), the HTML part will look like this:

It’s important to remember that to send HTML mail, you need to set the Content-type header:

Simple Transmission Protocol (SMTP)

Where do I specify the SMTP settings? This is a fair question. Go to the PHP installation folder and configure them in the “php.ini” file. But this will only work for localhost or Xmapp like solutions because as we have already mentioned,  PHP mail function does not support SMTP authentication and doesn’t allow sending messages via external servers. 

There are some other, rather haphazard options but we won’t promote them here. Alternatively, we recommend using external PHP mail packages for sending emails via an external SMTP server.

Better yet, you can use Mailtrap Email Delivery and we’ll provide all the necessary SMTP settings for you. You just need to copy-paste the SMTP settings, verify your domain, and start sending.

Try Mailtrap Email Delivery for Free

Sending multiple emails

To send your message to multiple recipients, specify their email addresses in “$to” =  parameter separating them with comma(-s).  It’s the only suitable method with a native mail() function. If you need to send a large volume of messages in a loop, try an external mailing package. In the official PHP documentation,  PEAR::Mail is recommended. 

PHP mailing packages

As we have already mentioned, the native PHP mail() function has limited functionality when it comes to mass sending. For example, it is not designed for creating engaging email templates that may boost your next campaign or sending a large volume of emails.

But since PHP is still one of the most popular programming languages, it also doesn’t lack resources for sending mass emails. Here are several plugins that we can highly recommend:

Pear Mail

Pear Mail is a class that provides multiple interfaces for sending emails (which is stated in their documentation). 

Here is what you can do with Pear Mail: 

  • create complex HTML/text messages with attachments and inlined images (with Mail_Mime class)
  • send emails via PHP’s built-in mail() function, a sendmail program, or SMTP server
  • send multiple emails from a queue (with Mail_Queue class).

Pear documentation looks a bit complicated but it’s still informative, and you can find several tutorials. To be able to compare several mail packages, let’s review code for sending a standard booking confirmation email. It will contain HTML and text parts, a single attachment, and will be sent via an authenticated SMTP server. 

For email experiments, we will use Mailtrap, a fake SMTP server. It imitates a real SMTP server and traps your test email in the virtual inboxes. This way, your email samples will never go to the inboxes of the real customers.

Swift Mailer

Swift Mailer is another popular package for sending emails in PHP. It is feature-rich, well covered by documentation, and pretty straightforward in use.

Here is what you can do with Swift Mailer:

  • create complex HTML/multipart templates 
  • add attachments and embed images
  • send emails via authenticated SMTP, sendmail, Postfix, or your own transport
  • use additional plugins.

Besides that, Swift Mailer offers enhanced security and handles large attachments and images with low memory usage.

For more details, refer to the “How to Use Swift Mailer to Send Emails from PHP Apps” post. Below we will demonstrate a simple example of the same sending booking confirmation we used above.

PHPMailer

And finally, PHPMailer, which is the classic and the most popular email sending library for PHP. It deserves a separate article and a tutorial. You will find it here.

Here is what you can do with PHPMailer:

  • create complex HTML/multipart templates
  • add attachments and embedded images
  • send emails via authenticated SMTP.

PHPMailer is protected against header injection attacks and automatically validates emails.

Now let’s send our booking confirmation with PHPMailer:

But if you’d want to keep track of your emails’ deliverability, Mailtrap Email Delivery gives you the upper hand to determine which emails perform the best. Plus, we keep your Email logs for 60 days, so you easily inspect and debug emails when necessary.

What else should you know about PHP mail sending options?

In this article, we have described the basic PHP email sending principles, syntax, and parameters. Moreover, we have reviewed the main ways of sending emails with PHP: its built-in mail function and the most popular external mail packages. PHPMailer and Swift Mailer are standard libraries for PHP email sending today, and PEAR Mail is still widely used.

Undoubtedly, external libraries offer much more advanced solutions, like SMTP authentication support and a wide set of HTML related features. However, PHP mail function() can still be an option if you are sending plain text notification via localhost.

Also, you can find several additional packages to supplement your mail tools:

  • Stampie, an API Wrapper for email sending providers (SendGrid, MailGun, Mandrill, SparkPost, and Mailjet)
  • Mautic, an open-source email marketing automation software.

Choose your option according to your current needs and preferences, and don’t forget to test emails before moving to production!

Article byDiana LepilkinaContent Specialist @Mailtrap

PHP Exception Handling

❮ PreviousNext ❯


Exceptions are used to change the normal flow of a script if a specified error occurs.


What is an Exception

With PHP 5 came a new object oriented way of dealing with errors.

Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

This is what normally happens when an exception is triggered:

  • The current code state is saved
  • The code execution will switch to a predefined (custom) exception handler function
  • Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code

We will show different error handling methods:

  • Basic use of Exceptions
  • Creating a custom exception handler
  • Multiple exceptions
  • Re-throwing an exception
  • Setting a top level exception handler

Note: Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.


Basic Use of Exceptions

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block.

If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.

Lets try to throw an exception without catching it:

<?php
//create function with an exception
function checkNum($number) {
  if($number>1) {
    throw new Exception("Value must be 1 or below");
  }
  return true;
}

//trigger exception
checkNum(2);
?>

The code above will get an error like this:

Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Try, throw and catch

To avoid the error from the example above, we need to create the proper code to handle an exception.

Proper exception code should include:

  1. - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown"
  2. - This is how you trigger an exception. Each "throw" must have at least one "catch"
  3. - A "catch" block retrieves an exception and creates an object containing the exception information

Lets try to trigger an exception with valid code:

<?php
//create function with an exception
function checkNum($number) {
  if($number>1) {
    throw new Exception("Value must be 1 or below");
  }
  return true;
}

//trigger exception in a "try" block
try {
  checkNum(2);
  //If the exception is thrown, this text will not be shown
  echo 'If you see this, the number is 1 or below';
}

//catch exception
catch(Exception $e) {
  echo 'Message: ' .$e->getMessage();
}
?>

The code above will get an error like this:

Message: Value must be 1 or below

Example explained:

The code above throws an exception and catches it:

  1. The checkNum() function is created. It checks if a number is greater than 1. If it is, an exception is thrown
  2. The checkNum() function is called in a "try" block
  3. The exception within the checkNum() function is thrown
  4. The "catch" block retrieves the exception and creates an object ($e) containing the exception information
  5. The error message from the exception is echoed by calling $e->getMessage() from the exception object

However, one way to get around the "every throw must have a catch" rule is to set a top level exception handler to handle errors that slip through.



Creating a Custom Exception Class

To create a custom exception handler you must create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class.

The custom exception class inherits the properties from PHP's exception class and you can add custom functions to it.

Lets create an exception class:

<?php
class customException extends Exception {
  public function errorMessage() {
    //error message


    return $errorMsg;
  }
}

$email = "[email protected]";

try {
  //check if
  if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
    //throw exception if email is not valid
    throw new customException($email);
  }
}

catch (customException $e) {
  //display custom message
  echo $e->errorMessage();
}
?>

The new class is a copy of the old exception class with an addition of the errorMessage() function. Since it is a copy of the old class, and it inherits the properties and methods from the old class, we can use the exception class methods like getLine() and getFile() and getMessage().

Example explained:

The code above throws an exception and catches it with a custom exception class:

  1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
  2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
  3. The $email variable is set to a string that is not a valid e-mail address
  4. The "try" block is executed and an exception is thrown since the e-mail address is invalid
  5. The "catch" block catches the exception and displays the error message

Multiple Exceptions

It is possible for a script to use multiple exceptions to check for multiple conditions.

It is possible to use several if..else blocks, a switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:

<?php
class customException extends Exception {
  public function errorMessage() {
    //error message


    return $errorMsg;
  }
}

$email = "[email protected]";

try {
  //check if
  if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
    //throw exception if email is not valid
    throw new customException($email);
  }
  //check for "example" in mail address
  if(strpos($email, "example") !== FALSE) {
    throw new Exception("$email is an example e-mail");
  }
}

catch (customException $e) {
  echo $e->errorMessage();
}

catch(Exception $e) {
  echo $e->getMessage();
}
?>

Example explained:

The code above tests two conditions and throws an exception if any of the conditions are not met:

  1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
  2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
  3. The $email variable is set to a string that is a valid e-mail address, but contains the string "example"
  4. The "try" block is executed and an exception is not thrown on the first condition
  5. The second condition triggers an exception since the e-mail contains the string "example"
  6. The "catch" block catches the exception and displays the correct error message

If the exception thrown were of the class customException and there were no customException catch, only the base exception catch, the exception would be handled there.


Re-throwing Exceptions

Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a "catch" block.

A script should hide system errors from users. System errors may be important for the coder, but are of no interest to the user. To make things easier for the user you can re-throw the exception with a user friendly message:

<?php
class customException extends Exception {
  public function errorMessage() {
    //error message

    return $errorMsg;
  }
}

$email = "[email protected]";

try {
  try {
    //check for "example" in mail address
    if(strpos($email, "example") !== FALSE) {
      //throw exception if email is not valid
      throw new Exception($email);
    }
  }
  catch(Exception $e) {
    //re-throw exception
    throw new customException($email);
  }
}

catch (customException $e) {
  //display custom message
  echo $e->errorMessage();
}
?>

Example explained:

The code above tests if the email-address contains the string "example" in it, if it does, the exception is re-thrown:

  1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
  2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
  3. The $email variable is set to a string that is a valid e-mail address, but contains the string "example"
  4. The "try" block contains another "try" block to make it possible to re-throw the exception
  5. The exception is triggered since the e-mail contains the string "example"
  6. The "catch" block catches the exception and re-throws a "customException"
  7. The "customException" is caught and displays an error message

If the exception is not caught in its current "try" block, it will search for a catch block on "higher levels".


Set a Top Level Exception Handler

The function sets a user-defined function to handle all uncaught exceptions:

<?php
function myException($exception) {
  echo "<b>Exception:</b> " . $exception->getMessage();
}

set_exception_handler('myException');

throw new Exception('Uncaught Exception occurred');
?>

The output of the code above should be something like this:

Exception: Uncaught Exception occurred

In the code above there was no "catch" block. Instead, the top level exception handler triggered. This function should be used to catch uncaught exceptions.


Rules for exceptions

  • Code may be surrounded in a try block, to help catch potential exceptions
  • Each try block or "throw" must have at least one corresponding catch block
  • Multiple catch blocks can be used to catch different classes of exceptions
  • Exceptions can be thrown (or re-thrown) in a catch block within a try block

A simple rule: If you throw something, you have to catch it.


❮ PreviousNext ❯


Related Videos

PHP Try Catch Error Handling

Remarkable: Php mail error catch

Php mail error catch
Return without gosub error access
STEP ERROR CODE 80004005 COPY DATABASE
php mail error catch string[] $headers Additional headers. * @type string bool $return Short-circuit return value. * @param array $atts { * Array of the `wp_mail()` arguments. * * @type string string[] $to Array or comma-separated list of email addresses to send message. * @type string $subject Email subject. * @type string $message Message contents. * @type string string[])(Required)Array or comma-separated list of email addresses to send message.

$subject

(string)(Required)Email subject.

$message

(string)(Required)Message contents.

$headers

(string string[] $attachments = array() )


Description

A true return value does not automatically mean that the user received the email successfully. It just only means that the method used was able to process the request without any errors.

The default content type is which does not allow using HTML, php mail error catch. However, you can set fan error asus content type of the email by using php mail error catch ‘wp_mail_content_type’ filter.

The default charset is based on the charset used on the blog. The charset can be set using the ‘wp_mail_charset’ filter.


Top ↑

Parameters

$to

(string string[] $to, string $subject, string $message, string

0 Comments

Leave a Comment