PHPMailer - Multiple text messages to single recipient - php

I have a portion of my project that grabs some customer information from a DB and sends a text-message to a salesman, using PHP Mailer. Some of the customer info included:
Name
Phone
Phone 2
Address
City
State
Zip
Notes
As you can imagine, 160 characters won't cut it. I need to be able to send at least two text messages to the same number within the same function.
I have a single text message working, using PHP Mailer. I will post the relevent code below:
db_functions.php:
function send_text($name, $message){
require 'class.phpmailer.php';
$to = 'xxxxxxxxxx#vtext.com';
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "xxxxxx#gmail.com";
$mail->Password = 'xxxxxxx';
$mail->SetFrom('xxxxxx#gmail.com');
$mail->Subject = $name;
$mail->Body = $message;
$mail->AddAddress($to);
$mail->Send();
$mail->ClearAddresses();
return;
}
assign_lead.php:
include 'mysql_login_pdo.php';
include '../functions/db_functions.php';
if (!isset($_POST['leadID'])) {
return;
} else {
$leadID = $_POST['leadID'];
}
if (!isset($_POST['salesID'])) {
return;
} else {
$salesID = $_POST['salesID'];
}
//DB FUNCTIONS
db_assignLead($leadID, $salesID);
$message = db_assignLeadNote($leadID);
$name = db_assignLeadName($leadID);
db_assignAddNote($leadID, $message);
//-------------------------This is the problematic area---------------------
//SEND TEXT MESSAGE(s)
send_text($name, $message);
$message = '8104124200_230 N Main St_Davison_48423';
send_text($name, $message);
As you can see, I want a text message to send to a salesman with the customer's name and a note about the customer. Then, I want to send a second text message with the customer's name and address information. I've used a placeholder of '8104124200_230 N Main St_Davison_48423' for now, but it will be replaced by a function that searches for the address info in the DB.
The first text message sends fine, but the second refuses to send. I made it work once by using a 20-second sleep, but from what I've read, it may be unnecessary. Also, the 20-second sleep was completely unreliable.
As always, I appreciate any help.

I ended up doing the following, which worked. I'm hoping it won't cause issues down the road, but if it does, I'll come back and update this post.
Basically, instead of calling the send_text() function twice, I sent the message twice within the same function:
function send_text($name, $message){
include 'class.phpmailer.php';
//$to = $_POST['to'];
//$password = $_POST['password'];
$to = 'xxxxxx#gmail.com';
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "xxxxxx#gmail.com";
$mail->Password = 'xxxxxx';
$mail->SetFrom('xxxxxx#gmail.com');
$mail->Subject = $name;
$mail->Body = $message;
$mail->AddAddress($to);
$mail->Send();
//Send the second message
$mail->Body = 'Testing second message';
$mail->Send();
//End Second message
return;
}

Related

PHPMailer not sending all emails to last email address

