How to send emails from a site using the php mail function

Server applications that support email features distribute messages using a PHP function called php mail(). While most popular web applications (such as WordPress) include the necessary coding to distribute email using php mail(), you can also manually call the function from a web page or the server command line.

Note: some knowledge of the PHP scripting language is required to use php mail (). In this document, we’ll illustrate basic steps but be sure to read the function’s full documentation at the PHP web site.

Send an email from the server command line

If you have Secure Shell access to the server (VPS hosting only), you can use php mail () to send email from the command line. Read this HostPapa knowledge base article to learn more about accessing your server using SSH.

The code below uses the “From” email defined in a php.ini file to send an email to papa@hostpapa.com with a subject that reads “Test subject” and a message (email body) that reads “This is our test message”.

Once you’ve logged in to your server via SSH, enter the following code to launch PHP’s Interactive Shell:

php –a
SSH terminal
Now enter the following command:

mail ('papa@hostpapa.com', "Test subject", "This is our test message");

PHP mail

 

 

Send an email using a PHP script

A more common example is to use a PHP script to launch the email function. Here’s an example script using code from the php.net documentation as a template.  This performs the same email task as we completed using the command line. Note that in the script below, the message is passed to the php mail () function as a variable.

<?php
 // The message
 $message = "This is our test message";

// Send
 mail('papa@hostpapa.com', 'Test subject', $message);
 ?>

Note that php mail does not use SMTP by default. HostPapa recommends using SMTP authentication to send emails whenever possible. The PEAR mail package could be used to add SMTP functionality to the php mail () function, or if you’re looking for a WordPress plugin to allow you to send emails using SMTP, check out this HostPapa knowledge base article: How to send email in WordPress with SMTP.

If you are looking to add contact forms, check the article How to create a PHP contact form for your website.

 

For further questions or if you need help, please open a support ticket from your HostPapa Dashboard. Follow this link to learn how.

Was this article helpful?

[was-this-helpful]

Related Articles

Leave A Comment?