PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label phpmailer. Show all posts
Showing posts with label phpmailer. Show all posts

Tuesday, August 30, 2022

[FIXED] why is PEAR mimedecode.php body output almost always NULL?

 August 30, 2022     eml, mime, pear, php, phpmailer     No comments   

Issue

It successfully decodes about 1/20 raw e-mails in .eml format, is it really that rubbish library or am I doing something wrong?


Solution

I now use parts array output instead of body. Looks like it is more reliable.



Answered By - Markus
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 7, 2022

[FIXED] how to send two different messages to two different users phpmailer

 July 07, 2022     php, phpmailer     No comments   

Issue

I am sending mails to two different persons, two different messages one for user and one for admin.

  $message1='hello user'      
  $message2='hello admin'
  $email = 'user@email.com'
  $adminemail = 'admin@email.com';

  require 'PHPMailerAutoload.php';
  $mail = new PHPMailer(true);
  $mail->isHTML();
  $mail->IsSMTP(); 
  $mail->setFrom('admin@mysite.com', 'admin site'); 
  $mail->AddAddress( $email);
  $mail->Subject  = $subject;
  $mail->Body     =$message1;
  $mail->Send();
  //message for admin 
  $mail->Body     =$message2;
  //$adminemail = $generalsettings[0]["admin_email"]; 

   $mail->AddAddress($adminemail);
   $mail->Send();

But as a user I am receiving the message twice.. How to send two different messages to two different users.


Solution

You need to clear the recipients list before you add the new address for the second message. If you don't do that, the first recipient will receive the second message as well:

...
$mail->Body     =$message1;
$mail->Send();

//message for admin 

// Remove previous recipients
$mail->ClearAllRecipients();
// alternative in this case (only addresses, no cc, bcc): 
// $mail->ClearAddresses();

$mail->Body     =$message2;
//$adminemail = $generalsettings[0]["admin_email"]; 

// Add the admin address
$mail->AddAddress($adminemail);
$mail->Send();


Answered By - jeroen
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How should I upgrade from PHPMailer 5.2 to 6.0?

 July 07, 2022     email, php, phpmailer     No comments   

Issue

I have a script that currently uses a recent version of PHPMailer 5.2.x. PHPMailer 6.0 has been released, but says it will break backward compatibility – what do I need to do to upgrade?

<?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->setFrom('from@example.com', '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->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';
}

Solution

The major things that have changed in PHPMailer 6.0:

  • Requires PHP 5.5 or later (up from 5.0)
  • Uses a namespace
  • Class filenames and locations have changed
  • Additional unrelated "extras" classes have been removed

There are many other smaller changes which you can read about in the changelog, and also the official upgrade guide, but these are the ones most likely to affect you.

Upgrading via composer

To upgrade via composer, change the entry in the require section of your composer.json file, and then run composer update phpmailer/phpmailer:

"phpmailer/phpmailer": "~6.0"

This will update only PHPMailer, and will not touch any other dependencies.

PHPMailer uses a semver release numbering policy, and that pattern will match all future releases in the 6.x series. This is a change from the previously recommended ~5.2 pattern.

Loading class files