I am using PHPMailer to send emails. I have created a function that sends 3 emails to 3 different email addresses (sending 9 emails in total).
The first email address is receiving all the 3 emails.
The second email address is receiving 2 emails.
The third email address is receiving only 1 email.
Why this happening?
Here is my code:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'lib/phpmailer/vendor/autoload.php';
$mail = new PHPMailer(true);
$mail1 = phpmaileremail($reciever1, $usertype1, $file, $subject1, $body1);
$mail2 = phpmaileremail($reciever2, $usertype2, $file, $subject2, $body2);
$mail3 = phpmaileremail($reciever3, $usertype3, $file, $subject3, $body3);
function phpmaileremail($reciever,$usertype, $file, $subject, $body)
{
global $mail;
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'xxx#gmail.com';
$mail->Password = 'xxx';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('xxx', 'xxx');
$mail->addAddress($reciever);
$mail->addAddress($reciever, $usertype);
$mail->addAttachment($file);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = 'NA';
$mail->send();
echo "Mail sent";
}
Because you're reusing the $mail object to addAddress() and send(). So the first time you call phpmaileremail() the first address gets the email. Then when you call it for the second time the second address is added and the first and second address get the email. And so on.
A simple solution would be to create the $mail object inside the phpmaileremail() function:
function phpmaileremail($reciever,$usertype, $file, $emailsubject, $email_body )
{
$mail = new PHPMailer(true);
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com;';
$mail->SMTPAuth = true;
$mail->Username = 'XXXXXXXX#gmail.com';
$mail->Password = 'XXXXXXXXXXXXXXXXXX';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('XXXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXX');
$mail->addAddress($reciever);
$mail->addAddress($reciever, $usertype);
// Attachments
$mail->addAttachment($file); // Add attachments
$mail->isHTML(true);
$mail->Subject = $emailsubject;
$mail->Body = $email_body;
$mail->AltBody = 'NA';
$mail->send();
echo "Mail sent";
}
PS: Not that it matters, but reciever is written receiver. I've made that mistake as well.
Kiko's answer will work, however it's not the best way. As its name suggests, addAddress adds an address, it doesn't set absolutely or replace existing recipients you've already added.
PHPMailer has a standard function to clear the list of addresses you're ending to called clearAddresses, so the right approach is to call that after each message you send and add the new address before sending the next one, so the sequence will be roughly:
addAddress();
send();
clearAddresses();
addAddress();
send();
and so on. This is most clearly demonstrated in the mailing list example provided with PHPMailer, which does its sending in a loop, calling clearAddresses each time around.
You can achieve the same thing using a new instance of PHPMailer each time (which has the effect of clearing addresses, but also clears everything else too), but it's more efficient to re-use the instance. This is especially true if you're sending over SMTP (which you are) because it will allow you to make use of keepalive, which dramatically reduces the overhead of making an SMTP connection. If you use a new instance, the connection is dropped and recreated each time. You can achieve this inside your function by making the PHPMailer instance static:
function phpmaileremail($reciever, $usertype, $file, $emailsubject, $email_body)
{
static $mail;
if ($mail === null) {
//Set everything that remains the same all the time in here
$mail = new PHPMailer();
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com;';
$mail->SMTPAuth = true;
$mail->Username = 'XXXXXXXX#gmail.com';
$mail->Password = 'XXXXXXXXXXXXXXXXXX';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->SMTPKeepAlive = true;
$mail->setFrom('XXXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXX');
}
$mail->addAddress($reciever, $usertype);
// Attachments
$mail->addAttachment($file); // Add attachments
$mail->isHTML(true);
$mail->Subject = $emailsubject;
$mail->Body = $email_body;
$mail->AltBody = 'NA';
$mail->send();
$mail->clearAddresses();
$mail->clearAttachments();
echo "Mail sent";
}
This has the added benefit of not using a global. Also note the use of clearAttachments, as that works the same way as addresses.

PHPMailer cannot be resolved

So I am trying to set up a contact us page on a website i am creating but PHPMailer just refuses to work for me.
From what I can see, it just isn't recognizing the PHPMailer class at all and I am not really sure why. Here is my PHP code for the form to send the email, as far as i can tell i have correctly installed PHPMailer/Composer, and have done everything else correctly, but i still get errors when trying to use PHPMailer at all. "PHPMailer cannot resolved to a type" and "The import PHPMailer\PHPMailer\PHPMailer cannot be resolved"
<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once './vendor/autoload.php';
// Bunch of code validating all the variables from the form
function send_mail($toEmail, $endSubject, $endMessage, $endName) {
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = "smtp.domain.com";
$mail->SMTPAuth = true;
$mail->Username = "LOGIN EMAIL"; // Email
$mail->Password = "PASSWORD"; // Email password
$mail->SMTPSecure = "tls";
$mail->Port = "587";
$mail->From = "example#domain.com"; //RANDOM EMAIL TO SEND THESE MESSAGES TO OUR EMAIL
$mail->FromName = $endName; //CUSTOMERS NAME
$mail->addAddress($toEmail); //WHOEVER WE ARE SENDING THESE EMAILS TO
$mail->isHTML(true);
$uri = 'http://'. $_SERVER['HTTP_HOST'];
$mail->Subject = $endSubject;
$mail->Body = $endMessage;
if($mail->send()) {
return true;
} else {
return false;
}
}
?>

