I have a script that sends emails to users, which are sometimes divided into multiple messages depending on size. Here's the code:
for($i=0; $i<count($the_message); $i++){
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->Host = "my.smtp.server";
$mail->Port = $email_port;
$mail->Username = "my#email.com";
$mail->Password = "mypassword";
$mail->SMTPAuth = true;
$mail->From = $from;
$mail->FromName = "My Name";
$mail->IsHTML($is_html);
if($is_html === TRUE){
$mail->AltBody = "To view the message, please use an HTML compatible email client, or change your export to a plain text format.";
}
foreach($to as $address){
$mail->AddAddress($address);
}
$mail->Body = $the_message[$i];
$mail->Subject = $the_sub;
$mail->Send();
}
This used to work great. Now, it seems that certain messages will never send. It seems to be a data issue (or perhaps the way PHPMailer sends lines to the server?), but I can't pinpoint why certain message segments are always rejected by the server.
The error message I get from PHPMailer is this:
SMTP Error: Data not accepted.
And from PHP itself:
Notice: fputs(): send of 31 bytes failed with errno=104 Connection
reset by peer in class.smtp.php on line 580
Here is a segment of HTML data that always fails to send:
http://pastebin.com/LGYkTTFA
Note that size isn't an issue, I can successfully send much larger HTML messages than this. However, when I send multiple segments, this one is never accepted by the server.
Here, I rewrote it for you in a somewhat saner way. You don't need to create everything from scratch every time around the loop, just change the body and send again.
<?php
require 'PHPMailerAutoload.php';
$the_message = array('Hello', 'there', 'Justin');
$to = array('tom#example.com', 'dick#example.net', 'harry#example.org');
$the_sub = 'Crazy subject';
$email_port = 25;
$from = 'justin#example.com';
$is_html = true;
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->Host = "localhost";
$mail->Port = $email_port;
$mail->Username = "my#email.com";
$mail->Password = "mypassword";
$mail->SMTPAuth = true;
$mail->From = $from;
$mail->FromName = "My Name";
$mail->Subject = $the_sub;
$mail->IsHTML($is_html);
$mail->WordWrap = 200;
if($is_html){
$mail->AltBody = "To view the message, please use an HTML compatible email client, '.
'or change your export to a plain text format.";
}
foreach($to as $address){
$mail->AddAddress($address);
}
for($i=0; $i<count($the_message); $i++){
$mail->Body = $the_message[$i];
$mail->setWordWrap();
$mail->Send();
}
Update: added word wrapping to deal with content with very long lines.
In class.smtp.php, line 51, I changed the constant MAX_LINE_LENGTH from 998 to 500. This allowed all of my email segments to pass through.
I'm still not sure if the issue lies with my SMTP server or PHPMailer, I'll have to test it elsewhere.
EDIT: Tested using Gmail's SMTP server, and keeping 998 worked fine. This leads me to assume that my SMTP relay server is rejecting data sometimes depending on the length.
EDIT2: Still experienced failures with the above fix. I changed my port number and added SSL, and it is magically working. Wonky server issues...
Related
Something weird is going on when i'm trying to send an e-mail with attachment to gmail, using phpmailer.
Sometimes the email received after a delay of 5 minutes and sometimes it is never received. From phpmailer debugger i get that the email is actually sended, so i assume it has something to do with the attachment getting blocked by gmail.
The attachment is a zip file containing only .jpg and .pdf files.
If i remove the addAttachment('path/to/file') everything works fine.
The weird thing is that sometimes, even with the attachment, the email received immediately and other times the email never gets received.
Here is the code
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = 'my_host';
$mail->Port = 'my_port';
$mail->SMTPAuth = true;
$mail->Username = 'my_username#domain.com';
$mail->Password = 'my_password';
$mail->setFrom('my_username#domain.com', 'my_username#domain.com');
$mail->addAddress('test#gmail.com', 'test#gmail.com');
$mail->Subject = $subject;
$mail->msgHTML($msg);
$mail->AltBody = $subject;
$mail->addAttachment($zipfilename);
if($mail->send()){
echo "ok";
}else{
echo "error";
}
I don't have any clue why this is happening so any help will be appreciated.
EDIT:
I found out that with two changes everything works fine.
The changes are the setting
$mail->SMTPSecure = 'tls'
and i had a path like this ./path/to/file and changed it to 'path/to/file'.
I keep on having the 500 internal sever error with my web hosted by GoDaddy, using the PHPmailer; I've tried several solutions available on StackOverflow relating to my challenge, but none of them worked.
Here is my code:
require 'phpmailer/PHPMailerAutoload.php';
$feedback='';
$flag = array();
if(isset($_POST["submitlogin"]) and $_SERVER['REQUEST_METHOD'] == "POST"){
$name = seo_friendly_url($_POST['name']);
$email = seo_friendly_url($_POST['email']);
$subject = seo_friendly_url($_POST['subject']);
$message = seo_friendly_url($_POST['message']);
//Email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$feedback="Invalid email format";
array_push($flag,"false");
}else {
array_push($flag,"true");
}
//Email
//Name
if (preg_match('/^[-a-zA-Z0-9._]+$/', $name)){
array_push($flag,"true");
}else {
$feedback="Invalid name format";
array_push($flag,"false");
}
//Name
if (!in_array("false", $flag)) {
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "smtpout.asia.secureserver.net";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
//$mail->Username = 'email#email.com';
//$mail->Password = 'password';
$mail->SMTPAuth = false;
//Set who the message is to be sent from
$mail->setFrom('email#email.com');
//Set an alternative reply-to address
$mail->addReplyTo($email);
//Set who the message is to be sent to
$mail->addAddress('email#email.com'); // Add a recipient
$mail->addAddress('email#email.com');
$mail->addAddress('email#email.com);
//Set the subject line
$mail->Subject = 'HLS Inquiry';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML($message);
$email_ar = $email;
$subject_ar = $name.", Thank you for your Inquiry";
$acknowledgement_receipt = '
<div style="padding:10px 20px;font-size:16px;">
<p>Dear '.$name.',</p>
<p>We've received your message and would like to thank you for contacting us. We will reply by email shortly.</p>
<p>Talk to you soon,</p>
<p>
<div>Customer Service</div>
</p>
</div>
';
if ($mail->send()) {
$feedback = "<span style='color:green;'>Thank you for your inquiry. We will respond to you within 24 hours.</span>";
}
}
Please note that I replaced some of the email values as: email#email.com for my privacy.
I believed that the email setups are correct because I already used those setups from my friend's website hosted by JustHost.
This line is missing a single quote:
$mail->addAddress('email#email.com);
This is quite obvious in SO because you can see how the syntax highlighting breaks at that point.
When you get an error 500 and nothing is displayed, it's a sign that you should be looking in your web server's error log.
There is a "split" function used to write the PHPMailer class. This function has been long deprecated and as such gives error in later PHP versions.
Find them and replace with "explode".
This worked for me.
i send email with PHPMailer, my code is:
$mail = new PHPMailer(true);
$mail->Mailer = "smtp";
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 0;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Username = "nati323#gmail.com";
$mail->Password = "****";
$mail->addCustomHeader('Content-Type: text/plain; charset="utf-8"');
$mail->SMTPAuth = true;
$mail->Port = 587;
$mail->From = $from;
$mail->AddAddress($to);
$mail->Subject = $subject;
$mail->Body = $msg;
return $mail->Send();
the $msg variable is a function parameter i use it like this:
function sendMail ($to, $subject, $msg, $from, $add = null)
and i use it like this:
sendMail($_POST['mail'], $text['EMAIL_RECOVER_MSG_SUBJECT'], $text['EMAIL_RECOVER_MSG'], $from)
the variables contain:
$text['EMAIL_RECOVER_MSG_SUBJECT'] = 'Password Recover: From dmworld24.com';
$text['EMAIL_RECOVER_MSG'] = 'You Forget Your Password To Recover it Please Go Into The Next Link:\r\n http://dmworld24.com/login.php?act=rec&token={TOKEN}&mail={MAIL} \r\n If You Didnt Ask For Password Recovering Just Ignore This Message';
$from = 'System#dmworld24.com';
now i try to add line break to message for example:
You Forget Your Password To Recover it Please Go Into The Next Link:\r\n http://dmworld24.com/login.php?act=rec&token=7054343021*****353214&mail=nati323#gmail.com \r\n If You Didnt Ask For Password Recovering Just Ignore This Message
and what i get in the mail is the same, the \r\n shows as chars and there is not line breaks, what i did wrong?
another problem that i have, that the form method dosent work, i send email for try to nati323#gmail.com , and i connect to smtp server with nati323#gmail.com acount, and i always get the message from my self, and the Form that i defined dosent show....
You're using single quotes in your message. That will take everything contained in it literally, which is why you're getting the literal string \r\n.
Replace the single quotes with double quotes to get the new line properly output.
I.e.
$text['EMAIL_RECOVER_MSG'] = "You Forget Your Password To Recover it Please Go Into The Next Link:\r\n http://dmworld24.com/login.php?act=rec&token={TOKEN}&mail={MAIL} \r\n If You Didnt Ask For Password Recovering Just Ignore This Message";`
Call the PHP function nl2br() to convert newlines to HTML line breaks. And then, setup PHPMailer to sent email as an html using $mail->IsHTML(TRUE);
I got a contact us page using PHP. Like all contact us, after someone clicking send, it will send a warning to my email.
The problem is it doesn't work. The script works perfectly in my localhost, it doesn't work only on the server and it doesn't show any error.
$default_path = get_include_path();
set_include_path(dirname(__FILE__)."/../");
require_once("extensions/PHPMailer/class.phpmailer.php");
set_include_path($default_path);
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->SMTPSecure="ssl";
$mail->Host="smtp.gmail.com";
$mail->SMTPDebug =0;
$mail->Port=465;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = Yii::app()->params['sender_email']; // SMTP username
$mail->Password = Yii::app()->params['sender_password']; // SMTP password
$webmaster_email = Yii::app()->params['webmaster_email']; //Reply to this email ID
$mail->From = $email_address;
$mail->FromName = "Webmaster";
$mail->AddAddress($email_address,"");
$mail->AddReplyTo($webmaster_email,"Webmaster");
$mail->WordWrap = 70; // set word wrap
//$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
$mail->IsHTML(true); // send as HTML
$mail->Subject = $mailcontent->subject;
$mail->Body = $mailcontent->body;
//$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
$mail->Send();
I think it's because of server misconfiguration(this is my first time settings a server), but i didn't know what i did wrong.
The firewall already set to allow every traffic, so it's not firewall problem.
No error and no results makes me very confused.
Okay, after I checked everything, it turns out google block my email access from the server because of suspicious activity.
To unblock this, you need to visit this page : https://accounts.google.com/DisplayUnlockCaptcha
and then run the script again.
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