How to add smtp host to send mails with this phpmail script - php

I want to send mails using this PHP MAILING script but through SMTP and not through sendmail because my host rejects all emails as spam and I don't check my spam folder as its heavy loaded with spam emails daily.
I just want to know where to put the code which will use my SMTP logins to send mails using this php script instead of using sendmail/
I tried adding some things like
$host = "smtp.gmail.com";
$port = "587";
$username = "testtest#gmail.com";
$password = "testtest";
But these didn't worked, actually it broke the whole code itself,
Edit: I also tried adding this, reading an answer from another answered question here, and it also broke the code itself but didn't work.
$smtp = Mail::factory('smtp', array(
'host' => 'ssl://smtp.gmail.com',
'port' => '465',
'auth' => true,
'username' => 'johndoe#gmail.com',
'password' => 'passwordxxx'
Original Code
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
//only shows if prevent default fails (js in index.html)
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
//only shows if prevent default fails (js in index.html)
$errorMSG .= "E-mail is required ";
} else {
$email = $_POST["email"];
}
// MESSAGE
if (empty($_POST["message"])) {
//only shows if prevent default fails (js in index.html)
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
// change this to fit !
$EmailTo = "demo#domain.com";
$Subject = "New Message from MENTOR";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Somethin went wrong...";
} else {
echo "An error has ocurred!";
//echo $errorMSG; Enable if you want full details of php error
}
}
?>

Related

How can i send mail to multiple addresses but grouped by 20-30 to avoid spamming in php?