PHP sending emails to but not text

I am trying to send emails to phones that have Verizon numbers. Here is my code right now
<?php require('includes/config.php');
function Send( $ToEmail, $MessageHTML, $MessageTEXT) {
require_once ( 'classes/phpmailer/phpmailer.php' ); // Add the path as appropriate
$Mail = new PHPMailer();
$Mail->IsSMTP(); // Use SMTP
$Mail->Host = "box405.bluehost.com"; // Sets SMTP server
$Mail->SMTPDebug = 2; // 2 to enable SMTP debug information
$Mail->SMTPAuth = TRUE; // enable SMTP authentication
$Mail->SMTPSecure = "ssl"; //Secure conection
$Mail->Port = 465; // set the SMTP port
$Mail->Username = 'techsupport#test.com'; // SMTP fake account username
$Mail->Password = 'password1'; // SMTP fake account password
$Mail->Priority = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
$Mail->CharSet = 'UTF-8';
$Mail->Encoding = '8bit';
$Mail->ContentType = 'text/html; charset=utf-8\r\n';
$Mail->FromName = 'Tech support';
$Mail->WordWrap = 900; // RFC 2822 Compliant for Max 998 characters per line
$Mail->AddAddress( $ToEmail ); // To:
$Mail->isHTML( TRUE );
$Mail->Body = $MessageHTML;
$Mail->AltBody = $MessageTEXT;
$Mail->Send();
$Mail->SmtpClose();
if ( $Mail->IsError() ) { // ADDED - This error checking was missing
return FALSE;
}
else {
return TRUE;
}
}
$stmt = $db->prepare("select phone From members where phone not like 'no';");
$stmt->execute();
$result = $stmt->fetchAll();
$ToEmail = $result[0][0];
$ToName = 'techsupport';
$MessageHTML = "test";
$MessageTEXT = 'test';
$Send = Send( $ToEmail, $MessageHTML, $MessageTEXT);
if ( $Send ) {
echo "<h2> Sent OK</h2>";
}
else {
echo "<h2> ERROR</h2>";
}
die;
?>
this works when I try to send emails but when I use it to send texts it says sent but I do not receive anything. I know this is not because of the address because I use the same address when I text myself from gmail and it is not the sql query because I have tested it . I Think the problem is in the smtp or phpmailer for I have not used either of those a lot. Also the code runs though and prints out the SENT OK echo but nothing goes through and no errors.
[EDIT] To answer ironcito's question I am sending the email to
phonenumber#vtext.com
I know this works because I have used the same address through gmail.
I think this might be because you push the content to the mail (body) before you set the content (messagehtml/messagetext), which creates an empty email. Try changing these around, that might be the solution.

PHPMailer Send an email through a Local Domain but from a regular Email

