My HTML email

Sending emails with PHP using mail() function

PHP mail() function is a built-in function in PHP that allows sending email using a local sendmail program.

Whenever you call the mail() function, it invokes a local sendmail program. If your website is hosted on an online server, the sendmail program is usually configured by default by the system administrator.

The sendmail package is also in-built in local servers (eg. XAMPP, WAMPP, easyPHP etc). However, it is not enabled by default and it will need to be configured in order to work.

The mail() function allows you to send emails directly from a script.

Syntax

This is what you need to start sending emails via the mail() function:

Breaking it Down

to

This is a required parameter specifying the email recipient. It should be a valid email address to which the email is sent eg. john@webdevsplanet.com.

Ways in which you can set the to parameter:

Subject

This is a single line of text that gives a summary of what the email is about. It is a required parameter and cannot contain any newline characters.

Message

This is a required parameter that defines the actual message of the email. The message can be either plain-text or HTML format.

i). Plain-text message
For plain-text message, each line should be separated with a LF ( ) and should not exceed 70 characters length.

In case the message has longer lines than 70 characters, use the wordwrap() function.

The wordwrap() function wraps a string into new lines when it reaches a specific length (ie, it adds “ ” characters).

Having our message held in a variable named $msg, we use the wordwrap() function below to break our message into new lines after every 70 characters length.

If a full stop is found at the beginning of a line in the message, it might be removed. To solve this problem, replace the full stop with a double dot:

ii). HTML message
When sending a HTML formatted message you need to set the Content-Type to “text/html” using a header. This will tell the recipient mail client that the received message content is in HTML format and it should be rendered as so. If you omit this header the message will be rendered as plain-text with HTML tags.

 