I want to bulk mails avoiding spam in php but I still do know how.
I have this function that returns the email addresses
public function getEmailAddress(){
$sql = "SELECT DISTINCT email,login FROM account.account";
$stmt=$this->o_db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
This function for send email:
public function sendVoucherCode($array2,$voucher){
$list = "";
foreach($array2 as $recipient){
if($recipient['email'] != NULL){
$list .= $recipient['email'].',';
}
}
$email_array = explode(",",$list);
foreach($email_array as $email)
{
$mail_own='Staff#blabla.ro';
$subject = 'Voucher cadou ';
$msg = '<html><body>';
$msg .= 'Ai primit un cod promotional care valoareaza <font color="darkorange">'.$value.'</font> monede. ' ."<br>";
$msg .= 'Adaugă codul: <b>'.$voucher.'</b> în meniul validare voucher pentru a primii monedele!'."<br>";
$msg .= 'Ține mine ofertă valabilă de la <b>'.$current_date.'</b> până la <b>'.$day_exp."</b><br>";
$msg .= "<br>"."<br>";
$msg .= 'Acest email este generat automat. Vă rugăm să nu răspundeți!'."<br>";
$msg .= "WebMaster -> Alex";
$msg .= '</body></html>';
$headers = "From: $mail_own\r\n";
$headers .= 'Content-Type: text/html; charset=utf-8';
$success = mail($email,$subject,$msg,$headers);
}
return true;
}
And so i call them:
$array2 = $this->getUserFunctions()->getEmailAddress();
$this->getUserFunctions()->sendVoucherCode($array2,$voucher);
How is possible to send emails grouped by 20-30 but in the end send to all? Or is there another way?
EDIT : i was blocked on ip when i sent to 100 addresses
Chunk your array of addresses. Take a look at array_chunk. The mail function allows multiple addresses in the $to argument.
So:
$addresses = array_chunk($list, 20);
foreach( $addresses as $group ){
...
mail(implode(',', $group), $subject, ...
You could create a table and store a sent emails history (a column containing the user id and another one containing the time email was sent). Then inside your PHP script do a "for loop" with 20-30 iterations to send emails to users not found in your new table (email history). You should then use a cron job to run your script at certain intervals (30mins or 1h).
In below code we are chunking the array in 20-20 value and then creating them as a one string with "," in this way every loop will send email to 20 emails.
Note:
Please change variable name accordingly.
public function sendVoucherCode($array2,$voucher){
$list = "";
foreach($array2 as $recipient){
if($recipient['email'] != NULL){
$list .= $recipient['email'].',';
}
}
$email_array = explode(",",$list);
$GroupingEmail = array_chunk($email_array,20);//Add this line
foreach($GroupingEmail as $email)
{
$sendEmailTo = impload(',',$email);//Add this line
$mail_own='Staff#blabla.ro';
$subject = 'Voucher cadou ';
$msg = '<html><body>';
$msg .= 'Ai primit un cod promotional care valoareaza <font color="darkorange">'.$value.'</font> monede. ' ."<br>";
$msg .= 'Adaugă codul: <b>'.$voucher.'</b> în meniul validare voucher pentru a primii monedele!'."<br>";
$msg .= 'Ține mine ofertă valabilă de la <b>'.$current_date.'</b> până la <b>'.$day_exp."</b><br>";
$msg .= "<br>"."<br>";
$msg .= 'Acest email este generat automat. Vă rugăm să nu răspundeți!'."<br>";
$msg .= "WebMaster -> Alex";
$msg .= '</body></html>';
$headers = "From: $mail_own\r\n";
$headers .= 'Content-Type: text/html; charset=utf-8';
$success = mail($sendEmailTo,$subject,$msg,$headers);//change this line
}
return true;
}
I did it with the PEAR:MAIL.
Several hundred emails are perfectly sent, but free access to smtp (without authorization) is needed:
function send_email($to, $from, $subject, $body) {
require_once "Mail.php";
require_once "Mail/mime.php";
$host = "your.smtp.server.com";
$headers['From'] = $from;
$headers["Reply-To"] = $from;
$headers["Return-path"] = $from;
$headers['To'] = $to;
$headers['MIME-Version'] = '1.0';
$headers['X-Mailer'] = 'MUA name';
$headers['Subject'] = $subject;
$mime_params = array(
'text_encoding' => '7bit',
'text_charset' => 'UTF-8',
'html_charset' => 'UTF-8',
'head_charset' => 'UTF-8'
);
$mime = new Mail_mime();
$mime->setHTMLBody($body);
$body = $mime->get($mime_params);
$headers = $mime->headers($headers);
$smtp = Mail::factory('smtp', array ('host' => $host));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
return false;
} else {
return true;
}
};
Forming a http-body email and get status as json.
If you want to send all the letters at once by the package you need to call this code in a circle, but remember that most smtp servers have a limit on the simultaneous number of recipients and the number of letters sent per unit of time.
// form mail header
$to = $recipient_address;
$from = "address#company.com";
$subject = "My subject";
// form mail body
$message = "<html><head><title>MyTitle</title></head><body>";
$message .= "<p>Text1</p>";
$message .= "<p>Text2</p>";
$message .= "</body></html>\r\n";
// send mail
if ( send_email($to, $from, $subject, $message) ) {
echo '{ "success": true, "msg": "OK" }';
} else {
echo '{ "success": false, "msg": "We have a problem" }';
};
May you can try BCC model, then you can send to many people once time.
When send mail, we can set to (receiver), cc (everyone can know cc users), bcc (protected), and them both allow more than one address there, like mail-1; mail-2...

PHP Mail Contact Form Not Working [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I'm a bit of an amateur when it comes to PHP and so need some help please. I have made a contact form on my website which can be seen here:
http://babylace.co.uk/thegardenmedic.co.uk/contact.html
I am using a contact.php file to handle the form submission. When I fill in the form it submits and says successful (feel free to try) but I am not receiving the email in my inbox. I have changed the email in this question to example to keep my email private. My code for contact.php is as follows:
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="alert alert-error">You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="alert alert-error">You must enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="alert alert-error">You must enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="alert alert-error">You must enter your phone number.</div>';
exit();
} else if(trim($address) == '') {
echo '<div class="alert alert-error">You must enter your post code.</div>';
exit();
} else if(trim($comments) == '') {
echo '<div class="alert alert-error">You must include a message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "example#example.com";
//$address = "example#example.com"";
$address = "example#example.com"";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'Contact Form';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name, their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email $email or via Phone $phone, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<div class='alert alert-success'>";
echo "<h3>Message Sent Successfully.</h3><br>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
} else {
echo 'ERROR!';
}
Your script seems fine so far. Though, it might not be your PHP code which is wrong. Maybe you need to setup your SMTP Auth, see here:
Sending email with PHP from an SMTP server

PHP Pear email message format wrong

I know the title is weird I cant for the life of me phrase it well lol.
I have done searches with multiple ways of phrasing the question and nothing shows up for this.
I have the email scripting working on the website im building and its fantastic! but when i edited the mail code to add extra message lines its made the sequence go wrong.
here is the code im using for the email message area:
<?php
require_once "Mail.php";
// load the variables form address bar
$name = $_REQUEST["name"];
$subject = 'Customer Feedback';
$message = $_REQUEST["message"];
$from = $_REQUEST["from"];
$compname = $_REQUEST["companyName"];
$ph = $_REQUEST["phone"];
$acp = $_REQUEST['allowCommentPublish'];
$marketing = $_REQUEST['incmarketing'];
$verif_box = $_REQUEST["verif_box"];
// Checking the check boxes and marking as appropriate
if(isset($_POST['allowCommentPublish']))
{
$acp = 'Yes';
}
else
{
$acp = 'No';
}
if(isset($_POST['incmarketing']))
{
$marketing = 'Yes';
}
else
{
$marketing = 'No';
}
// Optional data checker
if($compname == '')
{
$compname = 'N/A';
}
if($ph == '')
{
$ph = 'N/A';
}
// remove the backslashes that normally appears when entering " or '
$name = stripslashes($name);
$message = stripslashes($message);
$subject = stripslashes($subject);
$acp = stripcslashes($acp);
$marketing = stripcslashes($marketing);
$from = stripslashes($from);
// check to see if verificaton code was correct
if(md5($verif_box).'a4xn' == $_COOKIE['tntcon'])
{
// if verification code was correct send the message and show this page
$ToEmail = "email#email.com";
$message = "Name: ".$name."\n".$message;
$message = "From: ".$from."\n".$message;
$message = "Comments: ".$message."\n".$message;
$message = "Allow feedback to be Published: ".$acp."\n".$message;
$message = "[ OPTIONAL DATA ]"."\n".$message;
$message = "Company Name: ".$compname."\n".$message;
$message = "Phone Number: ".$ph."\n".$message;
$message = "Allow extra Marketing? ".$marketing."\n".$message;
$headers = array ('From' => $from,
'To' => $ToEmail,
'Subject' => 'Feedback: '.$subject);
$smtp = Mail::factory('smtp', array ('host' => 'smtp.vic.exemail.com.au', 'auth' => false));
$mail = $smtp->send($ToEmail, $headers, $message);
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
header("Location: /feedback_sent.php");
exit;
}
else
{
// if verification code was incorrect then return to contact page and show error
header("Location:".$_SERVER['HTTP_REFERER']."?subject=$subject&from=$from&message=$message&wrong_code=true");
exit;
}
?>
In my mind this should spit out the message body as this:
Name: name here
From: Email address
Comments: Message here
Allow feedback to be published: response
[ OPTIONAL DATA ]
Company Name: Company
Phone Number: Phone
Allow extra Marketing:
This should be how its seen in the email right?
What im actually getting is this:
Allow feedback to be Published: response
[ OPTIONAL DATA ]
Company Name: company
Phone Number: phone
Allow extra Marketing? Response
From: Email address
Name: name here
Comments: Message here
Is this normal? or have i inadvertently snuffed it somewhere along the lines and its messing with my head as payment?
Thanks for any help on this.
EDIT: Updated code.
<?php
// -----------------------------------------
// The Web Help .com
// -----------------------------------------
// remember to replace your#email.com with your own email address lower in this code.
require_once "Mail.php";
// load the variables form address bar
$name = $_REQUEST["name"];
$subject = 'Customer Feedback';
$comment = $_REQUEST["message"];
$from = $_REQUEST["from"];
$compname = $_REQUEST["companyName"];
$ph = $_REQUEST["phone"];
$acp = $_REQUEST['allowCommentPublish'];
$marketing = $_REQUEST['incmarketing'];
$verif_box = $_REQUEST["verif_box"];
// Checking the check boxes and marking as appropriate
if(isset($_POST['allowCommentPublish']))
{
$acp = 'Yes';
}
else
{
$acp = 'No';
}
if(isset($_POST['incmarketing']))
{
$marketing = 'Yes';
}
else
{
$marketing = 'No';
}
// Optional data checker
if($compname == '')
{
$compname = 'N/A';
}
if($ph == '')
{
$ph = 'N/A';
}
// remove the backslashes that normally appears when entering " or '
$name = stripslashes($name);
$comment = stripslashes($comment);
$subject = stripslashes($subject);
$acp = stripcslashes($acp);
$marketing = stripcslashes($marketing);
$from = stripslashes($from);
// check to see if verificaton code was correct
if(md5($verif_box).'a4xn' == $_COOKIE['tntcon'])
{
// if verification code was correct send the message and show this page
$ToEmail = "jim#digital2go.com.au";
$message = "Name: ".$name."\n".$message;
$message .= "From: ".$from."\n".$message;
$message .= "Comments: ".$comment."\n".$message;
$message .= "Allow feedback to be Published: ".$acp."\n".$message;
$message .= "[ OPTIONAL DATA ]"."\n".$message;
$message .= "Company Name: ".$compname."\n".$message;
$message .= "Phone Number: ".$ph."\n".$message;
$message .= "Allow extra Marketing? ".$marketing."\n".$message;
$headers = array ('From' => $from,
'To' => $ToEmail,
'Subject' => 'Feedback: '.$subject);
$smtp = Mail::factory('smtp', array ('host' => 'smtp.vic.exemail.com.au', 'auth' => false));
$mail = $smtp->send($ToEmail, $headers, $message);
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
header("Location: /feedback_sent.php");
exit;
}
else
{
// if verification code was incorrect then return to contact page and show error
header("Location:".$_SERVER['HTTP_REFERER']."?subject=$subject&from=$from&message=$message&wrong_code=true");
exit;
}
?>
Make your message "continue" in the order you wish by doing this:
$message = "Name: ".$name."\n".$message;
$message .= "From: ".$from."\n".$message;
$message .= "Comments: ".$message."\n".$message;
$message .= "Allow feedback to be Published: ".$acp."\n".$message;
$message .= "[ OPTIONAL DATA ]"."\n".$message;
$message .= "Company Name: ".$compname."\n".$message;
$message .= "Phone Number: ".$ph."\n".$message;
$message .= "Allow extra Marketing? ".$marketing."\n".$message;

PHP Sending Duplicate Emails

After some more troubleshooting I believe I found the problem. We use QR Tags for our product and when a QR code is scanned it takes the user to the URL that runs this script. If I manually type in the URL or if I use our custom built QR scanner app then the user will receive one email. However if I user any other QR scanning app then it will send multiple emails. How can I make it so that this script will run only once each time the URL is loaded even if its from a third party app?
<?php
$queryString = $_SERVER['QUERY_STRING'];
$count=-6;
$id=substr($queryString,$count,6);
//db connection
$db = new mysqli('localhost', '*****', '*****', '*****');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "SELECT * FROM `****` where id = '$id'";
$result = $db->query($query);
$row = $result->fetch_assoc();
$email = $row['email'];
$ownername = $row['ownername'];
$petname = $row['petname'];
//check to see if tag has been registered
if ($email != "") {
//send email
$datetime = date("D M j G:i:s T Y");
$subject = "Alert";
$mailheader.= "From: " . "Tag Team <support#tag.com>\n";
$mailheader.= "X-Sender: " . "support#tag.com\n";
$mailheader.= "Return-Path: " . "support#tag.com\n";
$mailheader .= "Bcc: support#tag.com";
$body .= "Dear " . $ownername . ", \n\n";
$body .= "" . $petname . "'s Tag has just been scanned.\n\n";
$body .= "Click here to Login :\n";
$body .= "http://www.tag.com\n";
$body .= "********************\n\n";
$body .= "Regards,";
$body .= " \n\n";
$body .= "Tag Team";
$body .= " \n\n";
$body .= "Keeping Pets Safe and Found";
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
//end email alert
}
header("Location: http://www.smartphonepettag.com/id/profile.php?id=$id");
mysql_close($db);
?>
In the code snippet I cannot see any reason why your script should be executed more than once but relating to your post yesterday it seems as if something on your mail server is going terribly wrong.
But anyway if it's not an mail server fault the solution would be something like this:
// add this at the very first line
session_start();
// add this in the code
if($_SESSION['send'] != true){
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
$_SESSION['send'] = true;
}
This will make sure that the "mail()" function will never be executed twice for the same user.
You can learn more about Session Variables at the PHP manual.
You could create a flag in your database indicating if the email has been sent. Check the flag before sending the email, set it after you send the email.

PHP Form - PHP Mailer cannot send to #Gmail.com

We have a PHP form on our website that has worked for years. When users fill the form out in sends us the details, and sends them an email and then re-directs the user to a "thank-you" page. However, if a user puts their email address as #gmail.com the form fails to send, it doesnt show the thank-you page.
This is really bizarre. We are using PHPMailer and validate if the form has been sent using:
if($mail->Send()) {
$mailsent = true;
If a user enters #hotmail.com or at #yahoo.com everything is fine. But enter #gmail.com and $mailsent is always false.
In this situation where does the problem lye? It seems to me that our web hosts SMTP connection to Gmail is failing. Would this seem right?
Here is the code:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$name = '';
$email = '';
$mailsent = false;
$referer = '';
if(isset($_POST['name'])){
include('phpmailer/class.phpmailer.php');
$name = $_POST['name'];
$email = $_POST['email'];
$subject = 'Quote request from ' . $name;
$body = 'A quote request has been received from a user with following details:' . "\n\n" .
"Name: $name \n" .
"Email: $email \n" .
"----------------------------------------------------\n\n" .
"Place: UK".
$body .= "\n----------------------------------------------------\n\n";
$body .= "Refering: ".$referer." \n";
$mail = new PHPMailer();
$mail->Subject = $subject;
$mail->From = $email;
$mail->FromName = $name;
$mail->Body = $body;
$mail->AddAddress("dean#example.com", "Example");
if($mail->Send()) {
$mailsent = true;
} else {
$error[] = 'There was some error. Please try later.';
}
}
?>

Categories