Php send email phpmailer

PHPMailer: How to send Emails in PHP

PHP mail() hardly get the job done. I don’t feel a need to go a distance to why the mail() is bad. You’re always going to be building web apps that have something to do with emails. And you don’t want even a single thing to fail while sleeping.

Think PHPMailer

  1. Send attachments, including inline and HTML based emails
  2. Validates email addresses automatically
  3. Protect against header injection attacks
  4. Print error messages in several languages
  5. Send without a local mail server
  6. and much more!

Installing PHPMailer

Are you still ignoring composer? Don’t, please.

The recommended way to install PHPMailer is via composer. Just add this line to your composer.json file:

composer require phpmailer/phpmailer 

This will add the PHPMailer package inside the vendor folder generated by Composer.

You’re now going to see several examples of sending emails with PHPMailer.

Sending emails using PHPMailer on a local server

From = "jeremiah@tolearn.com.ng"; // replace to your own domain $mail->FromName = "Jeremiah Succeed"; // replace to your own name // To address and name $mail->addAddress("recipent1@example.com", "Recipent Name"); $mail->addAddress("recepient1@example.com"); // Recipient name is optional // Address to which recipient will reply $mail->addReplyTo("reply@yourdomain.com", "Reply"); // CC and BCC $mail->addCC("cc@example.com"); $mail->addBCC("bcc@example.com"); // Send HTML or Plain Text email $mail->isHTML(true); $mail->Subject = "Subject Text"; $mail->Body = "Mail body in HTML"; $mail->AltBody = "This is the plain text version of the email content"; if(!$mail->send()) < echo "Mailer Error: " . $mail->ErrorInfo; > else

While the code above sends the email to the recipent, try to avoid it. Most of your emails will go straight to the recipent SPAM folder. And am sure it’s not something you want.

Читайте также:  Php вывод содержимого переменной

Sending emails with STMP

I mentioned above that PHPMailer has an integrated STMP support which enables you to send email without needing a local mail server.

SMTP is a protocol used by mail clients to send an email request to a mail server. And Once the mail server verifies that email, it sends it to the recipient mail server.

You can send an email with an external email host like Gmail. For example with a Gmail account, you can send an email from your application using your Gmail username and password.

This example code sends emails without a local mail server. A strong reason to use PHPMailer.

SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = 'stmp.gmail.com'; // Set the SMTP server to send through $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'username@gmail.com'; // SMTP username $mail->Password = 'Gmail Password'; // SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged $mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above // From email address and name $mail->setFrom('jeremiah@tolearn.com.ng', 'Jeremiah Succceed'); // To email addresss $mail->addAddress('recipent1@example.com'); // Add a recipient $mail->addReplyTo('reply@example.com', 'Reply'); // Recipent reply address $mail->addCC('cc@example.com'); $mail->addBCC('bcc@example.com'); // Content $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'; $mail->send(); echo 'Message has been sent'; > catch (Exception $e) < echo "Message could not be sent. Mailer Error: ErrorInfo>"; > 

I used Gmail STMP settings in the code above. Simply replace the $mail->username and $mail->password with your Gmail address and password.

You can use other STMP hosts like MailGun, Postmark, Sendinblue, elasticmail, e.t.c.

Send an email with Attachment

To send an attachment to the recipient, simply add the below code before the $mail->send()

// Attachments $mail->addAttachment('/path/to/file.mp3'); // Add attachments $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name . $mail->send(); 

Send email to multiple addresses

To send to multiple emails, simply addAddress(’email’) as much you want to.

$mail->addAddress('recipent2@gmail.com'); // Add a recipient $mail->addAddress('recipent3@gmail.com'); // Add a recipient $mail->addAddress('recipent4@gmail.com'); // Add a recipient 

Conclusion

You just learnt how to send emails in PHP using PHPMailer.

They are other premium email API services you can use to speedily send emails in PHP. However, sometimes just doing things with PHPMailer is enough — considering it free to use.

You can learn about PHPMailer APIs in the official documentation.

Do you enjoy PHPMailer? Or do you encounter any difficulties? Let me know in the comments!

Источник

How To Send Email Using PHPMailer in PHP

In order to add email services to your PHP application, the PHPMailer class is the ideal choice. PHP frameworks of all kinds are supported (Laravel or Symfony are based on the SwiftMailer library, though, but it is still possible to use PHPMailer as well.) An HTML email with attachments is created using this sophisticated tool, which can then be sent out through SMTP or web server on your local network to a large number of recipients in real time. At the end of this article You’ll be able to send a mail using the php library.

Prerequisites

Installation

You can send emails using mail(), Sendmail or Qmail, or you can send them directly through SMTP servers.
Additional advanced features include:

  • SSL/SMTP Authentication
  • Attachments in fs, string, and binary
  • A plain-text email can be sent to clients that do not support HTML email.
  • An active development community maintains it secure and current.

Installing PHPMailer

You must install PHPMailer through Composer, a dependency management for PHP, starting with version 6.0 released in August 2017. This method is suggested by PHPMailer’s developers on Github.
In your terminal, type the following code to install the library:

composer require phpmailer/phpmailer 

