Jump to content

PHPMailer Setup


Recommended Posts

Hi All,

 

I haven't made use of PHPMailer for quite sometime, as I had been in a different environment. I have noticed that the has been quite a few changes since I last used it, and after struggling the whole day to eventually get it working I am not entirely satisfied with the solution.

 

Some background of what I am doing and will be using it for:

  • I have a number of PHP Scripts that are executing through the use of *.bat files through windows Task Manager. 
  • The scripts execute running a number of tasks, and at the end of the task I need a mail to be sent with the results of the task i.e. Successful, Failed, Lines added to database etc...

 

The mail will be going to not only myself, but to a number of other users, and eventually I want to expand the use of it. So I would like to achieve the following:

  • A cleaner script
  • Select mail recipients from a database table, so that I don't need to manually input it into each form / script.
  • Send the mails as HTML using base64 for the images / other "beautifying" elements.
  • Understand exactly how to use all / at least most of the tags correctly.

I fully understand that many of these answers could probably be found on google, but I am yet to find a source, where the explanation is clear and precise. What I have noticed, is that 95% of coders expect the user to understand coding on the same level as they are on, but it is not always the case, so any help / guidance will really be appreciated. /if need be, I can supply my current code.

 

Thanks.

 

 

 

Link to comment
Share on other sites

A cleaner script

Not sure what you want for this.

 

Select mail recipients from a database table, so that I don't need to manually input it into each form / script.

If you want simplicity then a database isn't the answer. I'd go for a flat file, like INI or JSON or even just text files with one email per line.

 

Send the mails as HTML using base64 for the images / other "beautifying" elements.

Mock up the email in a single HTML file, put quick little placeholders (like "{{date}}") for any information that needs to be inserted, then file_get_contents() and strtr() with an array to get the final result.

 

Understand exactly how to use all / at least most of the tags correctly.

"Tags"?
  • Like 1
Link to comment
Share on other sites

Thanks for your answer here requinix.

 

Basically what I mean by a cleaner script really comes down to understand how to use and populate a mail and then send it via PHP mailer.

 

My current script is made up of a lot of code from various sources, meaning I don't always fully understand what it is doing, and secondly,  I have quite a bit of code repetition. Another problem would be that  I am possibly using outdated source code.

 

Here is an example of what I have / am using:

<?php

$sql1 = "USE mydatabase";

$sql2 = "TRUNCATE TABLE mytable";

$sql3 = "LOAD DATA LOCAL INFILE 'DataImport//sourcefile.csv' 
REPLACE INTO TABLE mytable
CHARACTER SET latin1
FIELDS TERMINATED BY ','
IGNORE 1 LINES
(`id`
, `column1`
, `column2`
, `column3`
, `column4`
, `column5`
, `column6`
, `column7`
, `column8`
, `column9`
, `column10`
, `column11`
, `column12`);";

$con=mysqli_connect("localhost","root","mypassword","mydatabase");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
};

$result1 = mysqli_query($con, $sql1);
$result2 = mysqli_query($con, $sql2);
$result3 = mysqli_query($con, $sql3);

if (mysqli_affected_rows($con) > 1) {
  $message ="". mysqli_affected_rows($con). " rows were successfully added to the table!";
} else {
  $message = "" . mysqli_error($con). "has caused the updateto fail";
};

echo $message;

 // To send HTML mail, the Content-type header must be set
require("PHPMailerAutoload.php"); // path to the PHPMailerAutoload.php file.
require("class.phpmailer.php"); 
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $body = "<html>\n"; 
    $body .= "<body style=\"font-family:Verdana, Verdana, Geneva, sans-serif; font-size:12px; color:#344433;\">\n"; 
    $body = $message; 
    $body .= "</body>\n"; 
    $body .= "</html>\n";
	
// Additional headers

$subject = 'Daily Import Result' ."\r\n";

   $mail = new PHPMailer();
   $mail->IsSMTP(true);
   $mail->Mailer = "smtp";
   $mail->Host = "smtp.mydomain.co.za";
   $mail->Port = 587; 						// 8025, 587 and 25 can also be used. Use Port 465 for SSL.
   $mail->SMTPAuth = true;
   $mail->SMTPSecure = 'tls';
   $mail->Username = "myusername@mydomain.co.za";
   $mail->Password = "mymailpassword";
   $mail->CharSet = "UTF-8";
   $mail->SMTPOptions = array( 				// Bypass security verification on e-mail. 
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);
   
    
   $mail->From     = 'reportingserver@mydomain.co.za';
   $mail->FromName = 'Reporting Server';
   //$mail->AddAddress('mail1@mydomain.co.za', 'Mail1');   
   //$mail->AddAddress('mail2@mydomain.co.za', 'Mail2');   
   //$mail->AddAddress('mail3@mydomain.co.za', 'Mail3');   
   $mail->AddReplyTo('me@mymailserver.com', 'My Name');
  
   $mail->Subject  = $subject;
   $mail->Body     = $body."\r\n";
   $mail->WordWrap = 50;  
 
   if(!$mail->Send()) {
		echo 'Message was not sent.';
		echo 'Mailer error: ' . $mail->ErrorInfo;
		exit;
   } else {
		echo 'Message has been sent.';
   }

