I'm trying to send an email via SMTP using PHPMailer on my site, it works the second time I try (use submit), but the first time it says it cannot authenticate, login or password is invalid. I have searched a lot and can't find the answer, can someone help me please?
By the way I'm using JSON to get the PHP response in an alert. My host doesn't have "smtp." in front because support told me to do it this way.
This is the code:
else {
$phpmail = new PHPMailer();
$phpmail->IsSMTP(); // envia por SMTP
$phpmail->Host = "velvetwebdesign.com.br"; // SMTP servers
$phpmail->Port = "587"; // Port
$phpmail->SMTPAuth = true; // Caso o servidor SMTP precise de autenticação
$phpmail->SMTPDebug = 1;
$phpmail->Username = "email#velvetwebdesign.com.br"; // SMTP username
$phpmail->Password = "xxxxxxx"; // SMTP password
$phpmail->IsHTML(true);
$phpmail->From = 'email#velvetwebdesign.com.br';
$phpmail->FromName = $_POST['nome'];
$phpmail->AddAddress("velvetwebdesign#velvetwebdesign.com.br");
$phpmail->AddAddress($_POST['email']);
$phpmail->Subject = 'Contato Velvet Web Design';
$phpmail->Body .= "<b>Cliente:</b> ".$_POST['nome']."<br />";
$phpmail->Body .= "<b>E-mail:</b> ".$_POST['email']."<br />";
$phpmail->Body .= "<b>Telefone:</b> ".$_POST['telefone']."<br />";
$phpmail->Body .= "<b>Assunto:</b> ".$_POST['assunto']."<br /><br />";
$phpmail->Body .= "<b>Mensagem:</b><br />".nl2br($_POST['mensagem'])."<br /><br />";
$phpmail->Body .= "Recebemos a sua mensagem, responderemos em breve.<br />";
$phpmail->Body .= "http://www.velvetwebdesign.com.br/";
$send = $phpmail->Send();
if($send){
echo "A Mensagem foi enviada com sucesso. Enviaremos uma copia para o seu e-mail tambem.";
exit;
}else{
echo "Tente novamente por favor. Erro: " .$phpmail->ErrorInfo;
exit;
}
}
?>
Related
I got two contact forms on my website. On in the contact section, and one in the careers section. I want to receive both forms in different email adresses.
<?php
include_once('class.phpmailer.php');
$mail = new PHPMailer;
$mail->setFrom('adres1','test');
$mail->Subject = 'Contactverzoek via careerspagina.';
$html = "Er is een contactverzoek gedaan via de careerspagina.<br>";
$html .= "<br>";
$html .= "<b>Naam:</b> " . $_POST['name']."<br>";
if(isset($_POST['lastname'])) {
$html .= '<b>Achternaam: </b> ' . $_POST['lastname']."<br>";
}
$html .= "<b>E-mail:</b> " . $_POST['email']."<br>";
if(isset($_POST['telefoon'])) {
$html .= '<b>Telefoon: </b> ' . $_POST['telefoon']."<br>";
}
if(isset($_POST['onderwerp'])) { //FIX NOG!!!
$html .= '<b>Onderwerp: </b> ' . $_POST['onderwerp']."<br>";
}
if(isset($_POST['Werkervaring'])) {
$html .= '<b>Werkervaring: </b> ' . $_POST['Werkervaring']."<br>";
}
if(isset($_POST['Functie'])) {
$html .= '<b>Functie: </b> ' . $_POST['Functie']."<br>";
}
if(isset($_POST['Opleidingsniveaus'])) {
$html .= '<b>Opleidingsniveaus: </b> ' . $_POST['Opleidingsniveaus']."<br>";
}
if(isset($_POST['comment'])) {
$html .= '<b>Bericht: </b> ' . $_POST['comment']."<br>";
}
$html .= "<br>";
if (isset($_FILES['resume']) &&
$_FILES['resume']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['resume']['tmp_name'],
$_FILES['resume']['name']);
}
if (isset($_FILES['letter']) &&
$_FILES['letter']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['letter']['tmp_name'],
$_FILES['letter']['name']);
}
$mail->msgHTML($html);
$mail->addAddress('adres1', 'Info ');
$mail->addBCC('adres1', 'Test ');
if(!$mail->send())
{
echo "0";
}
else
{
echo "1";
}
This is my code, and everything seems to work.
So once again. I want to keep sending this contact form to email A. But There needs to be made and else statement which sends the other contact form to email B.
i'm very new to PHP. Excuse me if i'm not clear.
One simple solution is to send a form parameter indicating which email address should be used. Then you check the POST variable for that parameter in an if statement and set the correct email address to be used.
$to = "forma#example.com";
if($_POST['form'] === "formB") {
$to = "formb#example.com";
}
$mail->addAddress($to, 'Recipient name');
Add hidden inputs in your forms named "form" and set the value to either "formA" or "formB":
<input type="hidden" name="form" value="formA">
Do not set the receiving email address in the form and use that since it can easily be abused to send spam from your server.
I am able to send plain text but not HTML..
Please assist as why the mail is not being recieved..
THX in advance :)
Below is the code:
$mailBody ='<table width="100%" >
<tr>
<td>
<img src="MailerImages/img_logo.gif" alt="UrMint.com"/>
<h1 style="font:bold 20px tahoma; color:#808080;">Hi #USERNAME,</h1>
<p style="font:13px tahoma; color:#666666; line-height:25px;">
Your password for xyzacccount associated with mobile no password #MOBNO is : <strong style="color:#e65786;">#PASSWORD</strong>
<br />
If you didn\'t request a new password, let us know immediately.
<br />
This message was sent from xyz.com at your request.
</p>
<strong style="font:bold 13px tahoma; color:#666666; line-height:25px;">
Happy Learning ,
<br />
The <span style="color:#42b1d6;">Ur</span><span style="color:#e65786;">urMint</span> Team
</strong>
</table>
';
echo $mailBody;
SendEMail_fun('xyz#gmail.com', $mailBody,'sub','xyzsender','xyz#rediffmail.com');
function SendEMail_fun($strEmailTo,$strEmailBody,$strSubject,$SenderName = '',$SenderEmail='')
{
global $SwiftMessage;
$SenderName = $SenderName <> ''?$SenderName:"support#xyz.com";
$SenderEmail = $SenderEmail <> ''?$SenderEmail:"support#xyz.com";
$email_from_name = $SenderName." <".$SenderEmail.">";
$email_from_mail = $SenderEmail;
$email_to_bcc= "";
$email_to= $strEmailTo;
$email_subject= $strSubject;
$emailbody =$strEmailBody;
try
{
require_once ("lib/Swift.php");
$smtp = new Swift_Connection_SMTP("localhost", 25);
$swift = new Swift($smtp);
$message = new Swift_Message($email_subject, $emailbody, "text/html");
$message->setFrom($email_from_name);
$message->setReplyTo($email_from_mail);
$message->setBcc($email_to_bcc);
if ($swift->send($message, $email_to, $email_from_mail))
{
//echo "Message sent";
echo $SwiftMessage = 'Message Sent';
return true;
}
else
{
//echo "Message failed to send";
echo $SwiftMessage = 'Message failed to send';
return false;
}
$swift->disconnect();
return true;
}
catch (Swift_ConnectionException $e)
{
// echo "There was a problem communicating with SMTP: " . $e->getMessage();
echo $SwiftMessage = "There was a problem communicating with SMTP: " . $e->getMessage();
return false;
}
catch (Swift_Message_MimeException $e)
{
// echo "There was an unexpected problem building the email:" . $e->getMessage();
echo $SwiftMessage = "There was an unexpected problem building the email:" . $e->getMessage();
return false;
}
}
I'm not sure the exact reason yours is not sending. I've included the html email script I always use. Hope it helps.
<?php
$myFile = "email.html";
$fh = fopen($myFile, 'r');
$htmlemail = fread($fh, filesize($myFile));
fclose($fh);
$to = "YOUREMAIL#gmail.com" . ",";
//$to .= "#gmail.com" . ",";
$subject = "SUBJECT";
$message = $htmlemail;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= 'From: NAME <email#email.com>' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
I'm wondering if the mail order has any effect on if it will work or not:
You have
if ($swift->send($message, $email_to, $email_from_mail))
Mine:
mail($to, $subject, $message, $headers);
Worth a shot
I'd like to use this free form template but I want it to redirect me to a thank you page upon submission.
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "e-mail here";
$email_subject = "subject here";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>
How can I add a code where I will be redirected to a page of my choice?
header("Location: http://page_of_your_choice.com");
Just insert this where you have the
<!-- include your own success html here -->
First, Thanks for your attention.
Comes to prob.
I'm using this IPN Listener code:
// IPN LISTENER
// intercetta le variabili IPN inviate da PayPal
$req = 'cmd=_notify-validate';
// legge l'intero contenuto dell'array POST
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// intestazione, prepara le variabili PayPal per la validazione
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: www.sandbox.paypal.com\r\n"; // www.paypal.com for a live site
$header .= "Content-Length: " . strlen($req) . "\r\n";
$header .= "Connection: close\r\n\r\n";
// apre una connessione al socket PayPal
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
// converte le variabili inviate da IPN in variabili locali
$txn_id = filter_var($_POST['txn_id'], FILTER_SANITIZE_STRING);
$payment_status = filter_var($_POST['payment_status'], FILTER_SANITIZE_STRING);
$receiver_email = filter_var($_POST['receiver_email'], FILTER_SANITIZE_EMAIL);
$payer_email = filter_var($_POST['payer_email'], FILTER_SANITIZE_EMAIL);
$first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_STRING);
$last_name = filter_var($_POST['last_name'], FILTER_SANITIZE_STRING);
$address_street = filter_var($_POST['address_street'], FILTER_SANITIZE_STRING);
$address_city = filter_var($_POST['address_city'], FILTER_SANITIZE_STRING);
$address_state = filter_var($_POST['address_state'], FILTER_SANITIZE_STRING);
$address_zip = filter_var($_POST['address_zip'], FILTER_SANITIZE_STRING);
// verifica l'apertura della connessione al socket
if (!$fp) {
// se la connessione non avviene l'esecuzione dello script viene bloccata
print("connessione PayPal non avvenuta, si prega di riprovare piu' tardi");
// in alternativa è per esempio possibile inviare un'email al venditore
} else {
// elaborazione delle informazioni
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
// azioni in caso di risposta positiva da parte di PayPal
if (stripos($res, "VERIFIED") !== false) {
$myvariables = 1;
$anothermyvariables = "INSERT INTO MyDB ( paid, name, email, date)
VALUES ('". $txn_id ."','" . $first_name ." ". $last_name . "','" . $payer_email ."','". the_date('Y-m-d','','',FALSE) . "');";
$wpdb->query($anothermyvariables);
}
}
// azione in caso di risposta negativa da parte di PayPal else
if (stripos($res, "INVALID") !== false) {
$anothervariablesofmine = 2;
$paypalerr = "Pagamento non riuscito!"; // Payment not success!
}
}
// chiusura della sorgente di dati
fclose($fp);
It did work previously, but not now... I've tested the variables that PayPal return to my website with var_dump and payment_status=Completed. They seem ok.
I've tested if connection is established and also it works:
if (!$fp) {
ecc..
} else {
print("Connection Established");
etc....
The problem comes with variables stripos($res, "VERIFIED") stripos($res, "INVALID").
var_dump returns both as bool (false).
Looking on Sandbox profile History (of buyer and seller), all transactions results are completed. But the thing that makes me crazy is that one week later works perfectly...
I've searched about maybe some change in IPN listener port, host or variables by PayPal but seems none has changed. Right?
I wrote the IPN Listener directly in the page of buying form, this mean IPN Listener is called also without $_POST variables. Only possible reply for me is a spam protection from IPN Listener in PayPal side that blocked me, it's possible? 'Cause the Listener is called also without cmd=_notify-validate, but simply it just don't work (but made a blank call that perhaps isn't very appreciated by PayPal).
EDIT:
Sorry guys, re-debugged (God bless var_dump).
Putted var_dump in while loop so:
....
while (!feof($fp)) {
$res = fgets ($fp, 1024);
var_dump(stripos($res, "VERIFIED"));
print("<br> VERIFIED". stripos($res, "VERIFIED") ."<br>");
var_dump(stripos($res, "INVALID"));
print("<br> INVALID". stripos($res, "INVALID") ."<br>");
...
and find one VERIFIED int(0) instead of bool (false)
I have just changed
if (stripos($res, "VERIFIED") !== false) {
to
if (stripos($res, "VERIFIED") == 0) {
I think same in INVALID case.
But I'm still not sure if this is right.
That was the problem? Or may I have to change something else? May I have to use both if conditions (if == 0 and if !== false)?
PayPal Just changed VERIFIED return value?
What worked for me was to remove the connection close header, and add a trim to the response back from PP. Here are the headers:
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: www.paypal.com\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
Here is the fsockopen:
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
and here is the trim on the response back from PP:
if (!$fp) {
// HTTP ERROR
error_mail("Could not open socket");
//
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = trim(fgets ($fp, 1024));
}
//
// check the payment_status is Completed
// check that receiver_email is your Primary PayPal email
//
if ((strcmp ($res, "VERIFIED") == 0) && ($payment_status == "Completed") && ($receiver_email == $valid_receiver_email)) {
That worked for me.
I had a similar problem, fixed as follows :
From time to time, when my listener posts back the cmd=_notify-validate to check a new IPN, you'll get something other than "VERIFIED" or "INVALID" back.
Sometimes I get this :
'8'.chr(13).chr(10).'VERIFIED'.chr(13).chr(10).'0'.chr(13).chr(10).chr(13).chr(10)
Sometimes I get this :
'00000008'.chr(13).chr(10).'VERIFIED'.chr(13).chr(10).'00000000'.chr(13).chr(10).chr(13).chr(10))
I think if you check for those two strings in addition to "VERIFIED" or "INVALID" you'll be fine. If not, show me what you ARE getting back from paypal that is failng your stripos($res, "VERIFIED") and stripos($res, "INVALID") tests.
Also worth noting I sometimes get an error from an intermediate cache or my ISP, or paypal just times out.. so your code needs to be able to recover from that by doing cmd=_notify-validate for that IPN later.
Lastly... I struggled with IPN systems for many years. It's always a bit unreliable, the documentation is seriously wrong in a couple of places, and IPNs lag behind transactions, often by 15 minutes or more.
I have found it is far better is to use the TransactionSearch and GetTransactionDetails methods of the API.
Documentation here :
https://developer.paypal.com/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
https://developer.paypal.com/docs/classic/api/merchant/TransactionSearch_API_Operation_NVP/
These are reliable and have much less lag. I have a cron job that runs every 15 minutes to check for new transactions using those methods. I also run the new transaction check every time I receive an IPN. Let me know if you want further guidance on implementing.
I have a basic PHP mail form, but whatever I do, I cannot seem to get the characters to display correctly once sent, if the language is written with French accents.
The example sentence I am using is:
Bonjour, ceci est un message de test envoyé avec PHP pour analyser si
oui ou non la mise en forme est correcte ou fausse. Les personnages ne
devraient être rendus de manière appropriée comme prévu dans le
lexique français.
But it comes out as:
Bonjour, ceci est un message de test envoyé avec PHP pour analyser si
oui ou non la mise en forme est correcte ou fausse. Les personnages ne
devraient être rendus de manière appropriée comme prévu dans le
lexique français.
As you can see, the characters with accents are screwed up, once they are received in the email.
I am processing my message variable as such:
$fieldenquiry = utf8_encode($_POST['fieldenquiry']);
I am then, sending it like so:
$cc = "example#example.com";
$subject = "Website Enquiry";
$message = '<html><body>';
$message .= "<p><strong>Enquiry</strong><br />" . nl2br($fieldenquiry) . "</p>";
$message .= "</body></html>";
$headers = "From: " . $fieldemail . "\r\n";
$headers .= "Cc: " . $cc . "\r\n";
$headers .= "Reply-To: ". $fieldemail . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
mail($to, $subject, $message, $headers);
I'm not a PHP developer by any means. The form works in the sense that it sends etc, but I cannot figure out why the characters mess up. I am encoding the POST variable and I am sending the HTML format with a UTF-8 charset.
Help and guidance appreciated.
Michael.
EDIT:
I figured this out. See my answer below.
I figured it out if anyone is in need of a similar piece of help:
I changed this line:
$fieldenquiry = utf8_encode($_POST['fieldenquiry']);
To this:
$fieldenquiry = utf8_encode(htmlentities($_POST['fieldenquiry'], ENT_QUOTES, "UTF-8"));
I use the htmlentities() function with UTF-8 specified in the arguments.
This fixed the issue completely. Hope it helps someone.