Complete Guide for Sending Emails in PHP Php by Vivek Pal - April 4, 2020April 13, 20200 Post Views: 5,662 Hi Friends, Hope you are doing well. Today we’ll see Complete Guide for Sending Emails in PHP. Actually, there are many methods to perform it which we learn in this post. I am writing this post because I didn’t found all the methods in one place. So, I am trying to do it. Sending Mails in PHP using mail() function Its a one of the traditional way to sending emails but it also have some limitations. It does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments. <?php $to = 'yourname@domain.com'; //Receaver Email Address $subject = 'I am a Sample Email'; //Subject of Email $message = 'This mail is sent via the PHP mail function'; //message Body $headers = 'From: sender@sendermail.com'; //From Email Address mail($to_email,$subject,$message,$headers); ?> 1234567 <?php $to = '[email protected]'; //Receaver Email Address$subject = 'I am a Sample Email'; //Subject of Email$message = 'This mail is sent via the PHP mail function'; //message Body$headers = 'From: [email protected]'; //From Email Addressmail($to_email,$subject,$message,$headers);?> Output Sending Mails using PHPMailer PHP Mailer is a good and most popular library to send emails safely and easily via PHP code from a web server. Sending emails directly by PHP code requires a high-level familiarity with SMTP standard protocol and related issues and vulnerabilities about Email injection for spamming. If PHP Mailer is already installed so you can add the path of the ‘PHPMailer.php’ else you can download PHP Mailer & Upload to public_html folder & add the path <?php //Import the PHPMailer class into the global namespace use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'PHPMailer-master/src/Exception.php'; require 'PHPMailer-master/src/PHPMailer.php'; require 'PHPMailer-master/src/SMTP.php'; $mail = new PHPMailer; //PhP Mailer Instance $mail->setFrom('sender@yourdomain.com', 'Sender Name'); //Sender Email Address $mail->addReplyTo('replyto@yourdomain.com', 'Reply To Name'); //Reply To Email Address $mail->addAddress('sendto@receaver.com', 'Name'); // Send Too Email Address $mail->Subject = 'PHPMailer mail() test'; //Subject $mail->Body = 'This is support html template'; //Email Body $mail->addAttachment('attachment.png'); //Attachment //send the message, check for errors if (!$mail->send()) { echo 'Mailer Error: '. $mail->ErrorInfo; } else { echo 'Message sent!'; } ?> 12345678910111213141516171819202122232425 <?php //Import the PHPMailer class into the global namespaceuse PHPMailer\PHPMailer\PHPMailer;use PHPMailer\PHPMailer\Exception;require 'PHPMailer-master/src/Exception.php';require 'PHPMailer-master/src/PHPMailer.php';require 'PHPMailer-master/src/SMTP.php'; $mail = new PHPMailer; //PhP Mailer Instance $mail->setFrom('[email protected]', 'Sender Name'); //Sender Email Address$mail->addReplyTo('[email protected]', 'Reply To Name'); //Reply To Email Address$mail->addAddress('[email protected]', 'Name'); // Send Too Email Address$mail->Subject = 'PHPMailer mail() test'; //Subject$mail->Body = 'This is support html template'; //Email Body$mail->addAttachment('attachment.png'); //Attachment //send the message, check for errorsif (!$mail->send()) { echo 'Mailer Error: '. $mail->ErrorInfo;} else { echo 'Message sent!';}?> Output Sending SMTP Emails Few hosting providers do not allow sending emails without SMTP Authentication. Like GCP (Google Cloud Platform), If You have disabled emails without authentication from Domain Registrar settings or you want to send emails with other SMTP Server. Then, In this condition, SMTP authentication is required before sending emails. It’s the most secured way for sending emails <?php //Import the PHPMailer class into the global namespace use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'PHPMailer-master/src/Exception.php'; require 'PHPMailer-master/src/PHPMailer.php'; require 'PHPMailer-master/src/SMTP.php'; $mail = new PHPMailer; //PhP Mailer Instance $mail->SMTPDebug = 3; //Enable SMTP Debugging $mail->isSMTP(); //Enable PHPMailer for SMTP Use $mail->Host = "smtp.gmail.com"; //SMTP Host Name $mail->SMTPAuth = true; //Enable SMTP Authentication $mail->Username = "id@domain.com"; //Email Address $mail->Password = "pwd@123zzz"; //Password $mail->SMTPSecure = "tls"; //Enable TLS Encryption $mail->Port = 587; //SMTP Port $mail->setFrom('id@domain.com', 'Name); //Sender Email Address $mail->addReplyTo('id@domain.com', 'Reply To Name'); //Reply To Email Address $mail->addAddress('sender@domain.com', 'Sendor Name'); // Send Too Email Address $mail->Subject = 'PHPMailer mail() SMTP Test'; //Subject $mail->Body = 'This is support html template'; //Email Body $mail->addAttachment('attatchment.png'); //Attachment //send the message, check for errors if (!$mail->send()) { echo 'Mailer Error: '. $mail->ErrorInfo; } else { echo 'Message sent!'; } ?> 123456789101112131415161718192021222324252627282930313233 <?php //Import the PHPMailer class into the global namespaceuse PHPMailer\PHPMailer\PHPMailer;use PHPMailer\PHPMailer\Exception;require 'PHPMailer-master/src/Exception.php';require 'PHPMailer-master/src/PHPMailer.php';require 'PHPMailer-master/src/SMTP.php'; $mail = new PHPMailer; //PhP Mailer Instance$mail->SMTPDebug = 3; //Enable SMTP Debugging$mail->isSMTP(); //Enable PHPMailer for SMTP Use$mail->Host = "smtp.gmail.com"; //SMTP Host Name$mail->SMTPAuth = true; //Enable SMTP Authentication$mail->Username = "[email protected]"; //Email Address $mail->Password = "pwd@123zzz"; //Password$mail->SMTPSecure = "tls"; //Enable TLS Encryption$mail->Port = 587; //SMTP Port $mail->setFrom('[email protected]', 'Name); //Sender Email Address$mail->addReplyTo('id@domain.com', 'Reply To Name'); //Reply To Email Address$mail->addAddress('sender@domain.com', 'Sendor Name'); // Send Too Email Address$mail->Subject = 'PHPMailer mail() SMTP Test'; //Subject$mail->Body = 'This is support html template'; //Email Body$mail->addAttachment('attatchment.png'); //Attachment //send the message, check for errorsif (!$mail->send()) { echo 'Mailer Error: '. $mail->ErrorInfo;} else { echo 'Message sent!';}?> Output Sending Emails Using Pear Mail Pear mail is a class that provides multiple interfaces for sending Emails. It also provides supporting functions useful to multiple mailer backends. Currently, supported backends include PHP’s native mail() function, Sendmail, and SMTP. This package also provides an RFC822 email address list validation utility class. Before implementing code you need to install Pear mail. Please follow these steps for Pear Mail Installation Step 1. Login to Hosting Control Panel > Software > Php Pear Packages Step 2. Note the Include Path. Example ini_set("include_path", '/home/sitename/php:' . ini_get("include_path") ); 1 ini_set("include_path", '/home/sitename/php:' . ini_get("include_path") ); Search ‘Mail’ at PHP Extension(s) and Application(s) Step 3. Install Mail 1.4.1 Now the installation process has been completed. Here is the sample code for Pear Mail <?php ini_set("include_path", '/home/name/php:' . ini_get("include_path") );// Replace code with your ini path require_once "Mail.php"; $from = "Name <sender@domain.com>";//Sender Email Id $to = "receaver@domain.com"; //Send To Email id $subject = "Pear Mail Email Test"; //Email Subject //SMTP Credentials $host = "domain.com"; $port = "587"; $username = "sender@domain.com"; $password = "password@123#"; $email_message = "I'm the body of the message " . "\n"; //Email Body $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject); 'Reply-To: '.$from."\r\n" . 'X-Mailer: PHP/' . phpversion(); $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password)); $mail = $smtp->send($to, $headers, $email_message); if (PEAR::isError($mail)) { echo "<p>" . $mail->getMessage() . "</p>"; } else { echo("<p>Message successfully sent!</p>"); } ?> 123456789101112131415161718192021222324252627282930313233 <?phpini_set("include_path", '/home/name/php:' . ini_get("include_path") );// Replace code with your ini pathrequire_once "Mail.php";$from = "Name <[email protected]>";//Sender Email Id$to = "[email protected]"; //Send To Email id$subject = "Pear Mail Email Test"; //Email Subject//SMTP Credentials$host = "domain.com";$port = "587";$username = "[email protected]";$password = "password@123#"; $email_message = "I'm the body of the message " . "\n"; //Email Body $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject); 'Reply-To: '.$from."\r\n" . 'X-Mailer: PHP/' . phpversion(); $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));$mail = $smtp->send($to, $headers, $email_message);if (PEAR::isError($mail)) { echo "<p>" . $mail->getMessage() . "</p>"; } else { echo("<p>Message successfully sent!</p>"); }?> Output Sending Emails using Swift Mailer Swift Mailer is one of the popular packages for sending emails in PHP. It offers enhanced security and handles large attachments and images with low memory usage. Click Here to know the steps for Swift Mailer Installation <?php require_once './vendor/autoload.php'; try { // Create the SMTP transport $transport = (new Swift_SmtpTransport('smtp.domain.com', 587)) ->setUsername('sender@domain.com') ->setPassword('password@123#'); $mailer = new Swift_Mailer($transport); // Create a message $message = new Swift_Message(); $message->setSubject('Swift Mailer Test Mail'); $message->setFrom(['sender@domain.com' => 'Name']); $message->addTo('sendto@domain.com','Name'); // Add attachment $attachment = Swift_Attachment::fromPath('./attachment.pdf'); $message->attach($attachment); // Set the plain-text part $message->setBody('Hi I am Plain Text.'); // Set the HTML part $message->addPart('I am html</br>body'); // Send the message $result = $mailer->send($message); } catch (Exception $e) { echo $e->getMessage(); } 1234567891011121314151617181920212223242526272829 <?phprequire_once './vendor/autoload.php'; try { // Create the SMTP transport $transport = (new Swift_SmtpTransport('smtp.domain.com', 587)) ->setUsername('[email protected]') ->setPassword('password@123#'); $mailer = new Swift_Mailer($transport); // Create a message $message = new Swift_Message(); $message->setSubject('Swift Mailer Test Mail'); $message->setFrom(['[email protected]' => 'Name']); $message->addTo('[email protected]','Name'); // Add attachment $attachment = Swift_Attachment::fromPath('./attachment.pdf'); $message->attach($attachment); // Set the plain-text part $message->setBody('Hi I am Plain Text.'); // Set the HTML part $message->addPart('I am html</br>body'); // Send the message $result = $mailer->send($message);} catch (Exception $e) { echo $e->getMessage();} Please like & share this post if you like it