I have a HTML form that is being processed by a php page. I have had it working exactly as I need using mail() but am running into issues with the email part. Sending an email out is very inconsistent which is not acceptable. I understand that mail() only takes care of a small part of the process and the mail servers take care of the heavy lifting.
I am trying out PHPMailer as an alternative. I have it up and running and am able to get mail to go out but some of the functionality is not there.
In my form you can add multiple 'projects' to a single submission. The php is supposed to loop over those projects and create a section for each in the email. Again, this is working with mail() but doesn't always send.
The code I am trying to implement is below. It will send an email but will not loop over the form fields if there are more than one. It will only see the last one entered.
<?php
require 'PHPMailerAutoload.php';
date_default_timezone_set('America/New_York');
$today = date("F j - Y - g:i a");
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mail#example.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'mail#example.com';
$mail->FromName = 'From name';
$mail->addAddress('mail#example.com', 'personName'); // Add a recipient
//$mail->addAddress('mail#anotherexample.com'); // Name is optional
$mail->addReplyTo('mail#example.com', 'replyTO');
//$mail->addCC('cc#example.com');
//$mail->addBCC('bcc#example.com');
$mail->WordWrap = 500; // 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
//VARIABLES FROM FORM FIELDS
$contractor = $_POST['ct'];
$noactive = $_POST['noconactivity'];
$hours = $_POST['hours'];
$project = $_POST['prjx'];
$city = $_POST['cx'];
$street = $_POST['street'];
$from = $_POST['from'];
$to = $_POST['to'];
$crewxtown = $_POST['cxtown'];
$construction = $_POST['construction'];
$mpt = $_POST['mpt'];
$direction = $_POST['direction'];
$police = $_POST['police'];
$optcomments = $_POST['optcomments'];
$submissionemail = $_POST['submissionemail'];
$mail_cm = $_POST['cm'];
$mail_pm = $_POST['pm'];
$intersection = $_POST['intersection'];
$parking = $_POST['parking'];
$count = count($street)-1;
$data = array();
//REPETITIVE VARIABLES
for( $i = 0; $i <= $count; $i++ )
{
$hours0 = $hours[$i];
$street0 = $street[$i];
$from0 = $from[$i];
$to0 = $to[$i];
$crewxtown0 = $crewxtown[$i];
$construction0 = $construction[$i];
$mpt0 = $mpt[$i];
$direction0 = $direction[$i];
$police0 = $police[$i];
$optcomments0 = $optcomments[$i];
$parking0 = $parking[$i];
$intersection0 = $intersection[$i];
$data[] = "$today, $noactive, $contractor, $hours0, $project, $city, $street0, $from0, $to0, $intersection0, $construction0, $mpt0, $crewxtown0, $direction0, $police0, $parking0, $optcomments0, $submissionemail, $mail_cm, $mail_pm\n";
$mail->Subject = $project;
$mail->Body = 'Message content header stuff.<br><br><br><b>Street: </b> ' . $street0;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
}
// WRITING DATA TO CSV TABLE
if(!empty($data)) {
$data = implode('', $data);
$fh = fopen("dailyupdatedata.csv", "a");
fwrite($fh, $data);
fclose($fh);
}
//SUCCESS & FAILURE MESSAGE ON PHP PAGE
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
Here is the mail() code that works but does not consistently send.
<?php
date_default_timezone_set('America/New_York');
$contractor = $_POST['ct'];
$noactive = $_POST['noconactivity'];
$hours = $_POST['hours'];
$project = $_POST['prjx'];
$city = $_POST['cx'];
$street = $_POST['street'];
$from = $_POST['from'];
$to = $_POST['to'];
$crewxtown = $_POST['cxtown'];
$construction = $_POST['construction'];
$mpt = $_POST['mpt'];
$direction = $_POST['direction'];
$police = $_POST['police'];
$optcomments = $_POST['optcomments'];
$submissionemail = $_POST['submissionemail'];
$mail_cm = $_POST['cm'];
$mail_pm = $_POST['pm'];
$intersection = $_POST['intersection'];
$parking = $_POST['parking'];
$count = count($street)-1;
$today = date("F j - Y - g:i a");//
$message = '<html><body>';
$message .= "Please see the info blah blah<br><strong>Date:</strong> $today<br><strong>Submission by:</strong> $submissionemail<br><br>"; // Beginning message content
$data = array();
for( $i = 0; $i <= $count; $i++ )
{
$hours0 = $hours[$i];
$street0 = $street[$i];
$from0 = $from[$i];
$to0 = $to[$i];
$crewxtown0 = $crewxtown[$i];
$construction0 = $construction[$i];
$mpt0 = $mpt[$i];
$direction0 = $direction[$i];
$police0 = $police[$i];
$optcomments0 = $optcomments[$i];
$parking0 = $parking[$i];
$intersection0 = $intersection[$i];
$data[] = "$today, $noactive, $contractor, $hours0, $project, $city, $street0, $from0, $to0, $intersection0, $construction0, $mpt0, $crewxtown0, $direction0, $police0, $parking0, $optcomments0, $submissionemail, $mail_cm, $mail_pm\n";
$message .= "<strong>Project:</strong> $project<br><strong>Active / Not Active:</strong> $noactive<br><strong>Contractor:</strong> $contractor<br><strong>Town:</strong> $city<br><strong>Hours:</strong> $hours0<br><strong>Street:</strong> $street0<br><strong>From:</strong> $from0<br><strong>To:</strong> $to0<br><strong>Intersection:</strong> $intersection0<br><strong>Construction Activity:</strong> $construction0<br><strong>MPT:</strong> $mpt0<br><strong>Crew Town:</strong> $crewxtown0<br><strong>Closure Direction:</strong> $direction0<br><strong>Police & Flaggers:</strong> $police0<br><strong>Parking Restrictions:</strong> $parking0<br><strong>Optional Comments:</strong> $optcomments0<br><br> -- <br><br>"; //Data for message
}
$message .= '</body></html>';
if(!empty($data)) {
$data = implode('', $data);
$fromemail = "email#email.com"; // email#email.com
$subject = $project;
//$headers = "From:" . $fromemail;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: "."Team Traffic "." <email#email.com>" . "\r\n";
mail($submissionemail,$subject,$message,$headers); // Submission Email
mail($mail_cm,$subject,$message,$headers); // C Manager Email
mail($mail_pm,$subject,$message,$headers); // P Manager Email
mail("email#email",$subject,$message,$headers);
//mail($trafficemail,$subject,$message,$headers); // Traffic
$fh = fopen("dailyupdatedata.csv", "a");
fwrite($fh, $data);
fclose($fh);
}
?>
Am I missing a step here? Does PHPMailer not work with looping over variables?
Thank you,
Eric
$mail->Body = 'Message content header stuff.<br><br><br><b>Street: </b> ' . $street0;
You are doing that in a loop, that means your code is overwriting the email body on every iteration and only the last one will stay. And then you exit the loop and send the email.
You should be appending those values to the body instead of overwriting the value.
$mail->Body.="New content for new project";
^
I think $mail->Subject = $project; should be out of the loop.
As for body I think you forgot adding a dot(.=) to accumulate the message.
$mail->Body .= 'Message content header stuff.<br><br><br><b>Street: </b> ' . $street0;
Related
This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 1 year ago.
Ive been on this for a while. What I am trying to do is create a CSV file from the while loop with CODE & QUANTITY then attach it to the email below then send. Any help would be greatly appreciated
$sql = mysql_query("SELECT code, quantity
FROM table
WHERE active = '1'
ORDER BY code Asc");
while($row = mysql_fetch_array($sql)){
$code = $row['code'];
$quantity = $row['quantity'];
//CREATE CSV FILE HERE I THINK?
}
$to = “email#gmail.com” ;
$from = “email#website.com”;
$subject = “Inventory”;
$message = ''<html>Code</html>'';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: Inventory' . "\r\n";
mail($to, $subject, $message, $headers);
I want it to look something like this. The .csv file will be an attachment and Ill still display the regular email below it.
Here you go. But You need the PHPMailer.
Learn how to set up PHPMailer on shared hosting
function create_cvs_from_db($sql)
{
// create a temp location in memory with 5MB
$csv = fopen('php://temp/maxmemory:' . (5 * 1024 * 1024), 'r+');
// add the headers
fputcsv($csv, array("code", "quantity"));
// the loop
while ($row = mysql_fetch_array($sql)) {
$code = $row['code'];
$quantity = $row['quantity'];
// creates a valid csv string
fputcsv($csv, array($code, $quantity));
}
rewind($csv);
// return the the written data
return stream_get_contents($csv);
}
// you need to setup PHPMailer
$mail = new PHPMailer();
// configurations
$mail->isSMTP();
$mail->Host = 'smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Username = '1a2b3c4d5e6f7g'; //your mail username
$mail->Password = '1a2b3c4d5e6f7g'; //your mail password
$mail->SMTPSecure = 'tls';
$mail->Port = 2525;
// now the fun part
$mail->setFrom('info#mailtrap.io', 'Mailtrap');
// the subject of the email
$mail->Subject = 'Test Email via Mailtrap SMTP using PHPMailer';
// if your mail body uses html
$mail->isHTML(true);
$mailContent = "";
$mail->Body = $mailContent;
/**
* now here you attach your file
*/
// the cvs extension is very important
$filename = "summary.cvs";
$mail->addStringAttachment(create_cvs_from_db($sql), $filename);
// now send the mail
if ($mail->send()):
echo 'Message has been sent';
else:
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
endif;
I'm trying to send an email to multiple recipients using phpmailer and getting the emails list from my table in the database, however, whenever I make a request only one recipient, the first one on the list gets the email. *I know this might be marked as duplicate but I couldn't find a similar example using mysql
<?php
if (isset($_POST['submit'])) {
if (empty($errors)) {
$thisType = mysql_prep($_POST["partner_type"]);
$content = $_POST["content"];
$header = $_POST["header"];
$query = "SELECT * FROM partners_list WHERE partner_type = '$thisType' ";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result)){
require_once("phpMailer/class.phpmailer.php");
require_once("phpMailer/class.smtp.php");
require_once("phpMailer/language/phpmailer.lang-uk.php");
$to_name = "Order";
$subject = $header;
$message = $content;
$message = wordwrap($message,70);
$from_name = "thisCompany";
$from = "noreply#thicCompany.com";
$mail = new PHPMailer();
$mail->AddAddress($row['email'], "Test Message"); // add each DB entry to list of recipients
$mail->FromName = $from_name;
$mail->From = $from;
$mail->Subject = $subject;
$mail->Body = $message;
$result = $mail->Send();
// Success
$_SESSION["message"] = "e-mail successfully sent.";
redirect_to("successpage.php");
}
}
} else {
}
?>
I am having issues with my phpMailer script. I can email from the script, I can even send attachments from the script. However, it only works SOMETIMES and not at other times. I tried changing servers and I have the same issues so I am assuming that it is a coding issue.
when It does not work, the emails still go thorough but it is stripped from any attachments.
The attachments are definitely making it onto the server in the same location and then this script is sent an array of attachments which it then adds onto the message.
In one instance the same code and same files will send and not send! Very confusing! Usually some will send for awhile and then some will not for awhile.
Here is the code:
<?php
include('connection.php');
require_once('PHPMailer/PHPMailerAutoload.php');
class Mailer extends PHPMailer {
public function copyToFolder($folderPath) {
$message = $this->MIMEHeader . $this->MIMEBody;
$path = "INBOX" . (isset($folderPath) && !is_null($folderPath) ? ".".$folderPath : ""); // Location to save the email
$imapStream = imap_open("{mail.server.com:143/novalidate-cert}" . $path , $this->Username, $this->Password) or die(mysql_error());
imap_append($imapStream, "{mail.server.com:143/novalidate-cert}" . $path, $message)or die(mysql_error());
}
imap_close($imapStream);
}
}
$from = $_POST['from'];
$username = $from;
$grabPassword = mysql_query("SELECT * FROM `email_pw_db` WHERE `emailaddress` = '$from'");
$fetchPassword = mysql_fetch_assoc($grabPassword);
$password = $fetchPassword['password'];
$company = $_POST['to'];
$toemail = $_POST['toemail'];
$from = $username;
$namefrom = $_POST['from'];
$subject = $_POST['subject'];
$cc = trim($_POST['cc']);
$bcc = trim($_POST['bcc']);
$message = $_POST['body'];;
$attachments = $_POST['attachments'];
$mail = new Mailer();
$body = $message;
/*Create a new email*/
$mail = new Mailer();
$mail->isSMTP();
$mail->Host = 'mail.server.com';
$mail->Username = $username;
$mail->Password = $password;
$mail->From = $from;
$mail->AddReplyTo($from,$namefrom);
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->SetFrom($from, $namefrom);
$mail->AddReplyTo($from,$namefrom);
$address = $toemail;
$mail->AddAddress($address, $company);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
if($cc!=''){
$mail->addCC($cc);
}
//CC EMAILS//
$breakOutCC = explode(',', $cc);
$countBreakOut = count($breakOutCC);
$i = 0;
while($i <$countBreakOut)
{
$mail->addCC($breakOutCC[$i]);
$i++;
}
$breakOutBCC = explode(',', $bcc);
$countBreakOutBCC = count($breakOutBCC);
$i = 0;
while($i <$countBreakOutBCC)
{
$mail->addBCC($breakOutBCC[$i]);
$i++;
}
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
$mail->AddAttachment("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
$errorMessage = $mail->ErrorInfo;
header( 'Location: email-software.php?dialog=Whoops Something Happened- '.$errorMessage ) ;
} else {
//$mail->copyToFolder(); //save email
$mail->copyToFolder("Sent"); // Will save into Sent folder
$attachments = $_POST['attachments'];
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
unlink("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
header( 'Location: email-software.php?dialog=email sent' ) ;
}
?>
This question already has answers here:
PHP send email foreach - send to
(2 answers)
Closed 8 years ago.
I would like to know how to make a loop to make it send email to each checked row from php table.
Here's the table row for checkboxes:
echo "<input name=\"approve[]\" type=\"checkbox\" value='".$row["id"]."' >";
Approve php:
$pfw_header .= "MIME-Version: 1.0\r\n";
$pfw_header .= "Content-type: text/html; charset=utf-8\r\n";
$fromName = "HP EG NPI - Registracija";
$fromEmail = "hp_eg_npi#eventregistration.rs";
$toEmail = "$email";
$subject = "Prijava prihvacena";
function sendEmail ($fromName, $fromEmail, $toEmail, $subject, $emailBody, $pfw_header) {
$mail = new PHPMailer();
$mail->FromName = $fromName;
$mail->From = $fromEmail;
$mail->AddAddress("$toEmail");
$mail->Subject = $subject;
$mail->Body = $emailBody;
$mail->isHTML(true);
$mail->WordWrap = 150;
if(!$mail->Send()) {
return false;
} else {
return true;
}
}
function readTemplateFile($FileName) {
$fp = fopen($FileName,"r") or exit("Unable to open File ".$FileName);
$str = "";
while(!feof($fp)) {
$str .= fread($fp,1024);
}
return $str;
}
//Data to be sent (Ideally fetched from Database)
$name = "$first_name";
$lastname = "$last_name";
$UserEmail = "$email";
//Send email to user containing username and password
//Read Template File
$emailBody = readTemplateFile("../html-email/mail2.html");
//Replace all the variables in template file
$emailBody = str_replace("#username#",$fnames,$emailBody);
$emailBody = str_replace("#password#",$lnames,$emailBody);
//Send email
$emailStatus = sendEmail ($fromName, $fromEmail, $UserEmail, $subject, $emailBody, $headers);
}
}
}
I have tried searching around the internet, but couldn't manage to find a solution.
Thanks in advance!
You could just do:
$mail = new PHPMailer();
$mail->FromName = $fromName;
$mail->From = $fromEmail;
foreach($emails as $email) {
$mail->AddAddress("$email");
}
$mail->Subject = $subject;
$mail->Body = $emailBody;
$mail->isHTML(true);
$mail->WordWrap = 150;
if(!$mail->Send()) {
return false;
} else {
return true;
}
You don't need the sendEmail function.
So I'm trying to use PHPMailer to handle the email form on my website.
I wrote the code here based on a tutorial I found.
<?php
error_reporting(E_ALL);
require_once("class.phpmailer.php");
include("class.smtp.php");
$email = new PHPMailer();
//
// Set server details for send
//
$email->IsSMTP();
$email->Host = "mail.loganyoung.za.net";
$email->Port = 25;
$email-SMTPAuth = true;
$email->Username = "<my email>";
$email->Password = "<my password>";
//
// Send mail from the contact form
//
$to = "<my email>";
$from = $_POST["from"];
$name = $_POST["name"];
$subject = "From web: ".$_POST["subject"];
$message = $_POST["message"];
$body = "<p>Hi Logan,</p>";
$body .= "<p>You have received a new query on your website.<br />Please see below:</p>";
$body .= "<p>";
$body .= str_replace("\r\n", "<br />", $message);
$body .= "</p>";
$email->SetFrom($from, $name);
$email->AddReplyTo($from, $name);
$email->AddAddress($to, "LoganYoung.za.net");
$email->Subject = $subject;
$email->Body = $body;
$email->IsHTML = true;
session_start();
if(!$email->Send()) {
$_SESSION["mailresult"] = "success";
echo "success";
} else {
echo "<p>Failed:</p><p>".$email->ErrorInfo."</p>";
$_SESSION["mailresult"] = "failed";
$_SESSION["mailerror"] = $email->ErrorInfo;
}
?>
I figure possible reasons for it not sending could be...
Incorrect SMTP details (possibly send without SMTP auth to resolve?)
Handler isn't getting POST data (the ajax that sends it seems to work fine though)
Some problem with this code that I'm not able to identify...
As a means of eliminating possibilities, can anyone spot anything wrong with the code here? If so, what's wrong, and how do I fix it?
Thanks in advance!
$email-SMTPAuth = true;
Isn't that supposed to be:
$email->SMTPAuth = true;