[Tut] Sendmail in PHP using mail(), SMTP with Phpmailer - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: PHP Development (https://www.sickgaming.net/forum-82.html) +--- Thread: [Tut] Sendmail in PHP using mail(), SMTP with Phpmailer (/thread-99075.html) |
[Tut] Sendmail in PHP using mail(), SMTP with Phpmailer - xSicKxBot - 03-27-2022 Sendmail in PHP using mail(), SMTP with Phpmailer <div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/03/sendmail-in-php-using-mail-smtp-with-phpmailer.jpg" width="550" height="305" title="" alt="" /></div><div><div class="modified-on" readability="7.1304347826087"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on October 10th, 2021.</div> <p>Sendmail in PHP is possible with just single line of code. PHP contains built-in mail functions to send mail.</p> <p>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.</p> <div class="post-section-highlight" readability="34"> <h2>Quick Example</h2> <pre class="prettyprint"><code class="language-php"> <?php mail('[email protected]', 'Mail Subject', 'Mail test content'); ?> </code></pre> </div> <p>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.</p> <p>The below list examples we are going to see below. It will cover basic to full-fledged support to sendmail in PHP.</p> <ol> <li>Simple text mail with PHP mail().</li> <li>Send <a href="https://phppot.com/php/php-image-upload-using-tinymce-editor/">rich-text content</a> via mail.</li> <li>Sendmail in PHP with attachments.</li> <li>Sendmail using PHPMailer with SMTP.</li> </ol> <h2>PHP mail()</h2> <p>The PHP mail() is to sendmail from an application. Let’s see the <a href="https://phppot.com/php/php-ini-file/">PHP configurations</a> required to make the mail() function work. Also, we will see the common syntax and parameters of this <a href="https://phppot.com/php/functions-in-php/">PHP function</a> below.</p> <h3>Syntax</h3> <pre class="prettyprint"><code class="language-php"> mail( string $recipient_email, string $subject, string $message, array|string $headers = [], string $additional_params = "" ) </code></pre> <h3>Parameters</h3> <p><strong>$recipient_email</strong><br />One or more <a href="https://phppot.com/php/how-to-handle-csv-with-php-read-write-import-export-with-database/">comma-separated value</a> that is the target mail addresses. The sample format of the values are,</p> <ul> <li>[email protected]</li> <li>Name <[email protected]></li> <li>[email protected], name2.domain.com</li> <li>Name <[email protected]>, Name2 <[email protected]></li> </ul> <p><strong>$subject<br /></strong>Mail subject. It should satisfy <a href="http://www.faqs.org/rfcs/rfc2047.html" target="_blank" rel="noopener">RFC 2047</a>.</p> <p><strong>$message<br /></strong>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.</p> <p><strong>$headers</strong><br />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 <a href="https://phppot.com/php/php-header/">headers</a>. The header array contains key-value pair to specify header name and specification respectively.</p> <p><strong>$additional_params</strong><br />This is also optional. It is to pass extra flags like envelope sender address with a command-line option.</p> <h3>Return Values</h3> <p>This function returns boolean <em>true</em> or <em>false</em> based on the sent status of the mail. By receiving boolean <em>true</em> that doesn’t mean the mail was sent successfully. Rather, it only represents that the mail sending request is submitted to the server.</p> <h2>PHP sendmail – configurations</h2> <p>We have to configure some directives to make the mail script work in your environment.</p> <p>Locate your php.ini file and set the mail function attributes. The below image shows the PHP configuration of the mail function.</p> <p><img loading="lazy" class="alignnone size-large wp-image-15685" src="https://phppot.com/wp-content/uploads/2021/10/sendmail-in-php-config-550x305.jpg" alt="sendmail in php config" width="550" height="305" srcset="https://phppot.com/wp-content/uploads/2021/10/sendmail-in-php-config-550x305.jpg 550w, https://phppot.com/wp-content/uploads/2021/10/sendmail-in-php-config-300x167.jpg 300w, https://phppot.com/wp-content/uploads/2021/10/sendmail-in-php-config.jpg 600w" sizes="(max-width: 550px) 100vw, 550px"></p> <p>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 <a href="https://phppot.com/php/phpinfo/">phpinfo()</a>.</p> <h2>Examples to Sendmail in PHP</h2> <h3>Sendmail in PHP to send plaintext content</h3> <p>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.</p> <p>This program print response text based on the boolean returned by the mail() function.</p> <p class="code-heading">sendmail-with-plain-text.php</p> <pre class="prettyprint"><code class="language-html"> <?php $to = '[email protected]'; $subject = 'Mail sent from sendmail PHP script'; $message = 'Text content from sendmail code.'; // Sendmail in PHP using mail() if (mail($to, $subject, $message,)) { echo 'Mail sent successfully.'; } else { echo 'Unable to send mail. Please try again.'; } ?> </code></pre> <h3>PHP Sendmail code to send HTML content</h3> <p>Like the above example, this program also uses the <a href="https://phppot.com/php/php-mail/">PHP mail()</a> function to send emails. It passes HTML content to the mail function.</p> <p>For sending HTML content, it sets the content type and other header values with the mail header.</p> <p class="code-heading">php-mail-with-html-content.php</p> <pre class="prettyprint"><code class="language-html"> <?php $to = '[email protected]'; $subject = 'Mail sent from sendmail PHP script'; $from = '[email protected]'; $headers = "From: $from"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=UTF-8\r\n"; $message = '<p><strong>Sendmail in PHP with HTML content. </strong></p>'; if (mail($to, $subject, $message, $headers)) { echo 'Mail sent successfully.'; } else { echo 'Unable to send mail. Please try again.'; } ?> </code></pre> <h3>Sendmail in PHP to attach files</h3> <p>This program attaches a text file with the email content. It reads a source file using <a href="https://phppot.com/php/php-file_get_contents/">PHP file_get_contents()</a>. It encodes the file content and prepares a mail header to attach a file.</p> <p>It sets content-type, encoding with the message body to make it work. This script uses the optional <em>$header</em> variable on executing sendmail in PHP.</p> <p class="code-heading">sendmail-with-attachment.php</p> <pre class="prettyprint"><code class="language-html"> <?php $file = "example.txt"; $to = '[email protected]'; $subject = 'Mail sent from sendmail PHP script'; $content = file_get_contents($file); $encodedContent = chunk_split(base64_encode($content)); $divider = md5(time()); $headers = "From: TestSupport <[email protected]>\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.'; } ?> </code></pre> <p><img loading="lazy" class="alignnone size-large wp-image-15682" src="https://phppot.com/wp-content/uploads/2021/10/sendmail-in-php-to-attach-file-550x185.jpg" alt="sendmail in php to attach file" width="550" height="185" srcset="https://phppot.com/wp-content/uploads/2021/10/sendmail-in-php-to-attach-file-550x185.jpg 550w, https://phppot.com/wp-content/uploads/2021/10/sendmail-in-php-to-attach-file-300x101.jpg 300w, https://phppot.com/wp-content/uploads/2021/10/sendmail-in-php-to-attach-file-768x258.jpg 768w, https://phppot.com/wp-content/uploads/2021/10/sendmail-in-php-to-attach-file.jpg 1100w" sizes="(max-width: 550px) 100vw, 550px"></p> <h3>Sendmail on form submit</h3> <p>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 <a href="https://phppot.com/php/php-contact-form/">send a contact email via the form</a>.</p> <p>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.</p> <p>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.</p> <p>All the form fields are mandatory and the <a href="https://phppot.com/php/php-form-validation/">validation</a> is done by the browser’s default feature.</p> <p class="code-heading">sendmail-on-form-submit.php</p> <pre class="prettyprint"><code class="language-html"> <?php if (isset($_POST["submit_btn"])) { $to = "[email protected]"; $subject = 'Mail sent from sendmail PHP script'; $from = $_POST["email"]; $message = $_POST["msg"]; $headers = "From: $from"; // Sendmail in PHP using mail() if (mail($to, $subject, $message, $headers)) { $responseText = 'Mail sent successfully.'; } else { $responseText = 'Unable to send mail. Please try again.'; } } ?> <html> <head> <style> 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 { } </style> </head> <body> <?php if(!empty($responseText)) { ?> <div class="response-ribbon"><?php echo $responseText; ?></div> <?php } ?> <form id="email-form" name="email-form" method="post" action=""> <table width="100%" border="0" align="center" cellpadding="4" cellspacing="1"> <tr> <td> <div class="label">Name:</div> <div class="field"> <input name="name" type="text" id="name" required> </div> </td> </tr> <tr> <td><div class="label">E-mail:</div> <div class="field"> <input name="email" type="text" id="email" required> </div></td> </tr> <tr> <td><div class="label">Message:</div> <div class="field"> <textarea name="msg" cols="45" rows="5" id="msg" required></textarea> </div></td> </tr> <tr> <td> <div class="field"> <input name="submit_btn" type="submit" id="submit-btn" value="Send Mail"> </div> </td> </tr> </table> </form> </body> </html> </code></pre> <p><img loading="lazy" class="alignnone size-large wp-image-15683" src="https://phppot.com/wp-content/uploads/2021/10/mail-sending-html-form-550x383.jpg" alt="mail sending html form" width="550" height="383" srcset="https://phppot.com/wp-content/uploads/2021/10/mail-sending-html-form-550x383.jpg 550w, https://phppot.com/wp-content/uploads/2021/10/mail-sending-html-form-300x209.jpg 300w, https://phppot.com/wp-content/uploads/2021/10/mail-sending-html-form.jpg 600w" sizes="(max-width: 550px) 100vw, 550px"></p> <h3>PHP sendmail via SMTP</h3> <p>PHP mail() function has some limitation. To have a full-fledge functionality to sendmail in PHP, I prefer to use the PHPmailer library.</p> <p>This library is one of the best that provides advanced mailing utilities. We have seen examples already to sendmail in PHP using <a href="https://phppot.com/php/send-email-in-php-using-gmail-smtp/">PHPMailer via SMTP</a>. If you are searching for the code to <a href="https://phppot.com/php/sending-email-using-phpmailer-with-gmail-xoauth2/">sendmail using OAuth token</a>, the linked article has an example.</p> <p>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.</p> <p>The mail object is used to configure the mail parameters. Then it invokes the <em>send() </em>method of the PHPMailer class to send mail.</p> <p>Download <a href="https://github.com/PHPMailer/PHPMailer" target="_blank" rel="noopener">PHPMailer from Github</a> and put it into the vendor of this example directory. Replace the SMTP configurations in the below script to make this mail script working.</p> <p class="code-heading">sendmail-in-php-via-smtp.php</p> <pre class="prettyprint"><code class="language-html"> <?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/Exception.php'; require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/PHPMailer.php'; require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/SMTP.php'; $mail = new PHPMailer(true); $mail->SMTPDebug = 0; $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = ""; $mail->Password = ""; $mail->SMTPSecure = "ssl"; $mail->Port = 465; $mail->From = "[email protected]"; $mail->FromName = "Full Name"; $mail->addAddress("[email protected]", "recipient name"); $mail->isHTML(true); $mail->Subject = "Mail sent from php send mail script."; $mail->Body = "<i>Text content from send mail.</i>"; $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; } ?> </code></pre> <h2>Related function to sendmail in PHP</h2> <p>The PHP provides alternate mail functions to sendmail. Those are listed below.</p> <ul> <li>mb_send_mail() – It sends encoded mail based on the language configured with mb_language() setting.</li> <li>imap_mail() – It allows to sendmail in PHP with correct handling of CC, BCC recipients.</li> </ul> <h2>Conclusion</h2> <p>The mail sending examples above provides code to sendemail in PHP. It supports sending various types of content, file attachments in the mail.</p> <p>The elaboration on PHP in-built mail() function highlights the power of this function.</p> <p>Hope this article will be helpful to learn more about how to sendmail in PHP.<br /><a class="download" href="https://phppot.com/downloads/sendmail-in-php.zip">Download</a></p> <p> <!-- #comments --> </p> <div class="related-articles"> <h2>Popular Articles</h2> </p></div> <p> <a href="https://phppot.com/php/sendmail-in-php-using-mail-smtp-with-phpmailer/#top" class="top">↑ Back to Top</a> </p> </div> https://www.sickgaming.net/blog/2021/10/10/sendmail-in-php-using-mail-smtp-with-phpmailer/ |