Single quotes(') works pretty much the same as the double quotes(") in the above examples to enclose the message ($msg) string.

However, you are likely to use quotes within the body of your message. In this case you will need to escape them to avoid errors. Use double quotes to enclose your message in case your message contains single quotes in it and vise versa.

Using variables within the message
You can add variables within your message in a number of ways.

 is a student from "; //Method 4 $message = $name, " is a ", $course, " student from ", $country; ?> 

Using heredoc instead of quotes

I said above that when your message string contains a single quote in it you should use double quotes to enclose in and vice versa.

But what if the message string contains both single and double quotes in it?

HEREDOC comes to your rescue.

The heredoc is a string method for multi-line strings and an alternative to using quotes. It is preferable because it allows the usage of both single and double quotes within your string.

The closing identifier must begin in the first column of the line. The line with the closing identifier must contain no other characters, except a semicolon (;), ie, make sure that there is no space before EOD; or after it.

headers

Headers are an an optional parameter in mail() function used to pass extra and vital information such as:
- Sender address
- Reply-to address
- Carbon copy (Cc)
- Blind carbon copy(Bcc)
- Content-type
- MIME-Version
- PHP version
- etc

When using multiple headers, always separate them with a CRLF ( ).

If outside data are used to compose this header, the data should be sanitized so that no unwanted headers could be injected.

Example of setting headers:

" . "\r\n"; $headers .= "Reply-To: email@example.com" . "\r\n"; $headers .= "Cc: recipient2@example.com" . "\r\n"; $headers .= "Bcc: recipient3@example.com" . "\r\n";

Parameters

This is an optional parameter that specifies an additional parameter to the sendmail program. You will rarely need to use so we won't use it in our examples.

Examples

We have multiple working examples which you can copy and use in your projects to do tests.

You need to upload the code to an online hosted server or configure the sendmail appropriately in your local server (XAMPP, WAMPP, EasyPHP etc) for it to work.

Note:
Remember to replace the dummy data in the examples with your valid details for them to work.

All successful sending of emails with print out “Message sent successfully” while the failed ones will print out “Message was not sent”.

In case you don't find the emails in the inbox after sending, kindly check also in the spam/junk folder.

Example 1: Sending Plain-text email

Example 2: Sending HTML email

   

This email contains HTML Tags!

First NameJohn
Last NameDoe
Emailemail@example.com
"; $mail = mail($to,$subject,$msgbody,$headers); if($mail) < echo "Message sent successfully"; > else < echo "Oops! An error occurred. Try again later."; > ?>

Example 3: Sending an email with variables in the message body and heredoc message string formating.

"; $subject = "Contact form submission"; $headers = "MIME-Version: 1.0". "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8". "\r\n"; $headers .= "X-Mailer: PHP /".phpversion(). "\r\n"; $headers .= "From: ". "\r\n"; $headers .= "Reply-To: $email". "\r\n"; $message =     

Hi Admin,
The following details were submitted by a website visitor:

First Name$firstname
Last Name$lastname
Phone$phone
Email$email
EOD; $mail = mail($to,$subject,$msgbody,$headers); if($mail) < echo "Message sent successfully"; > else < echo "Oops! An error occurred. Try again later."; > ?>

You can customize the HTML messages with embedded or inline CSS to improve their look and feel to look more attractive and to present your brand.

Example 4: Sending email from contact form

      
Hi Admin!

The message below was sent through contact form:

Sender Details:
Name: $name
Email: $email
Phone: $phone

Subject: $subject

Message:
$message

EOD; $to = "Admin Name "; $headers = "MIME-Version: 1.0"."\r\n"; $headers .= "Content-type:text/html;charset=UTF-8"."\r\n"; $headers .= "X-Mailer: PHP /".phpversion()."\r\n"; $headers .= "From: "."\r\n"; $headers .= "Reply-To: $email"."\r\n"; $mail = mail($to,$subject,$msgbody,$headers); if($mail) < $msg = "Message sent successfully"; > else < $msg = "Oops! An error occurred. Try again later."; > > ?>

All the fields are required

" method="post">

We collect the form inputs (name, email, phone, subject and message) using HTTP post method upon clicking of “Send message” button and send them to the recipient email address.

“ ” in action attribute of the opening form tag simply echos out the file name of the current page. We use the filename of this page because the PHP script handling our form is on the same page.

In case you want to send the email via an external php script, assign the action attribute with the name of the php file(eg. “ action = 'sendmail.php'”) or file path in case the file is in a different directory/folder(eg. “ action = 'path/to/file/sendmail.php'”).

Below is the form that we just created with the above code. I have set it to send email to your account email address when you click the “Send Message” button.

Note:
Though the PHP mail() function looks pretty much simple to work with, as a general opinion many people do not encourage its usage due to some of these reasons:

  • Wrong format of mail header or content (e.g. differences in line break between Windows/Unix).
  • Errors in the format of header or content can easily cause the mails to be treated as SPAM. In most cases, emails sent via default php mail() function lands in the spam folder.
  • PHP mail() function sends emails using a local sendmail program on Linux, BSD and OS X platforms. However, Windows usually doesn't include a local mail server and thus the function won't work on a windows server. Also when using local servers such as XAMPP or WAMPP it will require some more configurations to work.

According to the official PHP.net manual, mail() function is not suited for sending any substantial amount of emails.

Note

It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient.

For the sending of large amounts of email, see the » PEAR::Mail, and » PEAR::Mail_Queue packages.

Personally, I began by sending emails using the mail() function but later changed to PHPMailer, a free/open-source php mailing library.

The mailing libraries have SMTP integration that allows email sending without a local mail server. Examples of these libraries are PHPMailer and Swiftmailer among others.

Источник

PHP mail() Function

The mail() function allows you to send emails directly from a script.

Syntax

Parameter Values

Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters.

Windows note: If a full stop is found on the beginning of a line in the message, it might be removed. To solve this problem, replace the full stop with a double dot:
$txt = str_replace("\n.", "\n..", $txt);
?>

Note: When sending an email, it must contain a From header. This can be set with this parameter or in the php.ini file.

Technical Details

Return Value: Returns the hash value of the address parameter, or FALSE on failure. Note: Keep in mind that even if the email was accepted for delivery, it does NOT mean the email is actually sent and received!
PHP Version: 4+
PHP Changelog: PHP 7.2: The headers parameter also accepts an array
PHP 5.4: Added header injection protection for the headers parameter.
PHP 4.3.0: (Windows only) All custom headers (like From, Cc, Bcc and Date) are supported, and are not case-sensitive.
PHP 4.2.3: The parameter parameter is disabled in safe mode
PHP 4.0.5: The parameter parameter was added

More Examples

Send an email with extra headers:

$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";

$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML email";

$message = "


This email contains HTML Tags!

Firstname Lastname
John Doe



";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: ' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

Источник

Читайте также:  Php magic quotes gpc is deprecated
Оцените статью