22

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 );

Please give me some suggestions or simple and nice tutorials.

deemi-D-nadeem
  • 2,343
  • 3
  • 30
  • 71
  • Does this answer your question? [Sending email with PHP from an SMTP server](https://stackoverflow.com/questions/14456673/sending-email-with-php-from-an-smtp-server) – Abu Shoeb Jun 07 '20 at 11:06

4 Answers4

27

Take a look at PHP Mailer:

https://github.com/PHPMailer/PHPMailer

Example from that page:

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->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 <b>in bold!</b>';
$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 {
    echo 'Message has been sent';
}
Jonathon
  • 15,873
  • 11
  • 73
  • 92
  • Please tell me that i get "PHPmailer" folder and put into my project and write this code. – deemi-D-nadeem Sep 18 '14 at 09:52
  • 2
    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 – Jonathon Sep 18 '14 at 10:14
  • 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 – deemi-D-nadeem Sep 22 '14 at 06:16
  • It should work on localhost too, this class implemented the SMTP protocol and connects to your mail server to send the e-mail. – Jonathon Sep 22 '14 at 08:03
  • 1
    If you're using WP you can include the built-in class in your script `wp-includes/class-phpmailer.php` – Jack Aug 16 '20 at 15:34
  • 1
    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? – Anmol Juneja May 14 '21 at 21:41
  • FYI this answer shows basic authentication with simple username & password, which is now deprecated. Modern auth uses tokens. See this example for more details: https://github.com/PHPMailer/PHPMailer/wiki/Using-Gmail-with-XOAUTH2 – SendETHToThisAddress Jan 20 '22 at 21:52
  • For me, this only worked when I set `SMTPSecure` to `ssl`, not `tls`. – FWDekker Aug 04 '22 at 15:25
  • @AnmolJuneja Probably the subject you send is the same in all messages! – mehmet Nov 09 '22 at 20:08
3
$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
2

Please try this

Create library file for the SMTP Settings 'library.php':

    <?php
    error_reporting(0);
    define("SMTP_HOST", "SMTP_HOST_NAME"); //Hostname of the mail server
    define("SMTP_PORT", "SMTP_PORT"); //Port of the SMTP like to be 25, 80, 465 or 587
    define("SMTP_UNAME", "VALID_EMAIL_ACCOUNT"); //Username for SMTP authentication any valid email created in your domain
    define("SMTP_PWORD", "VALID_EMAIL_ACCOUNTS_PASSWORD"); //Password for SMTP authentication
    ?>

Make the form post and do the below actions:

<?php
include 'library.php';
include "classes/class.phpmailer.php"; // include the class file name
if(isset($_POST["send"])){
    $email = $_POST["email"];
    $mail   = new PHPMailer; // call the class
    $mail->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("<b>Hi, your first SMTP mail has been received. Great Job!.. <br/><br/>by <a href='http://asif18.com'>Asif18</a></b>"); //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 '<center><h3 style="color:#009933;">Mail sent successfully</h3></center>';
    }
    else{
        echo '<center><h3 style="color:#FF3300;">Mail error: </h3></center>'.$mail->ErrorInfo;
    }
}
?>

Please edit your email and password correctly.

You may see the demo and source code on Click here

  • the demo link was broken – Kishore Feb 27 '19 at 09:01
  • 1
    How about code without a third party script? Everything I find is using PHPMailer or some other script, which I cannot/do not want to use. Well I could go and reverse engineer PHPMailer and try to get only that which is needed to send via SMTP instead of PHP mail. – WebDude0482 Sep 20 '19 at 21:59
  • 1
    @WebDude0482 or anyone else who comes across this: the mail function in PHP will look for a local mail server to send the email from. If you have control of the server/container, you need to install an actual mail server such as Dovecot, on the same host. The mail command will then send to the mail server, which you can use locally or relay the mail onto an internet mail server such as Gmail. - HTH – Paul Allsopp Dec 29 '22 at 05:28
  • Hello, what you stated is correct. And, not what I was looking for, which was a simple script to send email in PHP via SMTP. Not a tutorial on PHPMailer or some other mail script, not use the mail() function. – WebDude0482 Dec 30 '22 at 16:17
0

you can employ the use of the phpmailer library since the mail() function has limitations in its use. so I prefer using PHPmailer it is easier to work with than the mail() function. I also used the mail() function it requires a lot of settings here and there and cannot be used to send remote mail messages. so in short, the mail() function is only suitable when working with the local server but not suitable when you want to work with a remote server.