A beginner here.
I have already checked the forum to find out answers but I was not successful, other questions were specifically on some parts of PHPMailer but mine is more general. So I hope no one will mark my question as duplicate as I am in learning curve.
I am working on a PHP project. How it works is that the user goes to the page and writes some comments or issues in a form (like a text editor) and clicks on the send button. I should be able to receive his message to my email. I have set my Gmail account here for testing purposes but later it will be my real email with my own domain.
Here is the error that I am receiving when I run on local host:
Fatal error: Uncaught exception 'phpmailerException' with message 'Could not execute: /usr/sbin/sendmail' in C:\xampp\htdocs\pp\classes\class.phpmailer.php:1100 Stack trace: #0 C:\xampp\htdocs\pp\classes\class.phpmailer.php(1026): PHPMailer->sendmailSend('Date: Thu, 9 Oc...', '--b1_9ea0b33e3f...') #1 C:\xampp\htdocs\pp\classes\class.phpmailer.php(935): PHPMailer->postSend() #2
Here is the code I am using:
<?php
require_once("../../classes/class.phpmailer.php");
if($_POST['mode']=='send'){
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSendmail(); // telling the class to use SendMail transport
//I assume this part is to make it run on linux base on Google search
$body = "New Bug Report from ".$_SESSION['name']."\n".$_POST['bug'];
$mail->AddReplyTo('mj#gmail.com', 'MJ Team');
$mail->AddAddress(''.$_SESSION['email'].'', ''.$_SESSION['name'].'');
$mail->SetFrom(mj#gmail.com', 'MJ Team');
$mail->AddReplyTo('mj#gmail.com', 'MJ Team');
$mail->Subject = 'New bug report for the portal';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
$mail->Send();
//And I assume this part of the code makes it run on windows based on Google search
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.postmarkapp.com";
$mail->Port = 26;
$mail->Username = "MJ";
$mail->Password = "MJ";
$mail->SetFrom('mj#gmail.com', 'mj');
$mail->Subject = "An email for test";
$mail->AddAddress($address, $name);
if($mail){
$message = 'Thanks. Bug report successfully sent. We will get in touch if we have any more questions.';
}
else {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>
Just as extra information I was not able to find any user and pass for SMTP so I just filled with with my name which obviously shouldn't be right.
Since I am beginner I appreciate any comments and suggestion code that might help me run my code.
Thank you!
Try this :
<?php
session_start();
if(isset($_POST['mode']) && $_POST['mode']=='send' &&
isset($_SESSION['email'], $_SESSION['name'])){
require_once("PHPMailerAutoload.php");
$mail = new PHPMailer(true);
//Send mail using gmail
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "mj#gmail.com"; // GMAIL username
$mail->Password = "mypassword"; // GMAIL password
//Typical mail data
$mail->AddAddress($_SESSION['email'], $_SESSION['name']);
$mail->SetFrom('mj#gmail.com', 'mj');
$mail->Subject = "This is a test message";
$mail->Body = "An email for test";
try{
$mail->Send();
echo "Thanks. Bug report successfully sent.
We will get in touch if we have any more questions!";
} catch(Exception $e){
//Something went bad
echo "Mailer Error: - " . $mail->ErrorInfo;
}
}else{
echo 'missing required values!';
}
If all you want to do is send an email why not use the PHP Mail command (http://php.net/manual/en/function.mail.php)
replace your code with this:
$to = 'mj#gmail.com';
$subject = 'the subject';
$message = 'New bug report for the portal';
$headers = 'From: mj#gmail.com' . "\r\n" .
'Reply-To: mj#gmail.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
Related
i'm trying to send a mail using stmp configuration but it always displays a puny encode invalid error . I'm guessing it's my validation method that has a bug when the prce8 is selected ( i'm using php5 so it selects as best choice pcre8). I have already checked on that answer but still does not work !
<?php
require_once('class.mail.php');
$to=isset($_POST['verify'])?$_POST['verify']:false;
$subject="TSHED Email verification";
$message='<html><p> my message </p></html>';
$mail = new PHPMailer();
$mail->isSMTP(); // telling the class to use SMTP
// SMTP Configuration
$mail->SMTPsecure='ssl';
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "smtp.gmail.com "; // SMTP server
$mail->Username = "myEmail";
$mail->Password = "mypassword";
$mail->Port = 465; // optional if you don't want to use the default
$mail->From = "<FromanEmail>";
$mail->FromName = "Name";
$mail->Subject = $subject;
//$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->isHTML($message);
$mail->Body=$message;
$mail->msgHTML($message);
// Add as many as you want
$mail->AddAddress($to,'USER');
if(!$mail->Send())
{ //echo"endterer";
$response = "Message error!".$mail->ErrorInfo;
echo $response;
echo $to;
}
else {
$response = "Message sent!";
echo $response;
}
?>
Any Help Please ?
my pcre8:
case 'pcre8':
return (boolean)preg_match(
'/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}#)' .
'((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
'(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
'([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
'(?2)")(?>(?1)\.(?1)(?4))*(?1)#(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
'(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
'|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
'|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
'|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
$address
);
exemple of valid Email: ouedson0128#yahoo.fr
Error :Invalid address: (punyEncode)
Seems it is a bug in phpMailer. Try another version
Instead of using php's mail() function, I've been trying to set up PHPMailer with no success. I put in "echo here" for debugging purposes, and that is all it shows. I do not get any emails, or the sent or error messages. I'm stumped, and after researching it on here may switch to swift mailer. I'd really like to know what I screwed up though.
In my code, address is set to my email, and the username and password are set to a dummy account I made.
<?php
include('class.phpmailer.php');
$mail = new PHPMailer();
$address = "test#gmail.com";
$body = "test email";
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = "username#gmail.com";
$mail->Password = "password";
$mail->SetFrom('name#yourdomain.com', 'Web App');
$mail->Subject = "A Transactional Email From Web App";
$mail->MsgHTML($body);
$mail->AddAddress($address, $name);
echo "Here";
if($mail->Send()) {
echo "Message sent!";
}
else {
echo "Mailer Error: " ; $mail->ErrorInfo;
}
?>
As you are using Gmail I think you must make sure the gmail account has the insecure application auth activated
i am using PHPmailer to send emails
here is code that i have used:
$mail = new PHPMailer();
$subject = "test";
$to = "test_patel#yahoo.com"
$mail->SetFrom("PDSociety#aol.com","Punjab Dental Society");
$mail->AddReplyTo("PDSociety#aol.com", "Punjab Dental Society");
$mail->Subject = $subject;
$mail->MsgHTML($str);
$mail->AddAddress($to, "Punjab Dental Society");
if(!$mail->Send())
{
$err = "Mailer Error: " . $mail->ErrorInfo;
//echo $err;
} else {
$msg = "Message sent!";
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
if i change email address from yahoo to gmail or hotmail, still email are not sent.
i checked by echoing error, but no errors.
can anyone explain what is the issue ?
After trying various ways, i found following code working with almost all email providers
$to['email'] = "recipients email address";
$to['name'] = "name";
$subject = "email subject";
$str = "<p>Hello, World</p>";
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = 'Specify main and backup server here';
$mail->Port = 465;
$mail->Username = 'xyz#domainname.com';
$mail->Password = 'email account password';
$mail->SMTPSecure = 'ssl';
$mail->From = 'From Email Address';
$mail->FromName = "Any Name";
$mail->AddReplyTo('xyz#domainname.com', 'any name');
$mail->AddAddress($to['email'],$to['name']);
$mail->Priority = 1;
$mail->AddCustomHeader("X-MSMail-Priority: High");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $str;
if(!$mail->Send()) {
$err = 'Message could not be sent.';
$err .= 'Mailer Error: ' . $mail->ErrorInfo;
}
$mail->ClearAddresses();
variable values needs to be changed accordingly.
Hope these helps people having issues with PHPmailer
PHPMailer is only involved in submitting the message to your own mail server, and you're not having any problem there. After that, your mail server takes on the responsibility of sending it on, so you will find the answer in your mail server's logs.
There is no simple way to ensure messages end up in the inbox and not spam - if there was, spammers would be using it and filtering would be useless. Make sure your DNS resolves backwards and forwards, that you have valid SPF records, that you sign your messages with DKIM (especially important for Yahoo) and most importantly, that you don't send messages that your recipients think are spam.
Try this :
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->AddAddress($to['email'],$to['name']);
$mail->FromName = '';
$mail->Subject = $subject;
$mail->MsgHTML($message);
$send = true;
return $mail->Send();
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
$e->getMessage(); //Boring error messages from anything else!
}
It will help you if any exception error.
Have you looked on the post here: Using PHPMailer Results in many blocked emails? The asker solved the issue by changing the email subject:
Well I solved the issue; the code above was not the problem and works
great.
In my subject, I used a phrase regarding "verify your account
information" and that got it blocked on a few ISP's.
So the lesson is, your subject matters. I was looking at my php code
and my body content before I realized this.
The content of the email and its subject can make ISPs ban it. You could try taking the content of one of your received emails from your inbox and see if that goes through.
I have a php code for sending confirmation email. But how to send this email to registered user using my mail server. Example using gmail to send confirmarion email.
<?php
if(isset($_SESSION['error'])) {
header("Location: index.php");
exit;
} else {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$com_code = md5(uniqid(rand()));
$sql2 = "INSERT INTO user (username, email, password, com_code) VALUES ('$username', '$email', '$password', '$com_code')"; $result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
if($result2) {
$to = $email;
$subject = "Confirmation from MyName to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn"; $message .= "http://www.yourname.com/confirm.php?passkey=$com_code";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail) {
echo "Your Confirmation link Has Been Sent To Your Email Address.";
} else {
echo "Cannot send Confirmation link to your e-mail address";
}
}
}
}
?>
If you have mail server then you follow the your mail server rules.
You can use PHPMailer and follow the rule of phpmailer function.
Fix : You have to find out whether you have installed a mail server in your server instance. This depends on server environment. You can find how to with simple web search.
Tip: If just get the response from the operation as normal your mail server is not connected. But if it's keep waiting for like 4 to 5 seconds means most of the time server is there issue is something in it.
Ubuntu - [How to install postfix][1]
Windows - [SMTP E-mail][2]
Further issues :
Once you can send the mail using php mail function but still you have give the accurate header information otherwise the mail will send to spam folder.
Wrong: $header = "TutsforWeb: Confirmation from TutsforWeb";
Correct:
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
If you want to do it gmail just refer this : Send email using the GMail SMTP server from a PHP page
You first fetch data from table where registered users are stored then you can send mail to registered users
If you have your mail servers credentials then you can use SMTP to send emails. You can also use PHPMailer which is very easy to use.
First thing is you need to install PHPMailer from above link after that use following code
`
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$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 = 'user#gmail.com'; // Your gmail username
$mail->Password = 'your_gmail_password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->From = 'from#example.com'; // from email address
$mail->FromName = 'User1'; // whatever is the name of sender
$mail->addAddress($_POST['email'], $_POST['username']); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message ;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?>`
Download PHPMailerAutoload
link here
<?php
// When we unzipped PHPMailer, it unzipped to
// public_html/PHPMailer_5.2.0
require("lib/PHPMailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// we are setting the HOST to localhost
$mail->Host = "mail.example.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
$mail->Username = "user#gmail.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$mail->From = "from#example.com";
// below we want to set the email address we will be sending our email to.
$mail->AddAddress("to#example.com", "To whom");
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "You have received feedback from your website!";
$message = "Text Message";
$mail->Body = $message;
$mail->AltBody = $message;
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
Edit: I forgot I'd created the SendMail(); function myself, which is why the explanation doesn't mention at first what it does.
I'm having some trouble with PHPMailer (https://github.com/PHPMailer/PHPMailer) when attempting to send two emails, one directly after the other.
The script is almost completely 'out of the box', with only a few modifications such as a foreach loop to allow for multiple addresses, and everything still works perfectly.
However, if I attempt to call more than one instance of SendMail(); I get the error message:
Fatal error: Cannot override final method Exception::__clone() in .... online 0
Previously I was using the in-built mail(); function, which allowed me to use it as many times as I liked in quick succession , but it doesn't appear to be that simple with PHPmailer:
$to = me#me.com;
$to2 = me2#me2.com';
$headers = 'php headers etc';
$subject = 'generic subject';
$message = 'generic message';
mail($to, $subject, $message, $headers);
mail($to2, $subject, $message, $headers);
The above would result in two identical emails being sent to different people, however I can't easily replicate this functionality with PHPmailer.
Is there a way of stacking these requests so that I can send successive emails without it failing? Forcing the script to wait until the first email has been sent would also be acceptable, although not preferential.
As I mentioned I know it works when only one instance is called, but I don't seem to be able to re-use the function.
I haven't included the source code, although it is all available on the link provided above.
Thanks in advance
Edit as requested
// First Email
$to = array(
'test#test.com',
'test2#test.com',);
$subject = "Subject";
$message = $message_start.$message_ONE.$message_end;
sendMail();
// Second Email
$to = array(
'test#test.com',
'test2#test.com',);
$subject = "Subject";
$message = $message_start.$message_TWO.$message_end;
sendMail();
The above is how I want this to work, as it would work with mail();. The first email will work fine, the second will not.
SendMail() code
This is from the PHPmailer website, and is what is defined as SendMail();. The only difference from the example is the loop for AddAddress, and the inclusion of $to as a global variable.
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "smtp1.example.com;smtp2.example.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "jswan"; // SMTP username
$mail->Password = "secret"; // SMTP password
$mail->From = "from#example.com";
$mail->FromName = "Mailer";
foreach($to as $to_add){
$mail->AddAddress($to_add); // name is optional
}
$mail->AddReplyTo("info#example.com", "Information");
$mail->WordWrap = 50; // 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
$mail->Subject = "Here is the subject";
$mail->Body = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
You haven't posted this code that lets me make this a complete conclusion, but from the Exception and the way you've defined an overriding class inside a function, you probably have class.phpmailer.php loading every time like this:
require('class.phpmailer.php');
or
include('class.phpmailer.php');
You should change that line to
require_once('class.phpmailer.php');
The reason you need to change it to require_once is so that PHP will not load the class file the second time when you try to create the new/second PHPMailer class. Otherwise, the line class PHPMailer throws the __clone() exception.
Added an example below:
<?php
/**
* This example shows how to send a message to a whole list of recipients efficiently.
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
require '../vendor/autoload.php';
//Passing `true` enables PHPMailer exceptions
$mail = new PHPMailer(true);
$body = file_get_contents('contents.html');
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 25;
$mail->Username = 'yourname#example.com';
$mail->Password = 'yourpassword';
$mail->setFrom('list#example.com', 'List manager');
$mail->addReplyTo('list#example.com', 'List manager');
$mail->Subject = 'PHPMailer Simple database mailing list test';
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
$mail->msgHTML($body);
//msgHTML also sets AltBody, but if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
//Connect to the database and select the recipients from your mailing list that have not yet been sent to
//You'll need to alter this to match your database
$mysql = mysqli_connect('localhost', 'username', 'password');
mysqli_select_db($mysql, 'mydb');
$result = mysqli_query($mysql, 'SELECT full_name, email, photo FROM mailinglist WHERE sent = FALSE');
foreach ($result as $row) {
try {
$mail->addAddress($row['email'], $row['full_name']);
} catch (Exception $e) {
echo 'Invalid address skipped: ' . htmlspecialchars($row['email']) . '<br>';
continue;
}
if (!empty($row['photo'])) {
//Assumes the image data is stored in the DB
$mail->addStringAttachment($row['photo'], 'YourPhoto.jpg');
}
try {
$mail->send();
echo 'Message sent to :' . htmlspecialchars($row['full_name']) . ' (' . htmlspecialchars($row['email']) . ')<br>';
//Mark it as sent in the DB
mysqli_query(
$mysql,
"UPDATE mailinglist SET sent = TRUE WHERE email = '" .
mysqli_real_escape_string($mysql, $row['email']) . "'"
);
} catch (Exception $e) {
echo 'Mailer Error (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
//Reset the connection to abort sending this message
//The loop will continue trying to send to the rest of the list
$mail->getSMTPInstance()->reset();
}
//Clear all addresses and attachments for the next iteration
$mail->clearAddresses();
$mail->clearAttachments();
}
In addition to #Amr most excellent code.
In order to use this in a cron fasion, two adds are useful.
$mail-> SMTPDebug = true;
$mail-> Debugoutput = function( $str, $level ) {_log($str);};
The function _log is up to you. Writing to a file, to a database or wherever. I personally have reduced this to
$mail-> Debugoutput = function( $str, $level ) {if( $level===3 ) {_log( $str ); } };
to only write the more juicier messages
the solution is to reset recipients data like this:
$Mailer->clearAddresses()
use your own variable as an instance of PHPMailer (instead of $Mailer)
$Mailer->clearAddresses()
This is the solution to avoid multiple msj to be send to the same recipient.