PHPMailer and Mail() both failing? From Address failed - php

require_once("libphp-phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.comcast.net";
//$mail->Host = "localhost";
//$mail->SMTPAuth = true;
$mail->WordWrap = 60;
//$mail->SetFrom("jharvard#cs50.net");
$mail->SetFrom("testmail#example.com");
$mail->AddAddress("kyzcreig#gmail.com");
$mail->Subject = "BUY! Receipt";
$mail->Body =
"You just bought {$_POST["symbol"]}: \n\n";
if ($mail->Send() == false) {
die($mail->ErrInfo);
}
I get this error when I run the above code:
Not sure what it means. I'm fairly new to PHP too so maybe I'm missing something?
If I try to use the generic mail() function that also fails. Although it doesn't give any error message.

I had no default SMTP settings so naturally the default mail() wasn't working. I configured things to use first my gmail account/smtp server and then later (so I could spoof headers) my hostgator smtp server.
This resolved the issue.

Related

PHPMailer slow response time

I'm using PHPMailer to send a forgot password email to users and when the user submits their email to the code below the page takes a few minutes to load!! Im not expecting the email to be send instantly but is there a way to make it so it will redirect the user while still sending the email?
I'm fairly new to php so there could be something simple I'm missing out.
Here is my code:
<?php
define('DB_NAME', '#######');
define('DB_USER', '#######');
define('DB_PASSWORD', '#######');
define('DB_HOST', 'localhost');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
$recovery = $_POST['recovery'];
$sql = "SELECT forgotpass FROM members WHERE username = '$recovery'";
$result=mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "Please wait... ";
$mailto = $recovery;
$mailSub = "Here's your password!";
$mailMsg = $row['forgotpass'];
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer();
$mail ->IsSmtp();
$mail ->SMTPDebug = 0;
$mail ->SMTPAuth = true;
$mail ->SMTPSecure = 'ssl';
$mail ->Host = "bemoresocial.co.uk";
$mail ->Port = 465; // or 587
$mail ->IsHTML(true);
$mail ->Username = "info#bemoresocial.co.uk";
$mail ->Password = "#########";
$mail ->SetFrom("info#bemoresocial.co.uk");
$mail ->Subject = $mailSub;
$mail ->Body = $mailMsg;
$mail ->AddAddress($mailto);
if(!$mail->Send())
{
echo "Something went wrong :(";
}
else
{
header('Location: ./success.php');
}
}
mysqli_close($conn);
SMTP can be slow, often deliberately so; it's really not well suited to sending email to remote servers during page submission processing, as PHP is typically used for.
The best way to fix this is to install a local mail server such as Postfix. Submitting messages to that (using SMTP to localhost) will be very fast, and then the mail server can deal with the slower onward delivery. This is effectively a queuing system, but is much easier than using something like beanstalkd, redis, or rabbitmq to build your own queue.
In your code, the require inside the while loop will cause a fatal error if it goes round more than once, because you will be requiring the same class file repeatedly. To send to multiple recipients efficiently, reuse the PHPMailer instance - you don't need to start from scratch every time around the loop - if you can use keepalive, this will also be much faster - see the mailing list example provided with PHPMailer for how to do that.
Though it's not part of the problem you're seeing, I can see you've based your code on an obsolete example, and you're using an old version of PHPMailer - upgrade to 6.0.
I ran into the same problem with VERY SLOW running PHP Mailer, like 3 minutes to send 15 emails using the Website Host SMTP server.
What I did to make it finish within seconds is to switch to gmail smtp. When you do this you'll need to go to Google and generate an app password Sign In Using App Password. So in your code use your normal email address with the generated password (note your normal password still works for your normal email access) and use tls security.
When I moved the program from testing to production the email failed. I found I had to go to google and just sign in and everything worked again.
Also note if you turn on SMTPDebug = 2; it will show you each step and the time it finished.
include ('class.PHPMailer.php');
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // 0=no output, 1=Commands, 2=Data & Commands, 3=2+connection status 4=Low-Level data output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mickeymouse#gmail.com'; // SMTP username
$mail->Password = 'aaaabbbbccccdddd'; // SMTP password (used google Generated app password)
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
// Recipients
$i = 0; $address="";
foreach($recipients as $i => $address)
{
$mail->addAddress($address);
}
$mail->addReplyTo('mickeymouse#gmail.com', 'Mickey');
$mail->isHTML(true);
$mail->setFrom('mickeymouse#gmail.com', 'Mickey');// Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $body;
$mail->send();
$message = 'Message has been sent';
}
catch (Exception $e) {
$message = 'Message could not be sent.'."<br>".
'Mailer Error: ' . $mail->ErrorInfo;
}

Godaddy phpmailer smpt configuration

