I am using send grid to email to the server webmail. Following are my code. I wrote this code by following the tutorials. But I get error :
Warning: rawurlencode() expects parameter 1 to be string, object given in /home/cwtestco/public_html/demo/active-fit-club/sendgrid-php/vendor/guzzle/guzzle/src/Guzzle/Http/QueryString.php on line 237
Warning: Cannot modify header information - headers already sent by (output started at /home/cwtestco/public_html/demo/active-fit-club/sendgrid-php/vendor/guzzle/guzzle/src/Guzzle/Http/QueryString.php:237) in /home/cwtestco/public_html/demo/active-fit-club/index.php on line 53
Code :
if($res != false){
require_once ($_SERVER['DOCUMENT_ROOT'].'/demo/active-fit-club/sendgrid-php/vendor/autoload.php');
require_once ($_SERVER['DOCUMENT_ROOT'].'/demo/active-fit-club/sendgrid-php/lib/SendGrid.php');
require_once ($_SERVER['DOCUMENT_ROOT'].'/demo/active-fit-club/sendgrid-php/lib/SendGrid/Exception.php');
$message = "Name : $name <br> Email : $email <br> Mobile : $mobile";
$sendgrid = new SendGrid('myapikey');
$email = new SendGrid\Email();
$email
->addTo("info#abc.co.uk")
->setFrom($email)
->setSubject("Contact mail")
->setHtml($message);
try {
$sendgrid->send($email);
$_SESSION['success'] = true;
header("location:url");
exit;
} catch(\SendGrid\Exception $e) {
// echo $e->getCode();
// foreach($e->getErrors() as $er) {
// echo $er;
// }
header("location:url");
exit;
}
}
Try moving setting the header before setting the SESSION variable and set $_SESSION['success'] to be 'true' instead of true:
try {
$sendgrid->send($email);
header("location:url");
$_SESSION['success'] = 'true';
exit;
}
im using the below code and its working.
$url = 'https://api.sendgrid.com/';
$apiKey = 'SENDGRID_API_KEY';
//api library from sendgrid
require_once "sendgrid/sendgrid-php.php";
$sendgrid = new SendGrid($apiKey);
$email = new SendGrid\Email();
$email
->addTo("to#example.com")
->setFromName("Fromname")
->setFrom("from#example.com")
->setSubject("your subject goes here")
->setText('')
->setHtml("your email html content goes here");
if($sendgrid->send($email))
echo "Mail sent";
else
echo "Failed";
you can get the library files from https://github.com/sendgrid/sendgrid-php
Related
Code:
<?php
if(isset($_POST['data']) && !empty($_POST['data']) && isset($_POST['email']) && !empty($_POST['email'])) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
var_dump($email);
$data = explode(',', $_POST['data']);
mailImages($data);
}
function mailImages($data){
require_once "../PHPMailer_5.2.0/class.phpmailer.php";
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try {
$mail->CharSet = 'UTF-8';
$mail->AddReplyTo('kasper.lassner#peterwolf.agency', 'Colegio Suizo de México');
// $mail->AddAddress('******#****.agency','K L');
//$mail->AddAddress('"'.$email.'"','');
$mail->AddAddress($email,'test');
$mail->SetFrom('*******#********.agency', 'Colegio Suizo de México');
$mail->Subject = 'CSM Fotos';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML('Test message');
foreach($data as $image){
$mail->AddAttachment(realpath(dirname(__FILE__)).'/'.str_replace(' ','',$image));
}
$mail->Send();
echo 'OK';
} catch (phpmailerException $e) {
//echo $e->errorMessage();
echo $mail->ErrorInfo;
} catch (Exception $e) {
echo 'NO';//Boring error messages from anything else!
}
}
?>
So my problem is the following: I get an "Invalid Address:"" Error. When I comment this line:
$mail->AddAddress($email,'test');
And uncomment this line:
$mail->AddAddress('******#****.agency','K L');
Passing a string value works. So the problem clearly is that the $email variable somehow isn't accepted. The var_dump outputs this: "string(24) "*******#****.com" so it is a string.
I've searched in already existing answers and couldn't find that specific issue.
Any help is greatly appreciated.
Your problem is explained in http://php.net/manual/en/language.variables.scope.php.
By default, every variable you use in a function is implicitly local to that function. The $email in mailImages is unrelated to the $email outside. Because the variable is not set, it causes the "Invalid Address" error.
You can fix this by either adding another function parameter:
function mailImages($data, $email) { ... }
// call as
mailImages($data, $email);
or by explicitly marking $email as global:
function mailImages($data) {
global $email;
...
}
Ok, my problem is that when i try to make my confirm link with the random code that i already created, it wont pass to the Confirmation mail. However the confirm code, still inserts to the database without problems. This is my code:
function NewUser()
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$confirm = md5(uniqid(rand(), true));
$success = "INSERT INTO members(user,pass,'$confirm')";
$data = mysql_query ($success)or die(mysql_error());
if($data)
{if($data)
{
SendUserConfirmationEmail($confirm);
echo "<div class ='verdanacenter'><img src='img/bienvenido.png' title='Enhorabuena'/><br><br><br><font face ='verdana'>Welcome <b>$name $lname</b> !!!<br>Success.<br><br>Soon u will receive a confirmation msg to <b>$email</b>";
}
else
{
echo "<div class ='verdanacenter'><img src='img/alerta.png' title='Error'/><br><br><br><font face ='verdana'>Fatal Error !!!";
}
}
function SendUserConfirmationEmail($confirmcode)
{
require 'PHPMailerAutoload.php';
$mail = new PHPMailer();
$mail->isSendmail();
$mail->setFrom('info#rene.org', 'Rene');
$mail->addAddress($_POST['email'],$_POST['name']);
$mail->Subject = 'Welcome';
$mail->IsHTML(true);
$confirmcode = $confirm;
$mail->Body = '<p align="left"> Welcome <b>'.$_POST['name'].'</b>,</p><p align="justify">This is ur confirmation code:</p>
<p align="left">CONFIRMAR,</p>
<p align="left">Regards,<br>
Admin.<br>
www.rene.org</p>';
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
The thing is that, when i register, i receive the email, but without the random code ($confimcode). It appears: "http://www.rene.org/confirmar.php?code=" instead of "http://www.rene.org/confirmar.php?code=A23B45423545V6764542543" What am i missing guys? PLEASE HELP.
This is called scope.
The function can't see variables from outside of itself. To pass that code to the function you include it in a parameter:
function SendUserConfirmationEmail($confirmcode){
...
when you call the function you pass your variable:
SendUserConfirmationEmail($confirm);
Anywhere inside your function, that value will be available as $confirmcode
Edit: Also just noticed you have a function inside a function. Don't do that, just make them separate.
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 trying to use php sendgrid to send emails from a contact form. I only need the simplest implementation and followed the basic steps indicated here: https://github.com/sendgrid/sendgrid-php
Here's my code:
require_once 'sendgrid-php/lib/SendGrid.php';
require_once 'unirest-php/lib/Unirest.php';
function spamcheck($field) {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
if (isset($_REQUEST['email'])) {
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck == FALSE) {
echo "Invalid Input";
} else {
$email = $_REQUEST['email'];
$name = $_REQUEST['name'];
$company = $_REQUEST['company'];
$message = $_REQUEST['message'];
$subject = "This is the subject";
$recipient = "test#email.com"; // Not the real value
$username = 'test'; // Not the real value
$password = '1234'; // Not the real value
$sendgrid = new SendGrid($username, $password);
$mail = new SendGrid\Email();
$body = "Name: " . $name . "\n" .
"Company: " . $company . "\n" .
"Message: " . $message;
$mail->addTo($recipient)->
setFrom($email)->
setSubject($subject)->
setText($message);
$sendgrid->smtp->send($mail);
echo 'SUCCESS';
}
} else {
echo "Fail";
}
And I'm getting this error:
<br />
<b>Fatal error</b>: Class 'SendGrid\Email' not found in <b>/usr/local/www/vhosts/.../intl/mail.php</b> on line <b>27</b><br />
Also, when I try to add this to my code (As indicated in the above link):
SendGrid::register_autoloader();
I get this error:
<br />
<b>Warning</b>: require_once(swift_required.php): failed to open stream: No such file or directory in <b>/usr/local/www/vhosts/.../intl/sendgrid- php/lib/SendGrid/Smtp.php</b> on line <b>25</b><br />
<br />
<b>Fatal error</b>: require_once(): Failed opening required 'swift_required.php' (include_path='.:/usr/local/share/pear') in <b>/usr/local/www/vhosts/.../intl/sendgrid- php/lib/SendGrid/Smtp.php</b> on line <b>25</b><br />
^ Based on that, I won't be using swift mailer so it might not be related.
What am I missing?
*PHP Version 5.4.21
*SendGrid Version 1.1.6
I did not install swiftmailer, but I did install smtpapi-php and unirest-php
https://github.com/Mashape/unirest-php
https://github.com/sendgrid/smtpapi-php
My test code looks like this:
require_once ('../includes/sendgrid-php/lib/SendGrid.php');
require_once ('../includes/smtpapi-php/lib/Smtpapi.php');
require_once ('../includes/unirest-php/lib/Unirest.php');
SendGrid::register_autoloader();
Smtpapi::register_autoloader();
$sendgrid = new SendGrid('user', 'pass');
$email = new SendGrid\Email();
$email->addTo( $to)->
setFrom($from)->
setSubject($subject)->
setText('Test')->
setHtml($html);
$x = $sendgrid->send($email);
var_dump($x );
And it works on php 5.4
Since you are using the SMTP sending method:
$sendgrid->smtp->send($mail);
You need to install swiftmailer. Instructions for that are here: https://github.com/sendgrid/sendgrid-php#optional
Your other option is to send using web - which is actually what we recommend at SendGrid now. It's faster than the chatty SMTP protocol.
$sendgrid->web->send($mail);
I have a contact form, but the messages are not sending to the email I have declared. This is the submit.php file:
<?php
/* config start */
$emailAddress = 'xxxxxxx#hotmail.com';
/* config end */
require "../php/class.phpmailer.php";
session_name("fancyform");
session_start();
foreach($_POST as $k => $v)
{
if(ini_get('magic_quotes_gpc'))
$_POST[$k] = stripslashes($_POST[$k]);
$_POST[$k] = htmlspecialchars(strip_tags($_POST[$k]));
}
$err = array();
if(!checkLen('name'))
$err[] = 'The name field is too short or empty!';
if(!checkLen('email'))
$err[] = 'The email field is too short or empty!';
elseif(!checkEmail($_POST['email']))
$err[] = 'Your email is not valid!';
if(!checkLen('subject'))
$err[] = 'You have not selected a subject!';
if(!checkLen('message'))
$err[] = 'The message field is too short or empty!';
if((int)$_POST['captcha'] != $_SESSION['expect'])
$err[] = 'The captcha code is wrong!';
if(count($err))
{
if($_POST['ajax'])
{
echo '-1';
}
else if($_SERVER['HTTP_REFERER'])
{
$_SESSION['errStr'] = implode('<br />', $err);
$_SESSION['post'] = $_POST;
header('Location: '.$_SERVER['HTTP_REFERER']);
}
exit;
}
$msg =
'Name: '.$_POST['name'].'<br />
Email: '.$_POST['email'].'<br />
IP: '.$_SERVER['REMOTE_ADDR'].'<br /><br />
Message:<br /><br />
'.nl2br($_POST['message']).'
';
$mail = new PHPMailer();
$mail->IsMail();
$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->AddAddress($emailAddress);
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->Subject = "A new ".mb_strtolower($_POST['subject'])." from ".$_POST['name']." | contact form feedback";
$mail->MsgHTML($msg);
$mail->Send();
unset($_SESSION['post']);
if($_POST['ajax'])
{
echo '1';
}
else
{
$_SESSION['sent'] = 1;
if($_SERVER['HTTP_REFERER'])
header('Location: '.$_SERVER['HTTP_REFERER']);
exit;
}
function checkLen($str, $len = 2)
{
return isset($_POST[$str]) && mb_strlen(strip_tags($_POST[$str]), "utf-8") > $len;
}
function checkEmail($str)
{
return preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
}
?>
If submit.php is opened in a browser, I get the following error message:
Warning: require(../php/class.phpmailer.php) [function.require]: failed to open stream:
No such file or directory in
/home/content/96/9227096/html/submit.php on line 10 Fatal error: require() [function.require]: Failed opening required
'../php/class.phpmailer.php'
(include_path='.:/usr/local/php5_3/lib/php') in
/home/content/96/9227096/html/submit.php on line 10
I was also told by my hosting server that I might need to add the following relay server in my code:(but I don't know where)
relay-hosting.secureserver.net
The statement require "../php/class.phpmailer.php"; means that the ../php/class.phpmailer.php file will be loaded and that if it can't be loaded then the script will terminate.
It is unable to load that script. That could be for any of a number of reasons. Maybe it's not there. Maybe the path you provided is wrong. Maybe it's a file permission issue. You'll have to figure that part out.
But since it can't load it, the script terminates with the error message.
I have encounter similiar problems on some hosting providers. Even if the path was good require did not include file and terminated whole script. You could write there a real path to your file, and maybe that will help. Since this problem I started to use
require(getcwd().'actual/path/relevant/to/index.php');
and starder to write apps in one class, similiar to Java or C# desktop apps.