I am trying to setup PHPMailer for a customer. He has his own mail server located at a certain IP address. When asked to give me the information to send email through the system, he gave the following:
Host: xx.xxx.x.x
Port: 25
Domain: mydomain.local
Username: myemail#mydomain.local
Password: <myemailpassword>
From: myemail#anotherdomain.xx
(Which he confirmed is being used for external email sending)
I tried to setup PHPMailer by setting the parameters to the exact namings above.
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "xx.xxx.x.x";
$mail->Port = 25;
$mail->Username = "myemail#mydomain.local";
$mail->Password = <myemailpassword>;
$mail->SetFrom('myemail#anotherdomain.xx', 'Webname');
$mail->[...]
I got the following error:
Failed to connect to server (0)
So I try to send an email through telnet to check if it's the customer's email server or the PHPMailer settings:
telnet xx.xxx.x.x 25
It goes through, I'm connected to the server.
helo mydomain.local
I'm getting 'Hello' as a reply. This leads me to believe it might be the PHPMailer settings that are wrong here.
I also try not using SMTP:
$mail->Host = "ssl://xx.xxx.x.x";
$mail->Port = 25;
$mail->Username = "myemail#mydomain.local";
$mail->Password = "password";
$mail->SetFrom('myemail#anotherdomain.xx', 'Webname');
$mail->[...]
Again no go. Am I going about this wrong? I'm only familiar with setting up PHPMailer to use Gmail before so I'm at a loss as to what could be the issue because I'm using a 'personal' email server.
Thanks Loadparts for your assistance.
I'm still not sure what the issue was but it seems it has resolved itself. It might have been from the email server side because coding wise, I didn't change anything. This is the final code I used.
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Port = 25;
$mail->Host = "xx.xxx.x.x"; // SMTP server
$mail->Username = "myemail#mydomain.local";
$mail->Password = <myemailpassword>;
$mail->From = "myemail#anotherdomain.xx";
$mail->FromName = <Web_Name>;
$mail->AddAddress("email#domain.com");
$mail->Subject = <Subject>;
$mail->AltBody = <Alt_Body>
$mail->WordWrap = 80;
$body = "test message";
$mail->MsgHTML($body);
$mail->IsHTML(true);
$mail->Send();
I use a test function that I know works 100% to test the email servers when using PHPMailer.
I'm not sure why you are having your problem, but try to use the function I have ( I know it's messy but it does the trick). Just replace all the XXXX with your info and make sure you have both class.phpmailer.php and class.smtp.php in the same folder.
<?php
error_reporting(E_ALL);
$toemail = 'XXXX';
$toname = 'XXXX';
$subject = 'Testing Email Sending...';
$bodyhtml = '<H1>yeah</h1>';
$bodytext = 'heres Hoping it works';
$fromemail = 'XXXX';
$fromname = 'XXXX';
var_dump(sendemail($toemail,$toname,$subject,$bodyhtml,$bodytext,$fromemail,$fromname));
function sendemail($toemail,$toname,$subject,$bodyhtml,$bodytext,$fromemail,$fromname)
{
require_once("class.phpmailer.php");
$mail = new phpmailer();
$mail->IsSMTP();
$mail->From = $fromemail;
$mail->FromName = $fromname;
$mail->Host = "XXXX";
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "XXXX"; // SMTP username
$mail->Password = "XXXX"; // SMTP password
$mail->Port="25";
$mail->SMTPDebug=true;
if(strlen($bodyhtml)>0) {
$mail->Body = $bodyhtml;
$mail->IsHTML(true);
}
else if(strlen($bodytext)>0){
$mail->Body = $bodytext;
}
if(strlen($bodytext)>0 && strlen($bodyhtml)>0){
$mail->AltBody = $bodytext;
}
$mail->AddReplyto($fromemail,$fromname);
$mail->Subject = $subject;
// Check if multiple recipients
if(preg_match("/;/",$toemail))
{
$tmp_email=preg_split("/;/",$toemail);
$tmp_contact=preg_split("/;/",$toname);
$mail->AddAddress($tmp_email[0], $tmp_contact[0]);
// echo "<!-- multi email:".$tmp_email[0]." contact:".$tmp_contact[0]." -->\n";
for($j=1;$j<count($tmp_email);$j++)
{
if(preg_match("/\#/",$tmp_email[$j]))
{ $mail->AddCC($tmp_email[$j], $tmp_contact[$j]);
// echo "<!-- multi email cc:".$tmp_email[$j]." contact:".$tmp_contact[$j]." -->\n";
}
}
}
else{
$mail->AddAddress($toemail, $toname);
}
$error= false;
if($mail->Send()){
$error =true;
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
return $error;
}
If this doesn't work, my first try would be using port 80 - which usually isn't blocked, then you can work on getting SSL to work.
PS: because it's a local domain, you may want to consider adding the domain to your /etc/hosts just to be sure.
Best of Luck!

Sending 2 emails with PHP mailer fails

I am rather puzzled with this one.
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
if($mail->Send())
{
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->ClearCustomHeaders();
...
$mail->From = "DO_NOT_REPLY#...";
$mail->FromName = "****";
$mail->AddAddress($ToEmail1, "***"); //To: (recipients).
$mail->AddAddress($ToEmail2, "***"); //To: (recipients).
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $notification_subject;
$mail->Body = $notification_msg;
if($mail->Send())
{
...
The first email sends fine. The second one doesn't. What could be the reason for that behavior? Am I missing some kind of reset?
Update: using a different mail server seems to work so apparently it's a setting of that specific mail server causing problems. Any idea what that could be?
Some providers impose restrictions on the number of messages that can be sent within a specific time span. To determine if your problem depends by a provider "rate limit", you should try to add a pause after the first send. For example:
if ($mail->Send()) {
sleep(10); // Seconds
...
if ($mail->Send()) {
...
}
}
Then, by progressively lowering the sleep time, you should be able to determine which is the rate limit.
Try this:
As #Felipe Alameda A mentioned Remove $mail->SMTPKeepAlive = true;
// for every mail
if(!$mail->Send())
{
echo 'There was a problem sending this mail!';
}
else
{
echo 'Mail sent!';
}
$mail->SmtpClose();
IMHO you need to create new PHPMailer object for every sent email. If you want to share some common setup, use something like this:
$mail = new PHPMailer();
/* Configure common settings */
while ($row = mysql_fetch_array ($result)) {
$mail2 = clone $mail;
$mail2->MsgHTML("Dear ".$row["fname"].",<br>".$cbody);
$mail2->AddAddress($row["email"], $row["fname"]);
$mail2->send();
}
I think your problem is $mail->SMTPAuth = false;
It is hard to believe there are ISP or SMTP providers that don't require authentication, even if they are free.
You may try this to check for errors instead of or in addition to checking for send() true:
if ( $mail->IsError() ) { //
echo ERROR;
}
else {
echo NO ERRORS;
}
//Try adding this too, for debugging:
$mail->SMTPDebug = 2; // enables SMTP debug information
Everything else in your code looks fine. We use PHPMailer a lot and never had any problems with it
The key may lie in the parts you have omitted. Is the domain of the sender of both emails the same? Otherwise the SMTP host may see this as a relay attempt. If you have access to the SMTP server logs, check these; they might offer a clue.
Also, check what $mail->ErrorInfo says... it might tell you what the problem is.
i personally would try to make small steps like sending same email.. so just clear recipients and try to send identical email (this code works for me). If this code passes you can continue to adding back your previous lines and debug where it fails
and maybe $mail->ClearCustomHeaders(); doing problems
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
// all above is copied
if($mail->Send()) {
sleep(5);
$mail->ClearAllRecipients();
$mail->AddAddress('another#email.com'); //some another email
}
...
Try with the following example.,
<?php
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.yourdomain.com"; // sets the SMTP server
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address1 = "whoto#otherdomain.com";
$address2 = "whoto#otherdomain.com";
$mail->AddAddress($address1, "John Doe");
$mail->AddAddress($address2, "John Peter");
$mail->AddAttachment("images/phpmailer.gif"); // attachment if any
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment if any
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Note : Better you can make a multiple user email and name as an ARRAY, like
<?php
$recipients = array(
'person1#domain.com' => 'Person One',
'person2#domain.com' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
(or)
foreach($recipients as $email => $name)
{
$mail->AddAddress($email, $name);
}
?>
i think this may help you to resolve your problem.
I think you've got organizational problems here.
I recommend:
Set your settings (SMTP, user, pass)
Create new email object with info from an array holding messages and to addresses
Send email
Goto step 2

Categories