The same registration form information comes to my mail more than once.
My Mailbox is filled with exactly the same forms.
Can you help me solve this problem?
PHP CODE:
<?php
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer(); // create a new object
$mail = new PHPMailer(); // create a new object
$subject = "[XX] Registration Form";
$question = nl2br(stripcslashes($_POST['question']));
$question = trim($question);
$email_message = "<b>Name:</b> ".stripcslashes($_POST['fname'])."<br><br>";
$email_message .= "<b>Surname:</b> ".stripcslashes($_POST['lname'])."<br><br>";
$email_message .= "<b>Birthday:</b> ".stripcslashes($_POST['dob'])."<br><br>";
$email_message .= "<b>Phone:</b> ".stripcslashes($_POST['phone'])."<br><br>";
$email_message .= "<b>Email:</b> ".stripcslashes($_POST['email'])."<br><br>";
$email_message .= "<b>Address:</b> ".stripcslashes($_POST['adres'])."<br><br>";
$email_message .= "<b>Location:</b> ".stripcslashes($_POST['Location'])."<br><br>";
$body = $email_message;
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->Host = "smtp.yandex.com.tr";
$mail->SMTPSecure = 'ssl';
$mail->Port = 465; // or 465
$mail->IsHTML(true);
$mail->CharSet ="utf-8";
$mail->SetFrom("info#xx.com", "XX REGISTRATION FORM"); // Mail adresi
$mail->Username = "info#xx.com"; // Mail adresi
$mail->Password = "xxx"; // Parola
$mail->Subject = $subject;
$mail->body = $body;
$mail->MsgHTML($body);
$mail->AddAddress("info#xx.com");
$mail->addReplyTo(stripcslashes($_POST['emailer']), "");
if(!$mail->Send()){
echo "Mail Error".$mail->ErrorInfo;} else {
echo "Mesaj Gönderildi";
}
It's most likely that the script is simply being run more than once. This can be caused by browser plugins, or by not preventing processing of empty forms. Protect against sending empty messages during page load by wrapping it in a condition like this:
if (isset($_POST['emailer'])) {
//Rest of your script
The main thing to check first is whether a single run of your script is sending multiple messages, or whether the script is being run more than once (sending one message each time). Try writing something to a log file, or making it obvious in received messages by appending a random number to the end of the subject line. If you receive two messages with the same number in the subject, they are true duplicates; if the numbers are different subjects, your script is being run more than once:
$mail->Subject = 'Hi ' . rand();
Some other problems:
$mail->body = $body;
PHP is case-sensitive for properties, so that should be $mail->Body = $body;, but you're also calling $mail->MsgHTML($body);, which sets the Body property for you, so you don't need to set body yourself as well.
While you're working on a script, $mail->SMTPDebug = 1 isn't very useful as it doesn't show what the server is saying; set $mail->SMTPDebug = 2. Don't forget to set it to 0 in production!
I can also see that you're using a very old version of PHPMailer, and have based your code on an obsolete example, so update.
The problem was solved when I edited my codes like this.
The code executed when the form is submitted includes the following:
<script type="text/javascript">
function checkForm(form) // Submit button clicked
{
//
// check form input values
//
form.myButton.disabled = true;
form.myButton.value = "Please wait...";
return true;
}
</script>
While the HTML for the form itself looks something like:
<form method="POST" action="..." onsubmit="return checkForm(this);">
...
<input type="submit" name="myButton" value="Submit">
</form>
Related
Something is mighty odd. I created a basic test file with the code from PHPMailer.
# Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'includes/PHPMailer/PHPMailer.php';
require 'includes/PHPMailer/SMTP.php';
require 'includes/PHPMailer/Exception.php';
function sendCampaignEmail ($email, $firstname, $lastname)
{
$mail = new PHPMailer(true); // Create a new PHPMailer instance. Passing `true` enables exceptions.
try {
//Server settings
# $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output. SMTP::DEBUG_SERVER = client and server messages
# $mail->SMTPDebug = SMTP::DEBUG_CLIENT; // SMTP::DEBUG_CLIENT = client messages
$mail->SMTPDebug = SMTP::DEBUG_OFF; // SMTP::DEBUG_OFF = off (for production use)
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'myhostxxxx.co.uk'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'oobaclub#xxxxxxxxx.co.uk'; // SMTP username
$mail->Password = 'xxxxxmyEmailPasswordxxxxx'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 465; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('myfromemail.co.uk', 'My Name');
$mail->addAddress($email, $firstname . ' ' . $lastname); // Add a recipient
$mail->addReplyTo('myfromemail.co.uk', 'My Name');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'Dear ' . $firstname . ' ' . $lastname . '<br/><br/>This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo '<br/>Message has been sent to ' . $email . ' (' . $firstname . ' ' . $lastname . ')';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
$names= array();
$id=0;
$names[$id]['email'] = "atestemail#gmail.com";
$names[$id]['first_name'] = "Bob";
$names[$id]['last_name'] = "gMail"; $id++;
$names[$id]['email'] = "anothertest#testingmyemail.co.uk";
$names[$id]['first_name'] = "Sid";
$names[$id]['last_name'] = "Smith"; $id++;
$count=0;
while ($count < count($names))
{
sendCampaignEmail ($names[$count]['email'], $names[$count]['first_name'], $names[$count]['last_name']);
$count++;
}
THIS CODE ABOVE WORKS FINE.
So... Then, I took the function and put it into an Included file (where all my functions are: "globalfunctions.php").... And now it says "Fatal error: Uncaught Error: Class 'PHPMailer' not found"
So, now, at the top of my index.php, I have:
## PHP MAILER - # Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once 'includes/PHPMailer/PHPMailer.php';
require_once 'includes/PHPMailer/SMTP.php';
require_once 'includes/PHPMailer/Exception.php';
require_once 'includes/connect.php';
require_once 'includes/globalfunctions.php';
I am confused as everything else works. All my other functions work. I thought namespaces were global... But, I tried adding the "use" code into the function... but, as expected, that didn't work either....
I am stumped.
PHP use declarations are local aliases that apply only to the file they appear in. You have to add a use statement in every file that uses that class; you can't put all your declares in one file and then include it from somewhere else.
Now might be a good time to learn how to use composer as it takes care of a lot of this.
I am sending attachments (CSV) which I have been sending for years using mail() but decided to migrate to SMTP for better reliability.
Code 1 (CSV attachment)
$attachment = $this->CSVData; // "Date","Name","Dept" ... \n"2019-03-13","Dave" ...
$encoding = 'base64';
$contentType = 'text/csv';
$filename = $this->createFileName(); //Get FileDate and Name
$recipient = $delivery_email; // xxxxxxx#gmail.com
$subject = $this->emailHeader['subject'] . " CSV Data";
$message = 'Daily Data File';
$mail = new PHPMailer\PHPMailer\PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = SMTP_HOST; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = SMTP_USER; // SMTP username
$mail->Password = SMTP_PASS; // SMTP password
$mail->SMTPSecure = SMTP_AUTH; // Enable TLS encryption, `ssl` also accepted
$mail->Port = SMTP_PORT; // TCP port to connect to
//Recipients
$mail->setFrom($this->fromEmail, $this->fromEmailName); // Add a FROM
$addresses = explode(',', $recipient);
foreach ($addresses as $address) {
$mail->AddAddress(trim($address)); // Add a recipient(s)
}
if ( !empty($this->emailCC) ) $mail->addCC($this->emailCC); // Add a CC
//13-03-2019: Add the attachment to the email
$mail->AddStringAttachment($attachment, $filename, $encoding, $contentType);
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'This email is formatted in HTML';
$mail->send();
$this->fo->printStatus('Email successfully sent to: '. $recipient );
return true;
} catch (Exception $e) {
$this->fo->printStatus( basename(__FILE__) .' '. __LINE__ . ': Message could not be sent. Mailer Error: '. $mail->ErrorInfo );
return false;
}
The email gets delivered to me BUT ...
Problems:
When viewing in Gmail browser - I get message: "
Gmail virus scanners are temporarily unavailable – The attached files haven't been scanned for viruses. Download these files at your own risk."
When viewing in Gmail browser - I cant save/download the file? (clicking the download button does nothing)
When clicking attachment to view in browser, I now get error: "Whoops. There was a problem while previewing this document"
I try "Show Original" and it takes 30+ seconds for the email to load which just shows the base64 encoded data
I tried to open in inbox in Outlook and after 5 minutes of the emails not loading I gave up (thinking the emails are not encoded properly or something causing outlook to get stuck)
It looks like it is working (i.e. the file looks legit based on the gmail icon preview) but I cant do anything else with it and I don't know if it is a Gmail issue or File Issue.
Any advice?
Turns out that Gmail was having issues all yesterday afternoon with attachments. It was a Gmail issue - The timing is unbelievable
https://www.theguardian.com/technology/2019/mar/13/googles-gmail-and-drive-suffer-global-outages
A number of people had shown similar question, using phpmailer with g-mail. This problem is slightly different and may need a different answer.
The phpmailer code is fairly standard (below). I have a loop that goes through some data in the table and builds customised messages for recipients, sending a message for each row in the table. When the message is sent, it successfully completes about 75 out of some 100 recipients, and for the last 25, it reports the SMTP connect() failed error. This doesn't happen every time, and occasionally, the script goes through the loop without errors.
<?php
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPsecure = "ssl";
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "smtp.gmail.com"; // sets the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "xx"; // SMTP account username
$mail->Password = "xx"; // SMTP account password
$mail->SetFrom("xx#gmail.com");
$mail->isHTML(true);
$mail->CharSet = "utf-8";
$mail->Subject = $msgsubject;
$mail->AltBody = "Invitation";
do {
$membername = $row_musicians['name'];
$membernumber = $row_musicians['number'];
$emailaddress = $row_musicians['email'];
$rhdate = $row_musicians['rhdate'];
$mail->clearAttachments();
$mail->Body = 'Dear '.$membername.',
<p>'.$maintext.'</p>
';
// some more text using custom variables from database
// closing part of the message
$mail->Body .= '<p>'.nl2br($closing, false).'</p>
</body>
</html>';
$mail->AddAddress($emailaddress, $membername); // sending each message
sleep(1); // wait one second between sends, to avoid spam filters
echo '<br />
Recipient: '.$membername.' ('.$emailaddress.') -- ';
if(!$mail->Send()) {
echo "Mailer Error: <div style='color:#009999'>" . $mail->ErrorInfo." </div>";
} else {
echo "Message sent!";
}
$mail->ClearAddresses();
} while ($row_musicians = mysql_fetch_assoc($musicians));
mysql_free_result($musicians);
?>
I recommend basing your code on the mailing list example provided with PHPMailer.
You're doing most things right - initialising PHPMailer first and setting properties that are common to all messages, but one key thing is missing:
$mail->SMTPKeepAlive = true;
Without this it means that it closes and reopens a connection for every message, and you're mostly likely running into connection rate limits.
you're also using the combination of Port= 587 and SMTPSecure = 'ssl' which will generally not work; switch to Port = 465.
I'd also recommend against the do/while loop - it will fail if your database query fails to find anything because it's bottom-tested and thus will always run once, even if there is no data. Use a while or foreach loop instead.
The mailing list example does all of these things already.
Final thing - if this is all your code, it looks like you're running an old version of PHPMailer, so get the latest.
I got a Award Space Mail Hosting account.I created that account only for the free email sending feature.
Tried
PHP mailer
swiftmailer ect..
But no use.Can anyone give me a full working code of php and mail form,so that i can just test it in my server .I cound send emails when using this file :
http://www.html-form-guide.com/php-form/php-form-validation.html
But,i dont want that peace of code.I want a perfect code that can work on My server.
Sample code:(Has an html form submit form)
<?php
if(isset($_POST['submit'])) {
$myemail = “support#domain.dx.am”;
$subject = $_POST['subject'];
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$headers = “From:Contact Form <$myemail>\r\n”;
$headers .= “Reply-To: $name <$email>\r\n”;
echo “Your message has been sent successfully!”;
mail($myemail, $subject, $message, $headers);
} else {
echo “An error occurred during the submission of your message”;
}
?>
Or i tried doing the same with php mailer:
<?php
require 'filefolder/mailer/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'localhost'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'support#whatever.dx.am'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->From = 'support#whatever.dx.am';
$mail->FromName = 'Support';
$mail->AddAddress('anything#gmail.com'… // Name is optional
$mail->WordWrap = 50; // Set word wrap to 50 characters
$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.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
?>
I am doing something wrong. But cant figure out what. Can anyone help me out .
The 'from' header should be an existing email account inside your Email Manager of your Hosting Control Panel.
as their FAQ says:
Tip: Please note that the 'From' header should be an existing email account inside your Email Manager of your Hosting Control Panel.
FAQ
I use PHPMailer class to send letter and I use gmail account as smtp server.
problem is what sometimes it work well and visitors get letters, but sometimes no and show me error "Message body is empty" or like that.
I think if be problem in code, so don't sent any letter for websites visitors.
why happien like this? what can be problem?
Change these lines:
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Port = 465;
With:
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
$mail->Port = 587;
and hopefully all will be okay from now on.
my code is
function mail_send($type, $id, $mailadd, $maillname) {
global $lang;
global $site_adress;
global $pavadinimas;
global $tekstas;
global $ivadas;
global $full_date;
global $short_date;
require_once ('includes/phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$siteuser_name = SQL_ROW("users", "WHERE user_id='1'", "user_name");
$siteadminemail = SQL_ROW("users", "WHERE user_id='1'", "user_email");
$alttext = users_langs(altmailtext);
if ($type == "mailactiveletter") {
$subj = users_langs("mailactivesubject");
$linktur = "$site_adress/$lang/usermail_$type-$id.html#kat";
// var_dump($linktur,$type, $siteuser_name,$siteadminemail);
}
if ($type == "mailchangeadress") {
$subj = users_langs("prisijduomenupriminimas");
$linktur = "$site_adress/$lang/usermail_$type-$id.html#kat";
}
$body = file_get_contents("$linktur");
$body = eregi_replace("[\]", '', $body);
define('GUSER', 'uxxxx#gmail.com'); // Gmail username
define('GPWD', 'xxx'); // Gmail password
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // 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;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->CharSet = 'UTF-8';
//$mail->AddReplyTo("$siteadminemail", "$siteuser_name");
$mail->AddReplyTo("no-replay#xxx.co.uk", "$siteuser_name");
$mail->AddAddress("$mailadd", "$maillname");
// $mail->SetFrom("$siteadminemail", "$siteuser_name");
$mail->SetFrom("no-replay#xxx.co.uk", "$siteuser_name");
// $mail->AddReplyTo("$mailadd", "$maillname");
$mail->AddReplyTo("no-replay#xxx.co.uk", "$siteuser_name");
$mail->Subject = "$subj";
$mail->AltBody = "$alttext $linktur";
// optional, comment out and test
$mail->MsgHTML($body);
if (!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "";
}
}
Add a $mail->Sender property.
For exemple:
$mail->Sender is the same value of a $mail->From and I add the two lines.
$mail->From = "noreply#test.com";
$mail->Sender = "noreply#test.com";