mysqli_close($con); 

?>
Edited by SalientAnimal
Link to comment
Share on other sites

Exactly how much repetition is there? Are all the scripts the same except for the input file and destination table? Are the email messages the same, or how do they vary?

 

The "best" case would be that everything but the file and table are the same. You could then get rid of all the script except for one (since they'll all work the same way) and find a way to provide the missing information: my choice would be an INI file like

[arbitrary_label]
source = DataImport/sourcefile.csv
database = mydatabase
table = mytable
email[] = "Mail 1 <mail1@mydomain.co.za>"
email[] = "Mail 2 <mail2@mydomain.co.za>"
email[] = "Mail 3 <mail3@mydomain.co.za>"
and you invoke the PHP script with the "arbitary_label" argument.

@C:\PHP\php.exe C:\path\to\script.php %*
Command: C:\path\to\batch-file.bat
Arguments: arbitary_label
Load the appropriate data into variables and pass them around as needed.

 

The worst case is the scripts are all totally different. Which I doubt is what you're working with. So reality is probably somewhere between the two.

  • Like 1
Link to comment
Share on other sites

Several things:

  • Don't clutter your PHP scripts with HTML markup, especially when the markup is divided into countless tiny fragments and further obscured by backslash escape sequences. Use proper external mail templates.
  • Write a helper function for sending mails. Most SMPT options are always the same, so there's no reason to go through the same PHPMailer instantiation process over and over again.
  • Why on earth did you break TLS certificate verification? If there's a problem with your TLS connections, fix it, don't castrate the protocol.
  • Your error handling is weird, to say the least. Why do you print internal error messages on the screen? Who is supposed to read them, and what is the reader supposed to do when all relevant information (line numbers, stack traces etc.) are missing? PHP has an error handler which is far better than any ad-hoc solution. I suggest you enable exceptions both for mysqli and for PHPMailer and let PHP do the rest.
  • What's the purpose of the USE query? mysqli has already selected the database at this point.
  • Are the columns really named column1, ... ?
Edited by Jacques1
  • Like 1
Link to comment
Share on other sites

Thanks guys, you answers really add a lot of value. And definitely help me in knowing where I need to do a lot more learning.

 

@requinix

  • The scripts would be just about exactly the same in each scenario yes, with the only difference being the column counts and the destination tables as mentioned. The party/s whom need to be notified of a failed / successful script in some instances may also differ, but this would not be often. 

 

@Jacques1

  • I was actually not aware of TWIG, so will be looking into making use of this and learning more about it.
  • I broke the TSL certification, as I could not get any of my settings to work correctly. The "Send" e-mail address I am using at the moment, is also only for a test scenario, and I will be creating the reporting e-mail address as soon as everything is working. I am still running everything on a "Virtual Environment".
  • The column names are luckily not named as listed here no  :happy-04:
  • I'm not sure how to answer your other comments  :-\
Link to comment
Share on other sites

The scripts would be just about exactly the same in each scenario yes, with the only difference being the column counts and the destination tables as mentioned.

a) If the table structure matches up with the CSV exactly - and the use of columnN names suggests it is - then you don't need to specify the columns at all

b) If the table does not match up, and if PHP can access the CSV file, then it can determine the columns dynamically: open the file, read the header row, count how many columns there are

c) If the table does not match up and PHP can't read the file, then you would have to put that configuration somewhere. Continuing with the INI example,

column[0] = id
column[1] = column1
Throw in the fact that you can read the table structure at runtime and you can probably figure out everything you need to know without having to resort to that third option.

 

The party/s whom need to be notified of a failed / successful script in some instances may also differ, but this would not be often.

But the point is that it could, so you'll need to account for that. You could set up a sort of "default email list" and then override that as needed.

 

 

But those columnN names aren't so great. Can you change those? Make them mirror what's in the CSV, even if that means having to `-quote them?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.