We have a site on godaddy server. We have a contact form. When user filled form, first we should send mail to our info#oursite, after we should send mail to user's mail from our info#oursite. My tried code below:
$name = $_POST['name'];
$email = $_POST['email'];
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->port = 25;
$mail->Host = 'localhost';
$mail->Username = 'username#example.com';
$mail->Password = 'password';
$mail->addAddress($email, $name);
$mail->subject = 'Subject';
$mail->MsgHTML('mail içeriği');
if ($mail->Send()){
this outputs below:
it seems mail delivered, but it never delivered the message.
I tried many things;
$mail->SMTPAuth = true;
port 25,80,3535,465(with ssl),
tls, ssl authentication,
what should I do? what should I try more, any ideas?
First of all, you're using a very old version of PHPMailer; get the latest.
I don't know where you got your code, but you've got the case of some vital properties wrong - I suggest you base your code on the examples provided with PHPMailer. In particular, subject should be Subject and port should be Port. When sending to localhost you don't need a username or password, so you don't need to set them. Similarly, Port defaults to 25, so you don't need to set it.
You're not specifying a From address, and it looks like whatever address you're passing to addAddress is invalid, so you're sending a message from nobody to nobody - and not surprisingly it's not going anywhere!
It looks like your message body is in Turkish (?), which will not work in the default ISO-8859-1 character set, so I suggest you switch to UTF-8 by setting $mail->CharSet = 'UTF-8';.
Check your return values when calling addAddress to make sure the submitted value is valid before trying to send to it.
With these things fixed:
$name = $_POST['name'];
$email = $_POST['email'];
$mail = new PHPMailer;
if (!$mail->addAddress($email, $name)) {
die('Invalid email address');
}
$mail->isSMTP();
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 2;
$mail->Host = 'localhost';
$mail->Subject = 'Subject';
$mail->msgHTML('mail içeriği');
$mail->setFrom('me#example.com', 'My Name');
if ($mail->send()) {
echo 'Sent';
} else {
echo 'Error: '.$mail->Errorinfo;
}

PHPmailer - 500 internal server error

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.

PHP Mailer - Internal Server Error

I have been trying to make the contact form on my website to work and I've spent weeks trying to figure it out and I couldn't.
Here's the problem - I purchased a web template and it came with the PHPMailer. I'm now done plugging my content into the template, but the contact form has been a pain. I've followed the instructions the best I know on the PHP file, but it's giving me an "Internal Server Error" when I am testing the contact form.
Here's the code that came with my purchase:
$name = trim($_POST['name']);
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$site_owners_email = 'name#mydomain.com'; // Replace this with your own email address
$site_owners_name = 'My Name'; // Replace with your name
try {
require_once('/Beta-BRC/php/PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "[WEB Form] ".$subject;
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Mailer = "smtp";
$mail->Host = "smtp.gmail.com"; // Replace with your SMTP server address
$mail->Port = 465;
$mail->SMTPSecure = "SSL";
$mail->SMTPAuth = true; // Turn on SMTP authentication
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
//echo "true";
if($mail->Send()) {
echo "true";
} else {
echo "Error sending: " . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo $e;
}
Quick note - I've alrealy tried using a GMAIL account on this part but it still does not work.
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
There's no need to log into Gmail with phpmailer. Below is an example of my phpmailer function using the default settings.
public function sendEmail($toaddress,$toname,$subject,$message){
if($template = file_get_contents('/home/username/domains/mydomain.com/public_html/html/email-template.html')){
$template = str_replace("[SUBJECT]",$subject,$template);
$template = str_replace("[CONTENT]",nl2br($message),$template);
$mailer = new PHPMailer;
$mailer->XMailer = "Organization Name 4.0.0";
if($this->is_logged_in()){
$mailer->AddCustomHeader("X-Originating-User-ID",$this->acct['id']);
}
$mailer->AddCustomHeader("X-Originating-IP",$_SERVER['REMOTE_ADDR']);
$mailer->setFrom("outbound#mydomain.com","From Name");
$mailer->AddAddress($toaddress,$toname);
$mailer->Subject = $subject;
$mailer->MsgHTML($template);
$mailer->AltBody = $message;
return $mailer->Send();
}else{
return false;
}
}
The email address listed doesn't actually exist. The email is just being sent from my server and phpmailer just says it's from that email address.
Try modifying my function to suit your needs and let me know how that works.
Note: You'll need to make sure your mail server is turned on for this to work
Although you don't have to use my function at all. Try debugging your code by checking some error logs on your server. Typically in the apache error logs (if you're running apache, however). Checking error logs is a huge part of troubleshooting your code and often can help you become more proactive.
I hope this helps even the slightest!
The specific cause of the Internal Server Error is the incorrect path you've supplied to the require_once statement that loads the PHPMailer class.
The path you've supplied is /Beta-BRC/php/PHPMailer/class.phpmailer.php, where the correct statement should be
require_once('/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
or perhaps more generally:
require_once($_SERVER['DOCUMENT_ROOT'].'/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
You've provided effectively a URL, but PHP requires the path in the server file system, which is not the same.
That should get you past this error. It's possible that there are others.

PHPMailer - Certain SMTP messages don't send

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...

Categories