I'm trying to send mail for a contact form locally by swiftmailer and gmail. I've checked every line and I know the problem is 'setFrom' .
$app->post('/contact', function ($request, $response, $args){
$body = $this->request->getParsedBody();
$name = $body['name'];
$email = $body['email'];
$msg = $body['msg'];
if(!empty($name) && !empty($email) && !empty($msg) ){
$cleanName = filter_var($name,FILTER_SANITIZE_STRING);
$cleanEmail = filter_var($name,FILTER_SANITIZE_EMAIL);
$cleanMsg = filter_var($name,FILTER_SANITIZE_STRING);
}else {
//redirecting to contact page
}
//sending email
$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername('xxx#gmail.com')
->setPassword('xxx');
$mailer= \Swift_Mailer::newInstance($transporter);
$message = \Swift_Message::newInstance();
$message->setSubject('Email from our website');
$message->setTo(array('ns.falahian#gmail.com'));
$message->setBody($cleanMsg);
$message->setFrom([
$cleanEmail => $cleanName
]);
$result=$mailer->send($message);
if ($result > 0) {
$path = $this->get('router')->pathFor('home');
return $response->withRedirect($path);
} else {
$path = $this->get('router')->pathFor('contact');
return $response->withRedirect($path);
}
});
as you can see I also use Slim 3 framework. when I run the code I get this error:
Slim Application Error
A website error has occurred. Sorry for the temporary inconvenience.
But if I replace the $cleanEmail with 'x#y.z' the code works!
what should I do?
I know that by using gmail I can't change the sender name but I want to upload this code in a webhost and I don't want to get this issue there.
And can anyone suggest a better way for redirecting in Slim 3? Instead of these two lines:
$path = $this->get('router')->pathFor('contact');
return $response->withRedirect($path);
I've set names for my routes like this:
$app->get('/contact', function ($req, $res, $args) {
return $this->view->render($res, "contact.twig");
})->setName('contact');
thanks a lot!
You probably want to do the following instead.
$cleanEmail = filter_var($email,FILTER_SANITIZE_EMAIL);
$cleanMsg = filter_var($msg,FILTER_SANITIZE_STRING);
Related
I have two forms that sends data using ajax. Both forms have their own scripts and I thought that I would be able to access the same $_POST[] variables on the separate scripts, but this is not working. I tried using session_start() and include_once and for some reason I can't figure out why the variables are not passing from script to script. I've been at it for three days researching for a solution so if you know what I'm doing wrong or have an alternative please let me know thanks.
javascript.
$('.test-input').load("test.php", {
'sendTo':sendTo,
'carrier':carrier,
'testSubmit':testSubmit
})
$('#error-display').load("textsms.php", {
'date':scheduleDate,
'firstname':firstName,
'number':number,
'message':message,
'time':time,
'service':service,
'submit':submit
})
test.php
if (isset($_POST['testSubmit'])) {
$sendTo = $_POST['sendTo'];
$carrier = $_POST['carrier'];
$sendToInvalid = false;
$testEmpty = false;
$sendTo = "";
if (!preg_match('/^\(?\b\d{3}[-.)\s]?\s?\d{3}[-.)\s]?\d{4}\b$/', $sendTo) and $sendTo !== '') {
$sendToInvalid = true;
} elseif (empty($sendTo) || empty($carrier)) {
$testEmpty = true;
} else {
$sendTo = preg_replace('/[-.()\s]/','',$sendTo).$carrier;
$_SESSION['sendTo'] = $sendTo;
}
}
Trying to get $sendTo to pass to textsms.php down below.
else {
include 'test.php';
$sendTo = $_SESSION['sendTo'];
$number = preg_replace('/[-.()\s]/','',$number);
$number = "(".substr($number,0,3).") ".substr($number,3,3)."-".substr($number,6,4);
if ($sendTo !== "contactme#aboutryansam.com") {
$header = $name."\r\n#: ".$number;
$sendMsg = $userMsg."\r\nOn: ".$date.$time."\r\nService: ".$service;
//mail($sendTo, "You win!", $sendMsg, $header);
echo $sendTo;
echo "it worked";
}
Of course, on the page you initialize the ajax, include the "header.php" file that has inside session_start(). include_once('header.php') in the test.php as well. It should do the trick.
It's not a good practice nowadays, I better suggest you to use cookies and access them with $_COOKIE. Even better, use a library that takes care of cookies like this one. JQuery also has very good cookie management.
I'm trying to use the mailgun api to send user registration confirmation emails from my website. My site is on a shared host. The mailgun api seems to work perfectly, when I test it out on a localhost (WAMP server). when I try to use the api in my source code, i.e. inside a controller, I get a syntax error. The shared host is a linux based (CentOS) server.
This is the error message.
Parse error: syntax error, unexpected '[' in /var/www/html/log2pdf/mailgun/vendor/guzzlehttp/psr7/src/functions.php on line 78
Since it was a syntax error, I downloaded and installed the mailgun dependancies (i.e. composer, guzzle adapter etc.) separately on the linux server, because I had originally copied the files from my localhost (windows) and was under the
impression that these files are different for windows and linux. But that made no difference either.
Running php 5.6.25 on localhost (WAMP), php 5.3.3 on shared host(CentOS). All the mailgun dependencies were installed using the commands on the mailgun webpage.
I have tried all that I could, any help on this will be greatly appreciated.
This is my controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require '/var/www/html/mysite/mailgun/vendor/autoload.php';
use Mailgun\Mailgun;
class Register extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('User_model');
$this->load->helper('cookie');
}
public function index($param = '')
{
if (($this->session->userdata('userLogin') == TRUE))
{
redirect(site_url('users/dashboard')); }
if (isset($_POST['registration'])){
$data['postdata'] = $_POST;
if(!empty($_POST['firstname']) && !empty($_POST['lastname']) &&
!empty($_POST['email']) && !empty($_POST['password']) &&
!empty($_POST['organization']) && !empty($_POST['country']) &&
!empty($_POST['address'])){
$checkEmail = $this->User_model->checkEmail();
if($checkEmail==true){
$this->session->set_flashdata('error', '<p><font>
This Email id is already registered!</font></p>');
}else{
$un = str_replace(' ', '',$_POST['firstname'].$_POST['lastname']);
//remove all spaces
$unwsc = preg_replace('/[^A-Za-z0-9\-]/', '', $un);
// Removes special chars.
$checkusername = $this->User_model->checkusername($unwsc);
if($checkusername==true){
$username = $this->getUserName($unwsc);
}else{
$username = $unwsc;
}
$data['code'] = rand(0,100000);
$data['username'] = $_POST['firstname'];
$this->User_model->saveUser($username,$data['code']);
mkdir("/var/www/html/users/".$username);
/*
$fromemail="_my_organisation's_email_";
$subject = "Registration Confirmation";
//this was the email sender that i used initially
//it's codeigniter's built in email library. but after a
//while, emails stopped being delivered.
$this->load->library('email');
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->to($_POST['email']);
$this->email->from($fromemail, "_my_organisation's_email_");
$this->email->subject($subject);
$body = $this->load->view('email/register.php',$data,TRUE);
$this->email->message($body);
$this->email->send();
*/
$subject = "Registration Confirmation";
$body = $this->load->view('email/register.php',$data,TRUE);
//using mailgun api
# Instantiate the client.
$mgClient = new Mailgun('_my_mailgun_key_');
$domain = "_my_maigun_domain_";
# Make the call to the client.
$result = $mgClient->sendMessage($domain, array(
'from' => 'NO REPLY <_my_organisation's_email_>',
'to' => 'new user <_authorized_recipient_>',
'subject' => 'Mailgun test',
'text' => 'testing email sender'
));
$this->session->set_flashdata('success','<p><font>Thanksfor registration! </font></p>');
redirect(site_url('register/complete'));
}
}else{
$this->session->set_flashdata('error', '<p><font>
Missing Some Fields!</font></p>');
}
}
$data['title']='';
$data['param']=$param;
$this->load->view('registration/index',$data);
}
function getUserName($string) {
$result = $string;
for ($i = 1; $i < 100; $i++) {
$userChecking = $this->User_model->checkusername($string.$i);
if(empty($userChecking)){
$result = $string.$i;
break;
}
}
return $result;
}
}
?>
The problem was solved after updating PHP to version 5.6.30. After a long duration of talk with Godaddy's customer support, They suggested that I update my PHP. It worked perfectly after.
I'm trying to write a simple Constant Contact script for adding and updating emails. The script is simple enough and should've ran smoothly. But when I start to include 'src/Ctct/autoload.php' the page just returns blank. I tried running it on another server and it works. But on my working server, it returns blank. It uses OAuth authentication from CTCT. I think it's a setting in the server, but I have no control over the server and any changes need to be forwarded to an admin, I just don't know what I need to change.
Here's the code:
require "Scripts/ConstantContact/src/Ctct/autoload.php";
use Ctct\ConstantContact;
use Ctct\Components\Contacts\Contact;
use Ctct\Components\Contacts\ContactList;
use Ctct\Components\Contacts\EmailAddress;
use Ctct\Exceptions\CtctException;
define("APIKEY", "*** Censored Media (18+ only) ***");
define("ACCESS_TOKEN", "*** Censored Media (18+ only) ***");
$cc = new ConstantContact(APIKEY);
// attempt to fetch lists in the account, catching any exceptions and printing the errors to screen
$lists = $cc->getLists(ACCESS_TOKEN);
$action = "Getting Contact By Email Address";
$Email = "asdf#asdf.com";
$FirstName = "Asdf";
$LastName = "Ghjk";
// check to see if a contact with the email addess already exists in the account
$response = $cc->getContactByEmail(ACCESS_TOKEN, $Email);
// create a new contact if one does not exist
if (empty($response->results)) {
$action = "Creating Contact";
$contact = new Contact();
$contact->addEmail($Email);
$contact->addList('1');
$contact->first_name = $FirstName;
$contact->last_name = $LastName;
$returnContact = $cc->addContact(ACCESS_TOKEN, $contact);
// update the existing contact if address already existed
} else {
$action = "Updating Contact";
$contact = $response->results[0];
$contact->addList('1');
$contact->first_name = $FirstName;
$contact->last_name = $LastName;
$returnContact = $cc->updateContact(ACCESS_TOKEN, $contact);
}
// catch any exceptions thrown during the process and print the errors to screen
if (isset($returnContact)) {
echo '<div class="container alert-success"><pre class="success-pre">';
print_r($returnContact);
echo '</pre></div>';
}
print '<p>'.$action.'</p>';
Again, this works on another server I tried, but doesn't work on my working server.
Any help would be appreciated.
Thanks!
Are you running PHP 5.3 or higher on the other server? Also did the domain change at all, if so that may throw an exception resulting in a blank page as your API key is domain specific. Feel free to shoot me an email and I will be glad to help you out with this - mstowe [at] constantcontact.com
-Mike
I'm working on adding a script to my site for a MailChimp subscribe form. I think I have everything setup right but when I hit the subscribe button I'm getting a blank page.
Here is the script I have currently
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once 'Mailchimp.php';
$apikey = "XXXXXXXXXXXXXXX";
$Mailchimp = new Mailchimp($apikey);
if (!empty($_POST)) {
$id = "XXXXXXXXXX";
$email = array(
'email' => trim($_POST['email'])
);
$result = $Mailchimp->$lists->subscribe($id, $email, $double_optin=false, $replace_interests=false);
var_dump($result);
}
echo "TESTING";
So I'm not getting the $result variable or "TESTING echo'd right now, so I assume I must be doing something simple wrong. Anyone see anything obvious? I believe I'm using the correct default JSON format. (keys have been X'd out, but the one's I'm using are correct)
Any help is much appreciated.
Thanks!!
EDIT: I have updated the code to something I believe to be more correct, but it still isn't working. I could really use some help on this.
Here's how I've handled AJAX email submissions in the past for MailChimp's API (MCAPI):
define("MC_API_KEY", "Your mailchimp API key");
define("MC_API_LIST", "The list ID to subscribe user to");
define("EMAIL_TO", "email address in case subscription fails");
require "MailChimp.API.class.php";
function json($error = true, $message = "Unknown error") {
die(json_encode(array("error" => $error, "message" => $message)));
}
if(!empty($_POST)) {
$email = !empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : false;
if($email !== false) {
$api = new MCAPI(MC_API_KEY);
$result = $api->listSubscribe(MC_API_LIST, $email);
if($api->errorCode || !$result) {
if(isset($api->errorCode) && $api->errorCode == 214) { // already subscribed
json(true, "You are already subscribed!");
} else {
$error = "Unable to save user email via MailChimp API!\n\tCode=".$api->errorCode."\n\tMsg=".$api->errorMessage."\n\n";
$headers = "From: your#email.com\r\nReply-to: <{$email}>\r\nX-Mailer: PHP/".phpversion();
mail(EMAIL_TO, "Newsletter Submission FAIL [MC API ERROR]", "{$error}Saved info:\nFrom: {$email}\n\nSent from {$_SERVER['REMOTE_ADDR']} on ".date("F jS, Y \# g:iA e"), $headers);
json(false, "Thank you - your email will be subscribed shortly!");
}
} else {
json(false, "Thanks - A confirmation link has been sent to your email!");
}
} else {
json(true, "Please enter your valid email address");
}
} else json();
SOLVED:
Here is the correct code - hopefully this will help others looking to use the new api -
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once 'Mailchimp.php';
$apikey = "XXXXXXXXXXXXXXXXXXX";
$Mailchimp = new Mailchimp($apikey);
if (!empty($_POST)) {
$id = "XXXXXXXXXX";
$email = array(
'email' => trim($_POST['email'])
);
$result = $Mailchimp->lists->subscribe($id, $email, $merge_vars=null, $double_optin=false, $replace_interests=false);
}
I'm using a 3rd party SMTP service for sending my newsletters. Because of that, my ISP does not accept bounces because they are coming from an email not originating with them. Okay. So I set up a mailbox with my SMTP service to accept the bounces.
However, my mailing list program is refusing to send out emails whose return-path has a different domain than the from field.
I believe this is caused by phpmailer in it's mailsend routine:
The key code appears to be this, but I'm not that much of an expert with PHP to figure out how to get around whatever check it is doing, which I think has something to do with that safe_mode. The return-path value that I want to use is in the variable: $this->Sender
/**
* Sends mail using the PHP mail() function.
* #param string $header The message headers
* #param string $body The message body
* #access protected
* #return bool
*/
protected function MailSend($header, $body) {
$toArr = array();
foreach($this->to as $t) {
$toArr[] = $this->AddrFormat($t);
}
$to = implode(', ', $toArr);
$params = sprintf("-oi -f %s", $this->Sender);
if ($this->Sender != '' && strlen(ini_get('safe_mode'))< 1) {
$old_from = ini_get('sendmail_from');
ini_set('sendmail_from', $this->Sender);
if ($this->SingleTo === true && count($toArr) > 1) {
foreach ($toArr as $key => $val) {
$rt = #mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
// implement call back function if it exists
$isSent = ($rt == 1) ? 1 : 0;
$this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$ body);
}
} else {
$rt = #mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
// implement call back function if it exists
$isSent = ($rt == 1) ? 1 : 0;
$this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$b ody);
}
} else {
if ($this->SingleTo === true && count($toArr) > 1) {
foreach ($toArr as $key => $val) {
$rt = #mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
// implement call back function if it exists
$isSent = ($rt == 1) ? 1 : 0;
$this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$ body);
}
} else {
$rt = #mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
// implement call back function if it exists
$isSent = ($rt == 1) ? 1 : 0;
$this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$b ody);
}
}
if (isset($old_from)) {
ini_set('sendmail_from', $old_from);
}
if(!$rt) {
throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
}
return true;
}
Does anyone know what in this code is preventing me from using a different domain for my return-path, or better yet, does anyone know how I can fix (or hack) this so it will send out my mail?
#Sanmai's comment got me looking at the parameters. When I started testing some of them in the phpmailer routine, I found the code wasn't executed. So at least he helped me realize the problem's somewhere else.
I still have the problem. I'll now try to better isolate it. Then maybe I can solve it, and if not, I'll modify this question and try again.
Thanks for giving me a bit of something to go on.
What error are you getting? It could be that the mailer server you are using doesn't allow different return address domains to prevent their service being used to send spam.