magento mail not sending - php

Try block for email sending is working, but it directly redirect to another page without sending mail. smtp setting are okay. This code was working perfectly but now nothing is happening.
try{ ..........................................//mail senting
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
//get customer details
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customer->getId();
$customer->getEmail();
//get general store details
$from_name = Mage::getStoreConfig('trans_email/ident_general/name');
$from_email = Mage::getStoreConfig('trans_email/ident_general/email');
$templateId=7;
$emailTemplate = Mage::getModel('core/email_template')->load($templateId);
//$emailTemplateVariables = array();
//$emailTemplateVariables[‘name′] = "$mh"";
$processedTemplate = $emailTemplate->getProcessedTemplate();
$mail=Mage::getModel('core/email');
$mail->setToName($customer->getId());
$mail->setToEmail($customer->getEmail());
$mail->setBody($processedTemplate);
$mail->setSubject("Upload Conformation ");
// print_r($mail);
//die;
$mail->setFromEmail($from_email);
$mail->setFromName($from_name);
$mail->setType('html');
try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
} catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
}
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl().'bank-info/');
} catch (Exception $ex) {
Mage::getSingleton('core/session')->addError($ex->getMessage());
Mage::log($ex->getMessage());
Mage::getSingleton("supplierfrontendproductuploader/session")->setProductData($postData);
if($editMode) {
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl() . 'supplierfrontendproductuploader/product/edit/id/'.$postData['product_id']);
} else {
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl() . 'supplierfrontendproductuploader/product/create/');
}

Related

SendGrid and PHP to multiple recipents