For the example script given, we mainly need to change how the class is loaded. The autoloader is no longer there, so you either need to be using composer (in which case you won't need to change anything - the standard composer autoloader will do it automatically), or you need to load the classes yourself.

With composer:

require 'vendor/autoload.php';

Without composer:

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

Namespacing

The PHPMailer classes are in the PHPMailer\PHPMailer namespace, so you either need to work in that namespace, or import them into your own or the global namespace, for example:

//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

Note that these must be placed before the require lines. After that you can use the original class names you're used to:

$mail = new PHPMailer;

Alternatively, you can refer to their fully-qualified names directly, without the use statements, for example:

$mail = new PHPMailer\PHPMailer\PHPMailer;

The reason this class ends up with this "triple name" is because it's the PHPMailer class, in the PHPMailer project, owned by the PHPMailer organisation. This allows it to be differentiated from other forks of PHPMailer, other projects by the PHPMailer organisation, and other classes within the project.

Exceptions

Other than the name change from phpmailerException, exceptions work the same way as in previous versions, but you need to look out for the namespace when catching:

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

$mail = new PHPMailer(true);
try {
    ...
} catch Exception($e) {
    //$e is an instance of PHPMailer\PHPMailer\Exception
} catch \Exception ($e) {
    //$e is an instance of the PHP built-in Exception class
}

Documentation

All documentation and example code has been updated for 6.0 too. The best place to start is the readme file or the project wiki, where you will find links to the ever-popular troubleshooting guide, numerous tutorials, and generated API documentation. If you're just starting out, base your code on the examples provided in the examples folder.

Getting help

If you have a problem using PHPMailer, first of all search on Stack Overflow for your specific error message and under the PHPMailer tag. If you think you have found a bug in PHPMailer, report it on the github project (hint - being unable to connect to mail servers from your GoDaddy server is not a PHPMailer bug!)



Answered By - Synchro
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to do file_get_contents() from directory other than __DIR__?

 July 07, 2022     php, phpmailer     No comments   

Issue

I'm sending an email using PHPMailer and this works fine:

$mail->Subject = "My Email Subject";
$mail->msgHTML(file_get_contents('emailcontent.html'), __DIR__);
$mail->send();

The file 'emailcontent.html' is in the current directory and it works.

Now I want to move the 'emailcontent.html' file into subdirectory 'emails/emailcontent.html'.

I tried this ...

$mail->msgHTML(file_get_contents('emailcontent.html'), __DIR__.'/emails/');

... and this ...

$mail->msgHTML(file_get_contents('/emails/emailcontent.html'), __DIR__);

... but neither worked.

What am I doing wrong?


Solution

Thanks to @RiggsFolly for straightening me out ... the problem was an errant /.

This works:

$mail->msgHTML(file_get_contents('emails/emailcontent.html'), __DIR__);


Answered By - AndySummers2020
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to output a forloop in a string?

 July 07, 2022     php, phpmailer     No comments   

Issue

I am trying to output data object with multiple properties into a string within phpmailer how do I achieve this?

function sendMailTo($mail, $data, $subject_, $toEmail) {
    $body = 'all data:' foreach ($data as $obj) {
        $obj->property;
    }

    $mail->ClearAllRecipients();
    $mail->AddAddress($toEmail);
    $mail->FromName = $data->inputName;
    $mail->From = $email;
    $mail->Subject = $subject_;
    $mail->IsHTML(true);
    $mail->Body = $body;
    $mail->AddReplyTo($toEmail, $data->inputName);
    $mail->send();
}

Solution

This code is a bit nonsensical, unless $data is really an array of objects, each having a property called property.

If you want to extract all the properties of an object, iterate over them, because PHP objects are iterable.

Also there's no need to use a local variable; assemble the string directly into $mail->Body:

$mail->Body = "All data:\r\n";
foreach ($data as $property => $value) {
    $mail->Body .= "$property = $value\r\n";
}

I've assumed that you want both the property names and values.

(and you can remove the later line that says $mail->Body = $body;)



Answered By - Synchro
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why did PHPMailer just change from using dynamic function calls to call_user_func()?

 July 07, 2022     php, phpmailer     No comments   

Issue

While vetting the latest update to PHPMailer (PHP library for sending e-mails), I noticed this change:

return $patternselect($address);

Into:

return call_user_func($patternselect, $address);

At first, I had to make sure that I wasn't looking at this in a "reverse" view, which I wasn't; the call_user_func change is the new code -- not the old. I also noticed the same being done in a different place of the code.

So, they decided to stop using the nice "new" syntax for dynamically calling a function and instead changed it into the old call_user_func syntax.

Why? Am I missing something? Wasn't the first code shown here (which is what I always use) an improvement to PHP which made it nicer to call functions dynamically without having to use call_user_func in your code? Why would they "go back" to the old way?

It's not like this was just added to PHP or anything, so it can't be a case of a buggy, bleeding-edge feature which "isn't quite ready yet".

PS: Note that I'm not asking you to look into the brains of the PHPMailer developer(s), but to offer me an explanation as to why anyone would want to actively do this once they had actually used the better (or so I thought?) way.


Solution

Since this is so specific, it would probably have been better asked on Github, but I'll answer it here.

This was done for a very specific reason; switching to variable functions (which was done in PHPMailer 6.1.2) caused a very specific BC break in PHP versions between 5.2.3 and 7.0.0, and that was reported to me. While those PHP versions are now considered defunct, many are still using them, and the current PHPMailer release (6.x) promises compatibility back to PHP 5.5, so this change needed be reverted to retain compatibility with those old versions. It has no effect on later PHP versions.

I originally changed to variable functions because, as you say, it's the new shiny, it's easier to read (IMHO), and it's the kind of thing that gets recommended by static analysers, however these (evidently!) don't take backward compatibility into account.

So what was the BC break? While variable functions themselves have been around for a while (since at least PHP 5.4 I think), the static method callable pattern (class::method) was only added in PHP 7.0.0, whereas that syntax works fine in call_user_func; that's exactly what the BC break was, and the reason for the reversion in the PHPMailer 6.1.7 release.



Answered By - Synchro
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can i make subject and body message to be given from inputs in phpmailer

 July 07, 2022     php, phpmailer     No comments   

Issue

This is index.php Right now all i can do is give values to the $mail->Subject and $mail->body but i want it to be dynamic for example Here i want to give 2 inputs for subject and message and pass it on $mail->Subject and $mail->Body since the post method is on ajax im unable to pass two values from input fields to the send_mail.php any help would be appreciated

<?php
    //index.php
    
    $connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
    $query = "SELECT * FROM customer ORDER BY customer_id";
    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    
    ?>
    <!DOCTYPE html>
    <html>
    <head>
       
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>
    <br />
    <div class="container">
      
        <br />
        <div class="table-responsive">
    
            <table class="table table-bordered table-striped">
                <tr>
                    <th>Customer Name</th>
                    <th>Email</th>
                    <th>Select</th>
                    <th>Action</th>
                </tr>
                <?php
                $count = 0;
                foreach($result as $row)
                {
                    $count = $count + 1;
                    echo '
                        <tr>
                            <td>'.$row["customer_name"].'</td>
                            <td>'.$row["customer_email"].'</td>
                            <td>
                                <input type="checkbox" name="single_select" class="single_select" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" />
                            </td>
                            <td>
                            <button type="button" name="email_button" class="btn btn-info btn-xs email_button" id="'.$count.'" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" data-action="single">Send Single</button>
                            </td>
                        </tr>
                        ';
                }
                ?>
                <tr>
                    <td colspan="3"></td>
                    <td><button type="button" name="bulk_email" class="btn btn-info email_button" id="bulk_email" data-action="bulk">Send Bulk</button></td></td>
                </tr>
            </table>
        </div>
    </div>
    </body>
    </html>
    
    <script>
        $(document).ready(function(){
            $('.email_button').click(function(){
                $(this).attr('disabled', 'disabled');
                var id  = $(this).attr("id");
                var action = $(this).data("action");
                var email_data = [];
                if(action == 'single')
                {
                    email_data.push({
                        email: $(this).data("email"),
                        name: $(this).data("name")
                    });
                }
                else
                {
                    $('.single_select').each(function(){
                        if($(this).prop("checked") == true)
                        {
                            email_data.push({
                                email: $(this).data("email"),
                                name: $(this).data('name')
                            });
                        }
                    });
                }
    
                $.ajax({
                    url:"send_mail.php",
                    method:"POST",
                    data:{email_data:email_data},
                    beforeSend:function(){
                        $('#'+id).html('Sending...');
                        $('#'+id).addClass('btn-danger');
                    },
                    success:function(data){
                        if(data == 'ok')
                        {
                            $('#'+id).text('Success');
                            $('#'+id).removeClass('btn-danger');
                            $('#'+id).removeClass('btn-info');
                            $('#'+id).addClass('btn-success');
                        }
                        else
                        {
                            $('#'+id).text(data);
                        }
                        $('#'+id).attr('disabled', false);
                    }
                })
    
            });
        });
    </script>

And this is send_mail.php

<?php
//send_mail.php

if(isset($_POST['email_data']))
{
    require 'class/class.phpmailer.php';
    $output = '';
    foreach($_POST['email_data'] as $row)
    {
        $mail = new PHPMailer;
        $mail->IsSMTP();                                
        $mail->Host = 'smtp.gmail.com';     
        $mail->Port = '587';                                
        $mail->SMTPAuth = true;                         
        $mail->Username = 'xx';                 
        $mail->Password = 'xx';                 
        $mail->SMTPSecure = 'tls';                          
        $mail->From = 'xx';         
        $mail->FromName = 'xx';                 
        $mail->AddAddress($row["email"], $row["name"]); 
        $mail->WordWrap = 50;                           
        $mail->IsHTML(true);                            
        $mail->Subject = 'i want input to be passed here'; 
        //An HTML or plain text message body
        $mail->Body = 'and the body message to be passed here';

        $mail->AltBody = '';

        $result = $mail->Send();                        //Send an Email. Return true on success or false on error

//        if($result["code"] == '400')
//        {
//            $output .= html_entity_decode($result['full_error']);
//        }

    }
    if($output == '')
    {
        echo 'ok';
    }
    else
    {
        echo $output;
    }
}

?>

Solution

I am assuming You want to add two inputs for subject and message for each email data.

You can add 2 fields and in ajax set it along with email data and pass it to send_mail.php.

JS Code

<script>
    $(document).ready(function(){
        $('.email_button').click(function(){
            $(this).attr('disabled', 'disabled');
            var id  = $(this).attr("id");
            var action = $(this).data("action");
            var email_data = [];
            if(action == 'single')
            {
                email_data.push({
                    email: $(this).data("email"),
                    name: $(this).data("name"),
                    subject: $(this).data("subject"), //or can be grab from input
                    message: $(this).data("message")
                });
            }
            else
            {
                $('.single_select').each(function(){
                    if($(this).prop("checked") == true)
                    {
                        email_data.push({
                            email: $(this).data("email"),
                            name: $(this).data('name'),
                            subject: $(this).data("subject"), //or can be grab from input
                    message: $(this).data("message")
                        });
                    }
                });
            }

            $.ajax({
                url:"send_mail.php",
                method:"POST",
                data:{email_data:email_data},
                beforeSend:function(){
                    $('#'+id).html('Sending...');
                    $('#'+id).addClass('btn-danger');
                },
                success:function(data){
                    if(data == 'ok')
                    {
                        $('#'+id).text('Success');
                        $('#'+id).removeClass('btn-danger');
                        $('#'+id).removeClass('btn-info');
                        $('#'+id).addClass('btn-success');
                    }
                    else
                    {
                        $('#'+id).text(data);
                    }
                    $('#'+id).attr('disabled', false);
                }
            })

        });
    });
</script>

In send_mail.php replace following lines

$mail->Subject = 'i want input to be passed here'; 
//An HTML or plain text message body
$mail->Body = 'and the body message to be passed here';

With This

$mail->Subject = $row["subject"]; 
$mail->Body = $row["message"];

Hope it will answer your question.



Answered By - Hitesh Shrimali
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I prevent mails sent through PHP mail() from going to spam?

 July 07, 2022     email, php, phpmailer, spam     No comments   

Issue

I am using PHP's mail() function to send emails (sendmail process is running). But all the mails are going to spam (in case of gmail). I have tried many tricks that I found on the net but none is working, please tell me about any sure-shot trick.


Solution

You must to add a needle headers:

Sample code :

$headers = "From: myplace@example.com\r\n";
$headers .= "Reply-To: myplace2@example.com\r\n";
$headers .= "Return-Path: myplace@example.com\r\n";
$headers .= "CC: sombodyelse@example.com\r\n";
$headers .= "BCC: hidden@example.com\r\n";

if ( mail($to,$subject,$message,$headers) ) {
   echo "The email has been sent!";
   } else {
   echo "The email has failed!";
   }
?> 


Answered By - user744116
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Add Multiple Attachments to an Email Using PHPMailer

 July 07, 2022     email, php, phpmailer     No comments   

Issue

I have only been able to attach one pdf to an email at a time. Could someone please help me to figure out how to add multiple attachments to email using PHPMailer? I initially tried just using multiple add attachment statements following each other.

$file1Name = $_FILES['myfile1']['name'];
$file1Path = $_FILES['myfile1']['tmp_name'];
$file2Name = $_FILES['myfile2']['name'];
$file2Path = $_FILES['myfile2']['tmp_name'];
$file3Name = $_FILES['myfile3']['name'];
$file3Path = $_FILES['myfile3']['tmp_name'];
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = '587';
$mail->SMTPAuth = true;
$mail->Username = 'email@gmail.com';
$mail->Password = 'password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
// . . .
$mail->Body = $mail_body;
$mail->addAttachment($file1Path, $file1Name);
$mail->addAttachment($file2Path, $file2Name);
$mail->addAttachment($file3Path, $file3Name);
$mail->Send();

This didn't work. After looking online, I found that you can generally only add multiple attachments to an email when the attachments are received from a form input that allows for multiple submissions at a time https://phppot.com/php/send-email-with-multiple-attachments-using-php/. The files are stored together as an array and are attached by looping through the array. It is important to me to not retrieve the multiple files from one form input, so I do not like this option. I thought it might help if I stored the file information in arrays myself, but this also didn't work.

$fileNameArray = array($file1Name, $file2Name, $file3Name);
$filePathArray = array($file1Path, $file2Path, file3Path);
// . . .
for($i = 0; $i < 3; $i++) {
$mail->addAttachment($fileDataArray[$i], $fileNameArray[$i]);
}
$mail->Send();

Next, I tried a solution where I attempted to send multiple emails, each in reply to the previous one, that contained a single attachment. This also didn't work. After the first email, no other attachments were included.

$fileNameArray = array($file1Name, $file2Name, $file3Name);
$filePathArray = array($file1Path, $file2Path, file3Path);
for($i = 0; $i < 3; $i++) {
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com'; 
$mail->Port = '587';        
$mail->SMTPAuth = true;       
$mail->Username = 'email@gmail.com';     
$mail->Password = 'password';     
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;     
//  . . .
$mail->Body = $mail_body;
 
$mail->addAttachment($filePathArray[$i], $fileNameArray[$i]);   

I've also looked through some fixes that involve editing the PHPMailer code. Both fixes have to do with the content-ID. I either couldn't find the code that was being referenced for the fix or it seemed like, in the time since the fix was posted, PHPMailer was updated and the fix was implemented.

https://sourceforge.net/p/phpmailer/discussion/130418/thread/42bf5695/ https://developer-paradize.blogspot.com/2015/02/how-to-fix-multiple-attachments-problem.html

I'm kind of lost at what to do at this point. If anyone knows how to add multiple attachments to an email using PHPMailer, could you please help me? Your help is much appreciated. Thank you.


Solution

This question was answered by synchro on another thread. https://github.com/PHPMailer/PHPMailer/issues/2098

"The threads you pointed at are years old!

The article about unique IDs is long obsolete; inline attachments with duplicate cid values will still be ignored, but that's expected behavior, and only applies to inline attachments created using addEmbeddedImage() and addStringEmbeddedImage().

The key problem here is that you're just not handling uploads properly. How you should handle uploads is covered in the PHP docs, and all that occurs before PHPMailer has any involvement.

First of all, you need to understand how file inputs work. These determine what shows up in the $_FILES superglobal that PHP populates for you. You can either have multiple file-type inputs that select a single file each, or you can have a single one that allows you to select multiple files. PHPMailer doesn't care either way, but you have to.

Next, you need to make sure you use move_uploaded_file or at least is_uploaded_file in order to validate what's in the $_FILES superglobal, otherwise, it's not safe.

Thirdly, you need to check whether the calls to addAttachment() are successful – at present, you're just assuming they work and have no error checking at all.

So, I recommend you take a look at the single and multiple file upload examples, both of which do all of the above, and there are no known problems with adding multiple attachments."



Answered By - Ryan Schultz
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use a custom SMTP settings in my WordPress site

 July 07, 2022     email, mailgun, phpmailer, smtp, wordpress     No comments   

Issue

I need to use custom SMTP settings for my WordPress site to send email through my email servers such as Mailgun or SendGrid.


Solution

Place this in your theme function.php or your own plugin.

add_action( 'phpmailer_init', 'custom_phpmailer_init' );
function custom_phpmailer_init( $phpmailer ) {

    $phpmailer->isSMTP();
    $phpmailer->Host = 'smtp.mailgun.com';
    $phpmailer->Port = 465;
    $phpmailer->Username = 'user_name';
    $phpmailer->Password =  '********';
    $phpmailer->SMTPAuth = true;
    $phpmailer->SMTPSecure = 'ssl';
    $phpmailer->From       = 'FromName@example.com';
    $phpmailer->FromName   = 'FromName';

}


Answered By - Mohamed Ali O.Ameur
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why do I get a sender rejected from postfix when sending from phpmailer?

 July 07, 2022     email, php, phpmailer, postfix-mta, smtp     No comments   

Issue

When I run the following PHP code I get an error.

$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // debug
$mail->Host = 'localhost';
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = $uname;
$mail->Password = $pw;
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->setFrom('no-reply@example.com', 'website registration');
$mail->addAddress($cleaned_email);
$mail->Subject = 'Please verify your account';
$msg = '[registration text...]'
$msg = wordwrap($msg, 70);
$mail->Body = $msg;
                        
if (!$mail->send()) {
  echo $mail->ErrorInfo;
  exit();
} else {
  [... add user to db, etc...]
}

The mail appears to be sent. No error is generated by PHPMailer and the database code is run.

Here is the error generated in mail.log.

Aug 22 11:47:06 server postfix/smtp[8339]: 079AB1F909: to=<outsider-at-anydomain.com>, relay=mail.brighthouse.com[47.43.26.56]:25, delay=5.7, delays=0.06/0.02/0.31/5.3, dsn=2.0.0, status=sent (250 2.0.0 <user-at-example.com> sender rejected. Please see understanding-email-error-codes for more information.)

I have tried changing the send from address to my user that I am authenticating with in the PHP code.

I have tried adding a smtpd_sender_login_maps paramter with a matching hash table to my postfix config to map the no-reply address to my user that I authenticate with, but it ignores it as an unused parameter.

Postfix config:

# See /usr/share/postfix/main.cf.dist for a commented, more complete version


# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Raspbian)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 2 on
# fresh installs.
compatibility_level = 2

# TLS parameters
smtpd_tls_cert_file = /etc/letsencrypt/live/www.example.com/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/www.example.com/privkey.pem
#smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
#smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions =
        permit_mynetworks
        permit_sasl_authenticated
        defer_unauth_destination
myhostname = server
mydomain = example.com
virtual_alias_domains = example2.com
virtual_alias_maps = hash:/etc/postfix/virtual
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = $mydomain
mydestination = $myhostname, $mydomain, server, localhost.localdomain, localhost
relayhost = mail.brighthouse.com
mynetworks = 127.0.0.0/8
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = ipv4
notify_classes = resource, software, 2bounce
home_mailbox = Maildir/
#mailbox_command =
mailbox_transport = lmtp:unix:private/dovecot-lmtp
smtpd_sender_restrictions = permit_sasl_authenticated
smtpd_recipient_restrictions =
        permit_sasl_authenticated,
        permit_mynetworks,
        reject_unauth_destination
        reject_sender_login_mismatch
smtpd_helo_required = yes
smtpd_helo_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_invalid_helo_hostname,
        reject_non_fqdn_helo_hostname,
        reject_unknown_helo_hostname,
        check_helo_access hash:/etc/postfix/helo_access
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_tls_security_options = noanonymous
smptd_sender_login_maps = hash:/etc/postfix/controlled_envelope_senders


Solution

My issue has nothing to do with PHP Mailer. The php code I posted works. My issue is with my email server setup. I have posted a more server related question on Super User here: https://superuser.com/questions/1580944/soho-postfix-dovecot-configuration-for-small-web-app-and-user-base

Thank you all for the replies.



Answered By - Bryan isthebest
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get PHP variable from another file?

 July 07, 2022     mysql, php, phpmailer, server-side     No comments   

Issue

I'm trying to make a forgot password system with PHPMailer on xampp. But when I send an email,the email body is a html mail template,what I get from another file $mail->Body = file_get_contents('mail_template.php');,and I have problem,because I don't know how should I get the data of the $url variable and send it to mail_template.php file to use it for the link in the mail. I tried the include 'filename.php'; command,but haven't worked.

Here is the code:

if (isset($_POST["submitButton"])) {
    $emailTo = $_POST["email"];

    $code = md5(uniqid(rand(), true));
    $query = $con->prepare("INSERT INTO resetpasswords(code,email) VALUES('$code', '$emailTo')");
    $query->execute();
    if (!$query) {
        exit("Something went wrong...");
    }

    $mail = new PHPMailer(true);

    try {
        //Server settings                                           // Enable verbose debug output
        $mail->isSMTP();                                            // Send using SMTP
        $mail->Host = 'smtp.gmail.com';                    // Set the SMTP server to send through
        $mail->SMTPAuth = true;                                   // Enable SMTP authentication
        $mail->Username = 'mail@gmail.com';                     // SMTP username
        $mail->Password = 'password';                               // SMTP password
        $mail->SMTPSecure = 'ssl';         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
        $mail->Port = 465;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

        //Recipients
        $mail->setFrom('mail@mail.com', 'Email');
        $mail->addAddress($emailTo);     // Add a recipient
        $mail->addReplyTo('no-reply@website.com', 'No reply');


        // Content
        $url = "http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/resetPassword/code/$code";
        $mail->isHTML(true);                                  // Set email format to HTML
        $mail->Subject = 'Reset your password!';
        $mail->Body = file_get_contents('mail_template.php');
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

        $mail->send();
    } catch (Exception $e) {
        echo "Message could not be sent. Error: {$mail->ErrorInfo}";
    }
    header("refresh:10;url=login.php");
}

So from this php file,I want to send the data of the $url to the mail_template.php

Is this possible to do?


Solution

To send data to another url in php you have to try the following url:

`mail_template.php?data=mail@gmail.com` 

then inside an empty mail_template.php do -

 <?php 
    if (isset($_GET['data'])) {
      $test = $_GET['data'];
//print the data added to the url
      echo $test;
    }
    ?>


Answered By - Temidayo Dtuzzy Omotayo
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to disable error messages in phpmailer

 July 07, 2022     debugging, forms, php, phpmailer     No comments   

Issue

I am using phpmailer for a contactform with attachment and in the php i build my own error messages. the form and email work fine but when not filling in an email address and not chosen a file to upload i got these error messages from phpmailer

Invalid address: Could not access file:

This is the code of phpmailer i use now:

// Software: PHPMailer - PHP email class                                    |
// Version: 5.1 

require('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();

$mail->SMTPAuth = FALSE;
$mail->Port     = 25;  
$mail->Host     = "localhost";
$mail->Mailer   = "smtp";
$mail->SetFrom($_POST["user_email"], $_POST["user_name"]);
$mail->AddAddress("myname@myemailcom"); 
$mail->Subject = "Contactform";
$mail->WordWrap   = 80;
$mail->MsgHTML($_POST["user_message"]);

if(is_array($_FILES)) {
$mail->AddAttachment($_FILES['user_attachment']['tmp_name'],$_FILES['user_attachment']['name']); 
}
$mail->IsHTML(true);
if(!$mail->Send()) {
    echo 'some error message';
}
else {
    echo 'success message';
}

After some research i tried to add:

$phpmailer->SMTPDebug=false; // without result

How can i get rid of these built in error messages?


Solution

First of all you're running a very old version of PHPMailer that is dangerously outdated and is exposing your site to some major vulnerabilities. Before you do anything else, upgrade. I also suggest you base your code on the current examples provided with PHPMailer.

In the code you posted, you're not enabling debug output (it's off by default) at all, so I suspect there may be other code you're not showing. You have not shown what the debug output looks like, so we can't tell whether it's really PHPMailer that's generating it.

Your PHPMailer instance is called $mail, not $phpmailer, and the SMTPDebug property is an integer, so change that line to:

$phpmailer->SMTPDebug = 0;


Answered By - Synchro
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I send an email via PHPMAILER without SSL - port 25?

 July 07, 2022     email, php, phpmailer, starttls     No comments   

Issue

I want to send an email without SSL using PHPMailer. I have enabled the debug mode so that I can check the details in the logs.

    $mail = new PHPMailer\PHPMailer\PHPMailer();
    $mail->IsSMTP(true); // enable SMTP
    $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true; // authentication enabled
    $mail->SMTPSecure = false; // secure transfer enabled REQUIRED for Gmail
    $mail->Host = "mail.company.co.uk";
    $mail->Port = 25; // or 587
    $mail->IsHTML(true);
    $mail->Username = "email@company.co.uk";
    $mail->Password = "password_of_username";
    $mail->SetFrom($email,$name);
    $mail->Subject = $subject;
    $mail->Body = $message;
    $mail->AddAddress($to);

This is giving an exception:

2018-09-28 10:04:27 CLIENT -&gt; SERVER: EHLO localhost<br>
2018-09-28 10:04:27 CLIENT -&gt; SERVER: STARTTLS<br>
SMTP Error: Could not connect to SMTP host.<br>
2018-09-28 10:04:28 CLIENT -&gt; SERVER: QUIT<br>
2018-09-28 10:04:28 <br>
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting<br>
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Solution

You've based your code on an old example, which doesn't help. You can't see what's going on because you've only used 1 for SMTPDebug; set it to 2.

Your mail server is advertising that it supports STARTTLS on port 25, so PHPMailer is using it automatically. You can disable encryption entirely by doing this:

$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;

However, I'd recommend not doing this; fix your TLS config instead. You probably need to update your local CA certificate bundle - see the troubleshooting guide for more details.



Answered By - Synchro
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to include PHPmailer in functions.php properly (Wordpress)

 July 07, 2022     email, php, phpmailer, wordpress     No comments   

Issue

I'm trying to include PHPmailer in functions.php

my code:

add_action('wp_ajax_nopriv_test_mailer', 'test_mailer');

function test_mailer () {

try {

    require_once(get_template_directory('/includes/mail/PHPMailer.php'));
    require_once(get_template_directory('/includes/mail/Exception.php'));

    $mail = new PHPMailer(true);                              // Passing `true` enables exceptions

    //Server settings
    $mail->SMTPDebug = 4;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'test@gmail.com';                 // SMTP username
    $mail->Password = 'dummypassword!';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('test@gmail.com', 'Mailer Test');
    $mail->addAddress('john.doe@gmail.com', 'John User');     // Add a recipient
    $mail->addReplyTo('test@gmail.com');

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject testing';
    $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';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

wp_die();

}

I also tried to put require_once out of the try catch still the same error here is the snippet about the error

"PHP Fatal error: Uncaught Error: Class 'PHPMailer' not found"

I use betheme template and I stored the files PHPmailer in betheme/includes/mail.


Solution

As BA_Webimax pointed out, you should be using Wordpress' built-in email functions, though due to WP's reliance on outdated PHP versions, you will end up using a very old version of PHPMailer with it.

Back to your current problem: It's not your require_once statements that are failing, it's that you have not imported the namespaced PHPMailer classes into your namespace. Add these at the top of your script:

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

Alternatively, use the FQCN when creating your instance:

$mail = new PHPMailer\PHPMailer\PHPMailer;

Note that this applies to the Exception class too, so you'd need to say:

catch (PHPMailer\PHPMailer\Exception $e) {


Answered By - Synchro
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can i get the correct "from" emailaddress, using PHPMailer and Google Apps?

 July 07, 2022     email, gmail, php, phpmailer     No comments   

Issue

I use a simple PHPMailer form to allow the users of my website to contact me through a contact form. I use my google apps account to send the mail. In the script i set the emailaccount the user provides me as the "from address".

Until a few weeks ago, this went well. From Google Apps i could click on reply to send a reply to the user contacting me.

However, recently, without changing anything in my code, when i click on reply, i send an email to myself. Is this something Google changed in its policy? Or did i maybe do something wrong incidentally?

This is the output i get. I use info@kynero.nl to send and use jaapklok@gmail.com as customer account. However, when i open the mail i receive in info@kynero.nl and click on reply, i send an email to info@kynero.nl instead of jaapklok@gmail.com

2019-02-06 20:34:31 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP x38sm6269222edx.24 - gsmtp
2019-02-06 20:34:31 CLIENT -> SERVER: EHLO www.kynero.nl
2019-02-06 20:34:31 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [2a0b:7280:200:0:4d0:baff:fe00:d8e]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2019-02-06 20:34:31 CLIENT -> SERVER: STARTTLS
2019-02-06 20:34:31 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2019-02-06 20:34:31 CLIENT -> SERVER: EHLO www.kynero.nl
2019-02-06 20:34:31 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [2a0b:7280:200:0:4d0:baff:fe00:d8e]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2019-02-06 20:34:31 CLIENT -> SERVER: AUTH LOGIN
2019-02-06 20:34:31 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2019-02-06 20:34:31 CLIENT -> SERVER: <credentials hidden>
2019-02-06 20:34:31 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2019-02-06 20:34:31 CLIENT -> SERVER: <credentials hidden>
2019-02-06 20:34:31 SERVER -> CLIENT: 235 2.7.0 Accepted
2019-02-06 20:34:31 CLIENT -> SERVER: MAIL FROM:<jaapklok@gmail.com>
2019-02-06 20:34:31 SERVER -> CLIENT: 250 2.1.0 OK x38sm6269222edx.24 - gsmtp
2019-02-06 20:34:31 CLIENT -> SERVER: RCPT TO:<info@kynero.nl>
2019-02-06 20:34:31 SERVER -> CLIENT: 250 2.1.5 OK x38sm6269222edx.24 - gsmtp
2019-02-06 20:34:31 CLIENT -> SERVER: DATA
2019-02-06 20:34:31 SERVER -> CLIENT: 354 Go ahead x38sm6269222edx.24 - gsmtp
2019-02-06 20:34:31 CLIENT -> SERVER: Date: Wed, 6 Feb 2019 21:34:31 +0100
2019-02-06 20:34:31 CLIENT -> SERVER: To: info@kynero.nl
2019-02-06 20:34:31 CLIENT -> SERVER: From: Jaap Klok <jaapklok@gmail.com>
2019-02-06 20:34:31 CLIENT -> SERVER: Reply-To: Jaap Klok <jaapklok@gmail.com>
2019-02-06 20:34:31 CLIENT -> SERVER: Subject: Aanvraag via Inschrijfformulier op kynero.nl
2019-02-06 20:34:31 CLIENT -> SERVER: Message-ID: <0bYvsZOe3xY7iWVxMyFA2uxOvWVDPpl5CAX58DcXA@www.kynero.nl>
2019-02-06 20:34:31 CLIENT -> SERVER: X-Mailer: PHPMailer 6.0.5 (https://github.com/PHPMailer/PHPMailer)
2019-02-06 20:34:31 CLIENT -> SERVER: MIME-Version: 1.0
2019-02-06 20:34:31 CLIENT -> SERVER: Content-Type: text/html; charset=iso-8859-1
2019-02-06 20:34:31 CLIENT -> SERVER: 
2019-02-06 20:34:31 CLIENT -> SERVER: Naam: Jaap Klok <br />
2019-02-06 20:34:31 CLIENT -> SERVER: Inschrijving: Detectie vrijdag 10.00 <br />
2019-02-06 20:34:31 CLIENT -> SERVER: Algemene voorwaarden: Akkoord <br />
2019-02-06 20:34:31 CLIENT -> SERVER: Bericht: Test 3 - 21:36
2019-02-06 20:34:31 CLIENT -> SERVER: 
2019-02-06 20:34:31 CLIENT -> SERVER: .
2019-02-06 20:34:32 SERVER -> CLIENT: 250 2.0.0 OK 1549485383 x38sm6269222edx.24 - gsmtp
2019-02-06 20:34:32 CLIENT -> SERVER: QUIT
2019-02-06 20:34:32 SERVER -> CLIENT: 221 2.0.0 closing connection x38sm6269222edx.24 - gsmtp

Solution

Google does not allow you to send from arbitrary addresses. You can only use your account address, or predefined aliases from your gmail settings. If you try to do this, it will simply substitute your account address for the from address, as you're seeing.

Generally trying to do this is the wrong approach anyway – it's forgery and will result in your messages being spam filtered or bounced due to SPF failures. The right way to do it is to use your own address as the from address, and the submitter's address as a reply-to address. The contact form example provided with PHPMailer does exactly this. The important bit of that:

    //Use a fixed address in your own domain as the from address
    //**DO NOT** use the submitter's address here as it will be forgery
    //and will cause your messages to fail SPF checks
    $mail->setFrom('from@example.com', 'First Last');
    //Send the message to yourself, or whoever should receive contact for submissions
    $mail->addAddress('whoto@example.com', 'John Doe');
    //Put the submitter's address in a reply-to header
    //This will fail if the address provided is invalid,
    //in which case we should ignore the whole request
    if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
        $mail->Subject = 'PHPMailer contact form';
        //Keep it simple - don't use HTML
        $mail->isHTML(false);
        //Build a simple message body
        $mail->Body = <<<EOT
Email: {$_POST['email']}
Name: {$_POST['name']}
Message: {$_POST['message']}
EOT;


Answered By - Synchro
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Make Forgot Password in Codeigniter, Password send in email

 July 07, 2022     codeigniter, email, mysql, phpmailer     No comments   

Issue

Hello guyz i have create small kind of application in codeigniter,in this application i am doing forgot password module, i have created a function but dont know why its not working, i need random password have to been send in mail which will be autogenerated , but email method does not work, so give me some suggestion.

Here is My view:

<form action="<?php echo base_url() . "welcome/forgotpassword" ?>" method="POST">

            <div class="form-group has-feedback">
                    <input type="email" class="form-control" placeholder="Email" name="user_email" />
                    <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
             </div>
              <div class="row">
              <div class="col-xs-4">
                     <input type="submit"  class="btn btn-primary btn-block btn-flat"  value="Send">

              </div>
             </div>
    </form>

Here is my Controller:

public function forgotpassword(){

    $email = $this->input->post('user_email');
    $findemail = $this->main_model->ForgotPassword($email);
    $this->load->view('forgotpassword');
    if ($findemail) {
        $this->main_model->sendpassword($findemail);
    } else {

          $this->session->set_flashdata('msg', 'Email not found!');

    }
}

Here is My model:

 public function sendpassword($data) {
    $email = $data['user_email'];
    print_r($data);
    $query1 = $this->db->query("SELECT *  from user_registration where user_email = '" . $email . "'");
    $row = $query1->result_array();


    if ($query1->num_rows() > 0) {

        $passwordplain = "";
        $passwordplain = rand(999999999, 9999999999);
        $newpass['user_password'] = md5($passwordplain);
        $this->db->where('user_email', $email);
        $this->db->update('user_registration', $newpass);
        $mail_message = 'Dear ' . $row[0]['full_name'] . ',' . "\r\n";
        $mail_message .= 'Thanks for contacting regarding to forgot password,<br> Your <b>Password</b> is <b>' . $passwordplain . '</b>' . "\r\n";
        $mail_message .= '<br>Please Update your password.';
        $mail_message .= '<br>Thanks & Regards';
        $mail_message .= '<br>Your company name';
        require FCPATH . 'assets/PHPMailer/PHPMailerAutoload.php';
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPSecure = "tls";
        $mail->Debugoutput = 'html';
        $mail->Host = "ssl://smtp.googlemail.com";
        $mail->Port = 465;
        $mail->SMTPAuth = true;
        $mail->Username = "xxxxxxxxx@gmail.com";
        $mail->Password = "xxxxxxxx";
        $mail->setFrom('xxxxxxx@gmail.com', 'admin');
        $mail->IsHTML(true);
        $mail->addAddress('user_email', $email);
        $mail->Subject = 'OTP from company';
        $mail->Body = $mail_message;
        $mail->AltBody = $mail_message;

        if (!$mail->send()) {


            $this->session->set_flashdata('msg', 'Failed to send password, please try again!');
        } else {

            echo $this->email->print_debugger();
            $this->session->set_flashdata('msg', 'Password sent to your email!');
        }

    }
}

Solution

This function may have something to do with it... can you show us that?

$findemail = $this->main_model->ForgotPassword($email);

When you use print_r($data) is anything returned? If not, $query1 will be 0 or null and everything will break.

// core function
public function sendpassword($data) {
    // include your libary at the top
    require FCPATH . 'assets/PHPMailer/PHPMailerAutoload.php';
    // email retrieved from the ForgotPassword() method.
    $email = $data['user_email'];
    // get the user_info array row
    $query1 = $this->db->query("SELECT * from user_registration where user_email = '" . $email . "'");
    $row = $query1->result_array();
    if ($query1->num_rows() > 0) {
        // assign users name to a variable
        $full_name = $row['full_name'];
        // generate password from a random integer
        $passwordplain = rand(999999999, 9999999999);
        // encrypt password
        $encrypted_pass = $this->pass_gen($passwordplain);
        $newpass['user_password'] = $encrypted_pass;
        // update password in db
        $this->db->where('user_email', $email);
        $this->db->update('user_registration', $newpass);
    // begin email functions
    $result = $this->email_user($full_name, $email, $passwordplain);
    echo $result;
    }
}

// email sending
public function email_user($full_name, $email, $passwordplain) {
    // compose message
    $mail_message = 'Dear ' . $full_name. ',' . "\r\n";
    $mail_message .= 'Thanks for contacting regarding to forgot password,<br> Your <b>Password</b> is <b>' . $passwordplain . '</b>' . "\r\n";
    $mail_message .= '<br>Please Update your password.';
    $mail_message .= '<br>Thanks & Regards';
    $mail_message .= '<br>Your company name';
    // email config
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->SMTPSecure = "tls";
    $mail->Debugoutput = 'html';
    $mail->Host = "ssl://smtp.googlemail.com";
    $mail->Port = 465;
    $mail->SMTPAuth = true;
    $mail->Username = "xxxxxxxxx@gmail.com";
    $mail->Password = "xxxxxxxx";
    $mail->setFrom('xxxxxxx@gmail.com', 'admin');
    $mail->IsHTML(true);
    $mail->addAddress('user_email', $email);
    $mail->Subject = 'OTP from company';
    $mail->Body = $mail_message;
    $mail->AltBody = $mail_message;
    // send the mail
    if (!$mail->send()) {
        return $this->email->print_debugger();
        $this->session->set_flashdata('msg', 'Failed to send password, please try again!');
    } else {
        return $this->email->print_debugger();
        $this->session->set_flashdata('msg', 'Password sent to your email!');
    }
}

// Password encryption
public function pass_gen($password) {
    $encrypted_pass = md5($password);
    return $encrypted_pass;
}


Answered By - maz3runn3r
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How secure is my contact form using JS fetch and PHPMailer?

 July 07, 2022     email, php, phpmailer, security, vue.js     No comments   

Issue

I'm currently building a small website with no real backend using vue-cli. As I'm a real potatoe when it comes to php (and backend in general), I was wondering how secure was my contact form on this website, and what to do if it's not secure enough.

To summarize, I'm making a fetch() call from my vue app to a mail.php file on my server. This mail.php file uses PHPMailer to send an email from one of my domain's email addresses to another of my addresses. And up to now it works fine.

Here is my JS related to sending mail :

  sendMail () {
    this.sendRequest()
      .then(r => {
        if (r.mailSent === 'ok') {
          // mail sent callback
        }
      })
  },
  async sendRequest () {
    const response = await fetch('./mail.php', {
      method: 'post',
      headers: {
        'content-type': 'application/json'
      },
      body: JSON.stringify({
        subject: 'Message de ' + this.firstNameInput + ' ' + this.lastNameInput + ' via mysite.com',
        body: '<html>' +
          '<body>' +
          '<p>De : ' + this.firstNameInput + ' ' + this.lastNameInput + '</p>' +
          '<p>Email : ' + this.mailInput + '</p>' +
          '<p>Message :<br>' + this.messageInput.replace(/\n/g, '<br>') + '</p>' +
          '</body>' +
          '</html>',
        altBody: 'De : ' + this.firstNameInput + ' ' + this.lastNameInput + ' /// Email : ' + this.mailInput + ' /// Message :' + this.messageInput
      })
    })
    return response.json()
  }

And here is the content of my mail.php file :

<?php

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

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

header('Content-Type: application/json');

include './mailSettings.php'; // contains $site, $mailFrom, $mailTo, $senderName and $recipientName

if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] == $site) {
  $contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';

  if ($contentType === "application/json") {
    $content = stripslashes(trim(file_get_contents("php://input")));
    $decoded = json_decode($content, true);

    if(!is_array($decoded)) {
      echo '{"status":"error"}';
    } else {
      $mail = new PHPMailer(TRUE);
      try {
        $mail->setFrom($mailFrom, $senderName);
        $mail->addAddress($mailTo, $recipientName);
        $mail->Subject = $decoded['subject'];
        $mail->isHTML(TRUE);
        $mail->Body = $decoded['body'];
        $mail->AltBody = $decoded['altBody'];
        $mail->send();
      }
      catch (Exception $e) {
        echo $e->errorMessage();
      }
      catch (\Exception $e) {
        echo $e->getMessage();
      }
      echo '{ "mailSent": "ok"}';
    }
  } else {
    echo '{"status":"error"}';
  }
} else {
  echo '{"status":"no call accepted from this adress"}';
}
?>

I guessed that I still have stuff to do in order to make this secure, but can you guys help me find out what and why ?


Solution

You've done the most important thing right – not using user-submitted addresses – which helps prevent you turning into a spam gateway!

First of all, for simple data capture like this, I'd avoid HTML altogether. Regular plain text will do the job.

If you do want to use HTML, I recommend assembling it on the server side - that way you can do much stricter filtering on the simple input fields, for example using strip_tags, or using an allow-list of characters to filter fields (see the link @DigitalDrifter provided), before inserting them into a layout. This is much easier and safer than trying to cleanly filter pre-assembled, user-supplied HTML. This is also really simple to do as the JS and PHP code will be more or less identical.



Answered By - Synchro
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I use phpmailer without composer

 July 07, 2022     php, phpmailer     No comments   

Issue

I need to send emails and the mail() function just does not work for me. The problem is that PHP is not installed on my device. Can I still use it in, index.php for example?

I use 000webhost


Solution

Try this code (it works for me):

<?php

use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer.php';
require 'SMTP.php';

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = 'xxx';            // Change here
$mail->Password = 'xxx';            // Change here
$mail->setFrom('xxx', 'Mailer');    // Change here
$mail->addAddress('xxx');           // Change here
$mail->isHTML();
$mail->CharSet = 'utf-8';
$mail->Subject = 'Subject';
$mail->Body = 'Hello world';

echo $mail->Send() ? 'OK!' : 'Something went wrong';

Be sure that:

  • the files PHPMailer.php and SMTP.php are in the same folder of the PHP script (I suggest you to put them all in the root of your website, for now);
  • the PHP script (containing the above code) is UTF-8 encoded.


Answered By - AbsoluteBeginner
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to send email with php without the mail landing automaticly in the trash box

 July 07, 2022     email, php, phpmailer, recycle-bin     No comments   

Issue

Im using PHP's mail() function to send some emails. But all my mails land automaticly in the trash box. Is there a way of preventing this? If so, where should i read to learn more about it.

Would you recommend me using PHPmailer?

Best of regards, Alexander


Solution

I suppose you mean thrash box at the receiver's end. So basically the receiving email server is regarding it as spam. This can happen if:

1) The IP you are sending from is already blacklisted for spamming (happens often in shared hosting)

2) The IP and domain are relatively new and unknown.

(Note that many times, newsletters from well established sites also end up in spam).

If its your dedicated IP, then setting RDNS for the IP, to match the domain name will very likely solve the issue. Another usual practice is to alert the receiver (if she is subscribing on your website) to check their thrash/spam folder and whitelist your email address in their mail account.

regards,

JP



Answered By - JP19
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing