- Sendmail in PHP using mail(), SMTP with Phpmailer
- Quick Example
- PHP mail()
- Syntax
- Parameters
- Return Values
- PHP sendmail – configurations
- Examples to Sendmail in PHP
- Sendmail in PHP to send plaintext content
- PHP Sendmail code to send HTML content
- Sendmail in PHP to attach files
- Sendmail on form submit
- PHP sendmail via SMTP
- Related function to sendmail in PHP
- Conclusion
- How to send email with SMTP in php
- 4 Answers 4
Sendmail in PHP using mail(), SMTP with Phpmailer
Sendmail in PHP is possible with just single line of code. PHP contains built-in mail functions to send mail.
There are reasons why I am feeling embraced with this PHP feature. Because I write lot of code for sending mails regularly. PHP really saves our time with its built-ins.
Quick Example
In this tutorial, we will see how to add code to sendmail in PHP. We will see several examples in this to enrich the features with more support.
The below list examples we are going to see below. It will cover basic to full-fledged support to sendmail in PHP.
- Simple text mail with PHP mail().
- Send rich-text content via mail.
- Sendmail in PHP with attachments.
- Sendmail using PHPMailer with SMTP.
PHP mail()
The PHP mail() is to sendmail from an application. Let’s see the PHP configurations required to make the mail() function work. Also, we will see the common syntax and parameters of this PHP function below.
Syntax
mail( string $recipient_email, string $subject, string $message, array|string $headers = [], string $additional_params = "" )
Parameters
$recipient_email
One or more comma-separated value that is the target mail addresses. The sample format of the values are,
$subject
Mail subject. It should satisfy RFC 2047.
$message
Mail content body. It uses \r\n for passing a multi-line text. It has a character limit of 70 for a line. It accepts various content types depends on the specification in the extra header.
$headers
This is an extra string or array append to the mail header. Use to pass the array of specifications like content-type, charset and more. It’s an optional parameter. It uses \r\n to append multiple headers. The header array contains key-value pair to specify header name and specification respectively.
$additional_params
This is also optional. It is to pass extra flags like envelope sender address with a command-line option.
Return Values
This function returns boolean true or false based on the sent status of the mail. By receiving boolean true that doesn’t mean the mail was sent successfully. Rather, it only represents that the mail sending request is submitted to the server.
PHP sendmail – configurations
We have to configure some directives to make the mail script work in your environment.
Locate your php.ini file and set the mail function attributes. The below image shows the PHP configuration of the mail function.
Set the mail server configuration and the sendmail path with this php.ini section. Then restart the webserver and ensure that the settings are enabled via phpinfo().
Examples to Sendmail in PHP
Sendmail in PHP to send plaintext content
This is a short example of sending plain text content via PHP Script. It sets the mail subject, message and recipient email parameter to sendemail in PHP.
This program print response text based on the boolean returned by the mail() function.
PHP Sendmail code to send HTML content
Like the above example, this program also uses the PHP mail() function to send emails. It passes HTML content to the mail function.
For sending HTML content, it sets the content type and other header values with the mail header.
Sendmail in PHP with HTML content. '; if (mail($to, $subject, $message, $headers)) < echo 'Mail sent successfully.'; >else < echo 'Unable to send mail. Please try again.'; >?>
Sendmail in PHP to attach files
This program attaches a text file with the email content. It reads a source file using PHP file_get_contents(). It encodes the file content and prepares a mail header to attach a file.
It sets content-type, encoding with the message body to make it work. This script uses the optional $header variable on executing sendmail in PHP.
\r\n"; $headers .= "Content-Type: multipart/mixed; boundary=\"" . $divider . "\"\r\n"; $headers .= "Content-Transfer-Encoding: 7bit\r\n"; // prepare mail body with attachment $message = "--" . $divider. "\r\n"; $message .= "Content-Type: application/octet-stream; name=\"" . $file . "\"\r\n"; $message .= "Content-Transfer-Encoding: base64\r\n"; $message .= "Content-Disposition: attachment\r\n"; $message .= $encodedContent. "\r\n"; $message .= "--" . $divider . "--"; //sendmail with attachment if (mail($to, $subject, $message, $headers)) < echo 'Mail sent successfully.'; >else < echo 'Unable to send mail. Please try again.'; >?>
Sendmail on form submit
Instead of static values, we can also pass user-entered values to the PHP sendmail. An HTML form can get the values from the user to send mail. We have already seen how to send a contact email via the form.
This example shows a form that collects name, from-email and message from the user. It posts the form data to the PHP on the submit action.
The PHP reads the form data and uses them to prepare mail sending request parameters. It prepares the header with the ‘from’ email. It sets the mail body with the message entered by the user.
All the form fields are mandatory and the validation is done by the browser’s default feature.
else < $responseText = 'Unable to send mail. Please try again.'; >> ?> body < font-family: Arial; width: 550px; >.response-ribbon < padding: 10px; background: #ccc; border: #bcbcbc 1px solid; margin-bottom: 15px; border-radius: 3px; >input, textarea < padding: 8px; border: 1px solid #ccc; border-radius: 5px; >#Submit-btn < background: #1363cc; color: #FFF; width: 150px; >#email-form < border: 1px solid #ccc; padding: 20px; >.response-ribbon ?> 
PHP sendmail via SMTP
PHP mail() function has some limitation. To have a full-fledge functionality to sendmail in PHP, I prefer to use the PHPmailer library.
This library is one of the best that provides advanced mailing utilities. We have seen examples already to sendmail in PHP using PHPMailer via SMTP. If you are searching for the code to sendmail using OAuth token, the linked article has an example.
This example uses a minimal script to sendmail in PHP with PHPMailer via SMTP. It loads the PHPMailer library to create and set the mail object.
The mail object is used to configure the mail parameters. Then it invokes the send() method of the PHPMailer class to send mail.
Download PHPMailer from Github and put it into the vendor of this example directory. Replace the SMTP configurations in the below script to make this mail script working.
SMTPDebug = 0; $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = ""; $mail->Password = ""; $mail->SMTPSecure = "ssl"; $mail->Port = 465; $mail->From = "test@testmail.com"; $mail->FromName = "Full Name"; $mail->addAddress("recipient@email.com", "recipient name"); $mail->isHTML(true); $mail->Subject = "Mail sent from php send mail script."; $mail->Body = "Text content from send mail."; $mail->AltBody = "This is the plain text version of the email content"; try < $mail->send(); echo "Message has been sent successfully"; > catch (Exception $e) < echo "Mailer Error: " . $mail->ErrorInfo; > ?>
Related function to sendmail in PHP
The PHP provides alternate mail functions to sendmail. Those are listed below.
- mb_send_mail() – It sends encoded mail based on the language configured with mb_language() setting.
- imap_mail() – It allows to sendmail in PHP with correct handling of CC, BCC recipients.
Conclusion
The mail sending examples above provides code to sendemail in PHP. It supports sending various types of content, file attachments in the mail.
The elaboration on PHP in-built mail() function highlights the power of this function.
Hope this article will be helpful to learn more about how to sendmail in PHP.
Download
How to send email with SMTP in php
I want to send email with SMTP in my project, previously i write php mail() in my project but now my client want that i should use SMTP . I search about this but i get nothing any proper solution for this. In my php mail() i send name, subject and comment, so how can i do this in SMTP . Here is my code:
$payer_email = "Your Email"; $subject = "Your Subject"; $message = 'Dear '.$name.', Thank you for your purchase from '.$site_url.'. The details of your purchase are below. Transaction ID: '.$txn_id.' Item Name: '.$item_name.' Payment Amount: '.$payment_amount.' Payment Amount: '.$payment_status.' Paid to: '.$receiver_email.' Thanks and Enjoy!'; $headers .= 'From: ' .$from. "\r\n" .'Reply-To: ' .$from . "\r\n"; $headers .= 'MIME-Version: 1.0' . "\r\n"; $headers .= "Content-Type: text/html; charset=iso-8859-1 "; //mail to buyer mail( $payer_email , $subject, $message, $headers );
4 Answers 4
Take a look at PHP Mailer:
SMTPDebug = 3; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'user@example.com'; // SMTP username $mail->Password = 'secret'; // SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->From = 'from@example.com'; $mail->FromName = 'Mailer'; $mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient $mail->addAddress('ellen@example.com'); // Name is optional $mail->addReplyTo('info@example.com', 'Information'); $mail->addCC('cc@example.com'); $mail->addBCC('bcc@example.com'); $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 in bold!'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if(!$mail->send()) < echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; > else
You should download PHPMailer, put it into your project directory and include it in your project like require ‘path/to/PHPMailer/PHPMailerAutoload.php; and then use it as shown above
sorry for delay . is this working on «localhost» or only on online server . because i am testing it on localhost but it didn’t working
This works for me, but there is a problem that every time I am receiving mail it’s coming on same thread, it is not coming up like as new email. Any solution?
$mail = new PHPMailer(); $mail->IsSMTP(); $mail->CharSet = 'UTF-8'; $mail->Host = "mail.example.com"; // SMTP server example $mail->SMTPDebug = 0; // enables SMTP debug information (for testing) $mail->SMTPAuth = true; // enable SMTP authentication $mail->Port = 25; // set the SMTP port for the GMAIL server $mail->Username = "username"; // SMTP account username example $mail->Password = "password"; // SMTP account password example
Create library file for the SMTP Settings ‘library.php’:
Make the form post and do the below actions: IsSMTP(); $mail->Host = SMTP_HOST; //Hostname of the mail server $mail->Port = SMTP_PORT; //Port of the SMTP like to be 25, 80, 465 or 587 $mail->SMTPAuth = true; //Whether to use SMTP authentication $mail->Username = SMTP_UNAME; //Username for SMTP authentication any valid email created in your domain $mail->Password = SMTP_PWORD; //Password for SMTP authentication $mail->AddReplyTo("reply@yourdomain.com", "Reply name"); //reply-to address $mail->SetFrom("from@yourdomain.com", "Asif18 SMTP Mailer"); //From address of the mail // put your while loop here like below, $mail->Subject = "Your SMTP Mail"; //Subject od your mail $mail->AddAddress($email, "Asif18"); //To address who will receive this email $mail->MsgHTML("Hi, your first SMTP mail has been received. Great Job.
by Asif18"); //Put your body of the message you can place html code here $mail->AddAttachment("images/asif18-logo.png"); //Attach a file here if any or comment this line, $send = $mail->Send(); //Send the mails if($send)< echo 'Mail sent successfully
'; > else< echo 'Mail error:
'.$mail->ErrorInfo; > > ?>
Please edit your email and password correctly.
You may see the demo and source code on Click here