I'm using sendgrid to send out html emails from a document system I'm building. When a file uploads sendgrid needs to email all those associated with that case. I have everything working for individual emails and I can customs the template I have saved but cant send the email to multiple recipients
I have generated an array of recipients
$email = array(j.bloggs#bloggs.com, j.doe#me.net, d.smith#smith.co.uk);
I want to pass this into my sendgrid email object to send to them all
private function send() {
$sg = new \SendGrid(self::$key);
$response = $sg->client->mail()->send()->post(self::$mail);
return $response->statusCode();
}
public function file_saved($file="", $case="") {
self::$from = new SendGrid\Email($this->fromName, $this->fromEmail);
self::$to = new SendGrid\Email($this->toName, $this->toEmail);
self::$content = new SendGrid\Content("text/html", "Hello, Email!");
self::$mail = new SendGrid\Mail(
self::$from,
$this->subject,
self::$to,
self::$content
);
$str = "<p>A file has been successfully uploaded to {$case->case_name} ({$case->case_code}).</p>
<br />
<p>{$file->file_name} - ".size($file->file_size)."</p>";
self::$mail->personalization[0]->addSubstitution("-name-", $this->toName);
self::$mail->personalization[0]->addSubstitution("-str-", $str);
self::$mail->personalization[0]->addSubstitution("-btn-", "Download File");
self::$mail->personalization[0]->addSubstitution("-url-", HTTP.BASE_URL.DS.'uploads'.DS.$file->file_path);
self::$mail->setTemplateId("2f845487-6243-4562-b6fb-022185b7fde7");
if (!$this->send() == 202) {
return false;
}
else {
return true;
}
}
I tried to use the personalization->to and pass that the array but get the error
Call to a member function to() on null in includes/classes/mail.php on line <b>82</b><br />
I just created a loop that went through each recipient and sent them an email, not as efficient as generating a multiple to: list but for now its working until I get a response from the sendgrid dev team
$this->email = array(j.bloggs#bloggs.com, j.doe#me.net, d.smith#smith.co.uk);
private function send() {
$sg = new \SendGrid(self::$key);
$response = $sg->client->mail()->send()->post(self::$mail);
return $response->statusCode();
}
public function file_saved($file="", $case="") {
$str = "<p>A file has been successfully uploaded to {$case->case_name} ({$case->case_code}).</p>
<br />
<p>{$file->file_name} - ".size($file->file_size)."</p>";
self::$from = new SendGrid\Email($this->fromName, $this->fromEmail);
self::$content = new SendGrid\Content("text/html", "Hello, Email!");
foreach($this->email as $email_addr) {
self::$to = new SendGrid\Email($this->toName, $email_addr);
self::$mail = new SendGrid\Mail(
self::$from,
$this->subject,
self::$to,
self::$content
);
self::$mail->personalization[0]->addSubstitution("-str-", $str);
self::$mail->personalization[0]->addSubstitution("-btn-", "Download File");
self::$mail->personalization[0]->addSubstitution("-url-", HTTP.BASE_URL.DS.'uploads'.DS.$file->file_path);
self::$mail->setTemplateId("2f845487-6243-4562-b6fb-022185b7fde7");
if (!$this->send() == 202) {
$response[$address] = false;
}
else {
$response[$address] = true;
}
}
return $response; // contains true/false for each email address if sent or not.
}

How to set sendAsEmail via Google's Gmail api

I'm updating a PHP application to create new email accounts in Google (using the Google Directory Service). I have no problem creating the account, but so far I've been unable to use the Google Gmail Service to set the sendAsEmail attribute (so that the alias will show up in the "From"). Also, var_dump($createSendAsResult) in the snippet below does not produce any output. Any help would be appreciated. Thanks!
Here's my code:
//Create account in Google
function createGoogleAccount($server_name, $acc_user, $acc_password)
{
$clientDir = getClientDir($server_name);
$dirService = new Google_Service_Directory($clientDir);
$userInstance = new Google_Service_Directory_User();
$nameInstance = new Google_Service_Directory_UserName();
$nameInstance -> setGivenName('Generic');
$nameInstance -> setFamilyName($acc_user);
$userInstance -> setOrgUnitPath("/generic_email");
$userInstance -> setName($nameInstance);
$userInstance -> setHashFunction("MD5");
$domain = getDomain($server_name);
$primary_email = $acc_user . '#' . $domain;
$userInstance -> setPrimaryEmail($primary_email);
$userInstance -> setPassword(hash("md5", $acc_password));
$optParams = array( );
$error_msg = null;
try
{
$createUserResult = $dirService->users->insert($userInstance, $optParams);
var_dump($createUserResult);
}
catch (Google_IO_Exception $gioe)
{
$error_msg = "Error in connection: ".$gioe->getMessage();
}
catch (Google_Service_Exception $gse)
{
$error_msg = "Service Exception: ".$gse->getMessage();
}
addSendAs($server_name, $acc_user, $domain); return $error_msg;
}
function addSendAs($server_name, $acc_user, $domain)
{
$clientGmail = getClientGmail($server_name);
$gmailService = new Google_Service_Gmail($clientGmail);
$primary_email = $acc_user . '#' . $domain;
$sendAsEmail = new Google_Service_Gmail_SendAs();
$alias = '';
if (($server_name == null) || (strpos($server_name, "dev") != false))
{
$alias = '#g.';
}
else
{
$alias = '#mail.';
}
$sendAsEmail -> setSendAsEmail($acc_user . $alias . $domain);
$sendAsEmail -> setIsDefault(TRUE);
$sendAsEmail -> setIsPrimary(TRUE);
$error_msg = null;
try
{
$createSendAsResult = $gmailService->users_settings_sendAs -> create($primary_email, $sendAsEmail);
var_dump($createSendAsResult);
}
catch (Google_IO_Exception $gioe)
{
$error_msg = "Error in connection: ".$gioe->getMessage();
}
catch (Google_Service_Exception $gse)
{
$error_msg = "Service Exception: ".$gse->getMessage();
}
}
Finally, after much experimentation with the code and some help from a couple of colleagues, I figured out what the problem is and how to solve it.
Apparently, Google needs time to set up a new user's account with email. When I added a 10-second delay - sleep(10) in php - that was sufficient for the account to be ready for calls to the Gmail API, including the creation of a SendAs alias.

How to send multiple emails?

I'm trying to send email to selected users by nette mailer but it allways results with an InvalidStateException.
public function contactsEditorFormSucceeded($form, $values)
{
try {
$recipients = $values->recipients;
$mail = new Message;
$mail->setFrom($values->email)
->setSubject($values->subject)
->setBody($values->message);
foreach ($recipients as $recipient) {
$mail->addTo($recipient);
}
$mailer = new SendmailMailer;
$mailer->send($mail);
$this->flashMessage('Done.', self::MSG_SUCCESS);
$this->redirect('this');
} catch (InvalidStateException $ex) {
$this->flashMessage('Error', self::MSG_ERROR);
}
}
I'm using foreach to get multiple addTo() but it will not send the mails.
Message can not have multiple recipients. It is necessary to create a cycle and create so many messages about how many recipients are
public function contactsEditorFormSucceeded($form, $values)
{
try {
$recipients = $values->recipients;
foreach ($recipients as $recipient) {
$mail = new Message;
$mail->setFrom($values->email)
->setSubject($values->subject)
->setBody($values->message)
->addTo($recipient);
$mailer = new SendmailMailer;
$mailer->send($mail);
}
$this->flashMessage('Done.', self::MSG_SUCCESS);
$this->redirect('this');
} catch (InvalidStateException $ex) {
$this->flashMessage('Error', self::MSG_ERROR);
}
}

stripe webhook test mode response "none"

I am trying to update database.
I have set up the webhook in stripe in test mode and send a "invoice.payment_succeeded" test webhook to file.but it shows response "none" in stripe output.
What have i done wrong, here is the webhook file, please someone help me, i am very stuck at this. any help will be appreciate...
<?php
include '../admin/include/functions.php';
require_once('Stripe/lib/Stripe.php');
require_once 'stripe_secret.php';
// Retrieve the request's body and parse it as JSON
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
$event_id = $event_json->id;
if(isset($event_json->id)) {
try {
Stripe::setApiKey($stripe['secretkey']);
$event = Stripe_Event::retrieve($event_id);
var_dump($event);
$invoice = $event->data->object;
if($event->type == 'invoice.payment_succeeded') {
$customer = Stripe_Customer::retrieve($invoice->customer);
$email = $customer->email;
$customerid = $customer->id;
/*$amount = $invoice->amount / 100;*/
$expiry = $invoice->period->end;
$expiredate = date('Y-d-m', $expiry);
$userup = $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' ");
if ($userup) {
echo "User Date extended";
}
// send a invoice notice email here
}
if($event->type == 'invoice.payment_failed') {
$obj->run_query("UPDATE users SET Status = '0' WHERE user_stripe_id = '$customerid' ");
echo "User membership expired";
}
}
catch(Stripe_CardError $e) {
}
catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
}
http_response_code(200);
?>
The test webhooks from the test webhook button sends a webhook with the right format but all the values are null / zero / etc. Thus your line that does $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' "); will return a falsey result. This means you don't echo anything and just send back an empty 200 response.

Google Cloud Messaging (GCM) Notification receiving with logs detail

I have implement the gcm to send notification to my application and its really working perfect.
I am getting notification on device but issue is that I am getting logs detail may be in notification message instead of only human readable message that I am pushing.
Here is my code that I am using to send notification:
$gcmApiKey = GOOGLE_API_KEY;
$pushApi = new PushAPI();
$sender = new \PHP_GCM\Sender($gcmApiKey);
$message = new \PHP_GCM\Message("1", $messsageVal);
try {
$multicastResult = $sender->sendMulti($message, $deviceRegistrationId, 2);
$results = $multicastResult->getResults();
for ($i = 0; $i < count($deviceRegistrationId); $i++) {
$regId = $deviceRegistrationId[$i];
$result = $results[$i];
$messageId = $result->getMessageId();
if ($messageId != null) {
$canonicalRegId = $result->getCanonicalRegistrationId();
if ($canonicalRegId != null) {
// same device has more than on registration id: update it
}
} else {
$error = $result->getErrorCodeName();
if ($error == \PHP_GCM\Constants::$ERROR_NOT_REGISTERED) {
$pushApi->clearDeviceByDeviceId($regId);
}
}
}
} catch (\InvalidArgumentException $e) {
// $deviceRegistrationId was null
} catch (PHP_GCM\InvalidRequestException $e) {
// server returned HTTP code other than 200 or 503
} catch (\Exception $e) {
// message could not be sent
}
Here is the link of whole API that I am using. PHP_GCM
I try to google it but I didn't get anything to rectify this.
Any help will be appreciated.
You have to parse your response same as you parse a webservice response and show only the msg.
Try getting the message from the received intent using:
String msg=intent.getExtras().getString("msg");
Then show the message as :
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.mipmap.app_icon)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle(context.getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);

Categories