PHPMailer can be added manually if you don’t want to install Composer in a testing environment, for example. PHPMailer source code files may be downloaded here. Once downloaded, transfer the PHPMailer folder to one of the include path directories provided in your PHP setup, then manually load each class file:

 use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'path_to_PHPMailer/src/Exception.php'; require 'path_to_PHPMailer/src/PHPMailer.php'; require 'path_to_PHPMailer/src/SMTP.php'; 

See the PHPMailer documentation on Github for comprehensive information on how to install the package without composer.

Use PHPMailer to send emails from a local server

The most likely scenario is that you will utilize HTML to create your email message As a result, you’ll be using HTML techniques and attributes to deliver the messages to recipients.
Include the autoload.php file created by Composer if you have used Composer to install:

require 'path/to/composer/vendor/autoload.php'; 

This is how to use PHPMailer if you have manually installed it:

require 'path_to_PHPMailer/src/PHPMailer.php'; require 'path_to_PHPMailer/src/SMTP.php'; require 'path_to_PHPMailer/src/Exception.php'; 

Then include the PHPMailer class:

use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; 

Creating a new PHPMailer object is the next stage in the process:

In the next step, we’ll provide the headers:

 $mail->setFrom('noreply@example.com', 'Admin');//Add a sender $mail->addAddress('joe@example.net', 'User');//Add a recipient $mail->addReplyTo('info@example.com', 'Information');//Add an address that the mail reply should be sent $mail->addCC('cc@example.com'); //Add a more recipient $mail->addBCC('bcc@example.com');//Add a more recipient 

If you need to add many addresses, create a new code for each one:

 $mail->AddBCC('bcc2@example.com', 'mick'); $mail->AddBCC('bcc3@example.com', 'doe'); 

A file can be attached by specifying its path. Also, you can specify a filename, although it’s not required: the script will use the real filename:

 $mail->addAttachment('path_to/file.csv', 'file.csv'); 

In other to add image,you use CID attachments to embed an image here:

 $mail->addEmbeddedImage('path_to/image_file.jpg', 'image'); 

and in the message body add

 $mail->Body = ' '; 

Add a subject, indicate that it should delivered with sendmail, and specify that the message contains HTML.

 $mail->Subject = 'Test Email Using PHPMailer'; $mail->IsSendmail();sets to send mail using Sendmail. $mail->isHTML(true); //Set email format to HTML 

You may now enter the email body:

 $mail->Body = "

Mail body in HTML

Email testing

"
; $mail->AltBody = "This is the plain text version of the email content";

Lastly, define the email sending features as follows:

try  $mail->send(); echo "Message has been sent successfully"; > catch (Exception $e)  echo "Mailer Error: " . $mail->ErrorInfo; > 

Finally, let’s put all the code you’ve created to send an email together.

 require 'path/to/composer/vendor/autoload.php'; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; $mail = new PHPMailer(); $mail->setFrom('noreply@example.com', 'Admin');//Add a sender $mail->addAddress('joe@example.net', 'User');//Add a recipient $mail->addReplyTo('info@example.com', 'Information');//Add an address that the mail reply should be sent $mail->addCC('cc@example.com'); //Add a more recipient $mail->addBCC('bcc@example.com');//Add a more recipient $mail->addAttachment('path_to/file.csv', 'file.csv'); $mail->addEmbeddedImage('path_to/image_file.jpg', 'image'); $mail->Subject = 'Test Email Using PHPMailer'; $mail->IsSendmail();sets to send mail using Sendmail. isHTML(true) sets the email's format to HTML. $mail->isHTML(true); //Set email format to HTML $mail->Body = "

Mail body in HTML

Email testingcid:image">

"
; $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; >

Sending emails with SMTP server

 //Server settings $mail->SMTPDebug = 1;//Enable SMTP debugging //Send using SMTP $mail->isSMTP(); //Enable SMTP authentication $mail->SMTPAuth = true; //SMTP Host $mail->Host='smtp.example.com'; //SMTP username $mail->Username= 'user@example.com'; //SMTP password $mail->Password= 'secret'; //Enable implicit TLS encryption $mail->SMTPSecure= PHPMailer::ENCRYPTION_SMTPS; //TCP port to connect $mail->Port= 465; $mail->isHTML(true); //Set email format to HTML $mail->Body = "

Mail body in HTML

Email testing

"
; $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; >

Let’s go through the variables now

  • $mail->SMTPDebug is used to enable debugging and display error messages.
  • $mail->isSMTP() is used to notify the PHPMailer to use SMTP to convey messages.
  • $mail->SMTPAuth is used to set authentication.
  • $mail->Host is used to define server host
  • $mail->Username is used to define the username for smtp server host account.
  • $mail->Password is used to define the password for smtp server host account
  • $mail->SMTPSecure sets the encryption type.
  • $mail->Port is used to define server port in which the email should be sent.

Conclusion

As a PHP developer, there’s little chance you’ll be able to avoid sending emails through script. Using third-party services like mailtrap or mailchimp may be a possibility in some cases, but developing your own email sending library may not be feasible. Therein lies the value of PHPMailer and its equivalents (such as Zend Mail and Swift Mailer).
Here we’ve covered the most frequent uses of Phpmailer: delivering pictures and attachments in HTML emails over SMTP or localhost, as well as debugging settings.

Источник

Оцените статью