How to send email to queue in Magento 1.9? - php

I need to send the emails to the queue "table core_email_queue".
But my code doesnt work.
I dont know why
$emailTemplate = Mage::getModel('core/email_template');
$emailTemplate->load(Mage::getStoreConfig('emailreminder/general/emailreminder_template'));
$emailTemplateVariables = [];
$emailTemplate->setSenderName($email);
$emailTemplate->setSenderEmail($email);
$emailQueue = Mage::getModel('core/email_queue');
$emailTemplate->setQueue($emailQueue)->send($email, $email, $emailTemplateVariables);

Related

How to send custom message before, proxy session send actual message

When Customer replies to proxy service reserved number then proxy hit an OutOfSessionCallbackUrl(if a session is not active).
That URL will come to my code below.
public function response()
{
$to = $_POST['To'];
$from = $_POST['From'];
$from = substr($from, 2);
$body = $_POST['Body'];
$twilio = new Client($this->sid, $this->token);
$response=$this->db->get_where('contact_management as cm
,proxy_service as ps',
array('mobile'=>$from,'company_mobile'=>$to,'sc.sms_template_id<>'=>0))
->row_array();
$number = trim($response['country_code'].$response['mobile_number']);
//Here I'm sending a response
header("content-type:application/json");
?>
{
"uniqueName": "<?php echo rand();?>",
"ttl":"64800",
"mode": "voice-and-message",
"participantIdentifier":"<?php echo $number;?>"
}
<?php
}
This will create a session between SMS sender and returned number(company) and send the message of the sender to the company. I want to send a custom message before Twilio proxy send actual message to the company.
Thanks.
Twilio developer evangelist here.
Currently you are using the out of session callback in order to create a session, but you want to send a message before you forward on the incoming message.
To do this, you won't be able to respond with the JSON to create a session. Instead, you should create the session manually using the session API. Once you have created a session you can then send your initial message by creating an interaction on the participant you want to send the message to. You can then follow up by using the same API to forward the original message. And finally you still need to respond to the webhook. Since you handled all the message sending manually, you can return an empty TwiML <Response/> to signify that you need Twilio to take no further part.
Let me know if that helps at all.
Here Are the complete Description.
I have add Twilio number as reserved in proxy service and set the proxy service OutOfSessionCallbackUrl.When this URL reach my code then the magic happens,
public function response()
{
$to = $_POST['To'];
$from = $_POST['From'];
$twilio = new Client($this->sid, $this->token);
$response=$this->db->get_where('contact_management ,proxy_service,
array('mobile'=>$from,'company_mobile'=>$to))->row_array();
$service_sid=$response['service_sid'];
$session = $twilio->proxy->v1->services($service_sid)->sessions
->create(array("uniqueName" => rand(),"ttl"=>"64800"));
$session_sid = $session->sid;
$participant1 = $twilio->proxy->v1->services($service_sid)
->sessions($session_sid)->participants->create($_POST['From'], // identifier
array("friendlyName" => $response['f_name'],"proxyIdentifier"=>$to));
$from_id = $participant1->proxyIdentifier;
$participant2 = $twilio->proxy->v1->services($service_sid)
->sessions($session_sid)->participants
->create($response['country_code'].$response['mobile_number'], // identifier
array("friendlyName" => $response['first_name']));
$to_id = $participant2->proxyIdentifier;
$to_sid = $participant2->sid;
$body = $response['campaign_name']."\n";
$body .= $_POST['Body'];
$message_interaction = $twilio->proxy->v1->services($service_sid)
->sessions($session_sid)
->participants($to_sid)
->messageInteractions
->create(array("body" => $body));
header("content-type:text/xml");
?>
<Response />
<?php
}

Magento - Mailgun plugin not sending email

I'm using Magento v1.9.1, with a MailGun plugin installed.
Plugin url:
https://www.magentocommerce.com/magento-connect/mailgun-for-email-delivery.html
Here you can see the MailGun plugin on the admin area:
Then I used the following code to send a test email (test_email.php):
<?php
// Invoke the Magento environment
require_once( 'app/Mage.php' );
Mage::app();
//Getting the Store E-Mail Sender Name.
$senderName = Mage::getStoreConfig('trans_email/ident_general/name');
//Getting the Store General E-Mail.
$senderEmail = Mage::getStoreConfig('trans_email/ident_general/email');
$customerEmail = "<personal_email#hidden_on_purpose>";
$text = "Hello, this is a test.";
//Sending E-Mail to Customers.
$mail = Mage::getModel('core/email')
->setToName($senderName)
->setToEmail($customerEmail)
->setBody($text)
->setSubject('Subject :')
->setFromEmail($senderEmail)
->setFromName($senderName)
->setType('html');
try{
//Confimation E-Mail Send
$mail->send();
}
catch(Exception $error)
{
Mage::getSingleton('core/session')->addError($error->getMessage());
return false;
}
?>
Then the email arrives to me but it is not sent via MailGun. I know that because on the header of the received email is the server where the application lives and on the MailGun log the email is not logged.
I think the MailGun plugin is working on the backend admin area only, but it is not getting called when sending an email with Magento.
I also did a test modifying the file:
./app/code/community/FreeLunchLabs/MailGun/Model/Mailgun.php
by adding the line:
die("Send stopped on file: ./app/code/community/FreeLunchLabs/MailGun/Model/Mailgun.php");
Like:
...
public function send($message) {
die("Send stopped on file: ./app/code/community/FreeLunchLabs/MailGun/Model/Mailgun.php");
$domain = $message->getStore()->getConfig('mailgun/general/domain');
$apiKey = $message->getStore()->getConfig('mailgun/general/key');
$files = null;
if(count($message->getAttachments())) {
foreach($message->getAttachments() as $attachment) {
$files[] = $attachment;
}
}
$sendResponse = $this->mailgunRequest('messages', $domain, $apiKey, $message->getMessage(), Zend_Http_Client::POST, false, $files);
if($message->getStore()->getConfig('mailgun/events/store')) {
Mage::getModel('freelunchlabs_mailgun/email')->saveInitialSend($message, $sendResponse);
}
return $sendResponse;
}
...
But when running the file: test_email.php, the stopped message inside the die(...) on the code above doesn't appear.
Any idea on how to solve/debug this?
Ok, after some try/error experiments I found the answer: that MailGun extension applies only to transactional emails as stated on its description. You cannot send custom emails using MailGun straightforward like on my initial code: test_email.php. If you wanna send some custom email using MailGun you should create a template before and then use that template like in the following code where I created the template with id: 1
<?php
// Invoke the Magento environment
require_once( 'app/Mage.php' );
Mage::app();
$templateId = 1;
$receiveName = "<Your Name Here>";
$receiveEmail = "<your email here>";
$storeId = Mage::app()->getStore()->getStoreId();
$emailTemplate = Mage::getModel("core/email_template")->load($templateId);
$vars = array(
"name" => $receiveName,
"email" => $receiveEmail,
"phone" => "+13052491037",
"comment" => "This is my comment: Hello World!"
);
$emailTemplate->getProcessedTemplate($vars);
/*
echo "<pre>\n";
print_r($emailTemplate);
echo "</pre>\n";
die();
//*/
$emailTemplate->setSenderName(Mage::getStoreConfig("trans_email/ident_general/name", $storeId));
$emailTemplate->setSenderEmail(Mage::getStoreConfig("trans_email/ident_general/email", $storeId));
$emailTemplate->send($receiveEmail, $receiveName, $vars);
?>
Hope this helps somebody.

Get transcational email id by name

Does someone know how do I get the id of an email by name set on backend? I have an email created in backend in transactional emails that I want to send it programatically, but the id of it may differ depending on the instance that I'm on (local, live, stage), and I can only provide the same name for it.
I have this:
Mage::getModel('core/email_template')->sendTransactional(
$templateId,
$sender,
$recepientEmail,
$recepientName,
$vars,
$store);
And I need to find out $templateId and I only know that I saved the mail with name "Tests".
You can get email template:
$templateName = “Test”;
$emailTemplate = Mage::getModel('core/email_template')->loadByCode($templateName);
Get id:
$templateId = $emailTemplate->getId();
And then send email on your way:
Mage::getModel('core/email_template')->sendTransactional(
$templateId,
$sender,
$recepientEmail,
$recepientName,
$vars,
$store
);
or use "my" method:
$vars = array('key' => 'value');
$storeId = Mage::app()->getStore()->getStoreId();
$recipientEmail = 'some#email.com';
$recipientName = 'Some Name';
$emailTemplate->setSenderEmail(Mage::getStoreConfig('trans_email/ident_general/email', $storeId));
$emailTemplate->setSenderName(Mage::getStoreConfig('trans_email/ident_general/name', $storeId));
$emailTemplate->send($recipientEmail, $recipientName, $vars);
please check the codes below. any way this is my first answer on stackoverflow.
$templateName = "Tests";
$templateID = Mage::getModel('core/email_template')->loadByCode($templateName)->getId();

How to send Batch messaging in yii using Clickatell SMS gateway

Am using Yii Framework. single and group sent SMS now working fine. but
now I want to sent Batch messaging using Clickatell.
This is single SMS API's link
Yii::app()->sms->send(array('to'=>'407xxxxxxxx', 'message'=>'Hello world!'));
how to send Batch messaging?
pls help me.-:)
$messages = array();
$messages[] = array('to'=>'0001000','message'=>'Hello');
$messages[] = array('to'=>'0002000','message'=>'Hello');
foreach($messages as $message){
Yii::app()->sms->send(array('to'=>$message['to'], 'message'=>$message['message']));
}
Same message to all
$message = "Hello world!";
$to = array();
$to[] = '001000';
$to[] = '200100';
foreach($to as $number){
Yii::app()->sms->send(array('to'=>$number, 'message'=>$message));
}

Error when Sending Mail with Attachments Using PEAR

My page continues to error out (Error 324 - Chrome) when attempting to send e-mails with attachments using PHP's PEAR Mail extension. Although the page error's out - I do receive one of the approximately 800 e-mails. Here's what I'm working with:
function email_statements($type) {
switch($type) {
// Determine the type of statement to be e-mailed
case 'monthly':
// Array holding all unique AP e-mail addresses
$ap_email_addresses = array();
include('../path/to/db/connection/params.php');
// Grab the unique AP e-mail address set to receive statements
$stmt = $mysqli->prepare("SELECT email FROM statements GROUP BY email ORDER BY email ASC");
$stmt->execute();
$stmt->bind_result($ap_email_address);
// Add unique e-mail address to AP E-mail Addresses array
while($row = $stmt->fetch()) $ap_email_addresses[] = $ap_email_address;
$stmt->close();
$mysqli->close();
// Verify we grabbed the e-mail addresses
if(count($ap_email_addresses) == 0) {
// Exit and return error code if unable to grab e-mail addresses
$return_message = 1;
exit;
}
// E-mail addresses grabbed - proceed
else {
// PDF formatted date
date_default_timezone_set('America/New_York');
$formatted_date = date('m_d_Y');
// Now we have the unique e-mail addresses - associate those with the account numbers
include('../path/to/db/connection/params.php');
foreach($ap_email_addresses as $email_address) {
$file_names = array();
$stmt = $mysqli->prepare("SELECT customer_number FROM statements WHERE email = ?");
$stmt->bind_param("s", $email_address);
$stmt->execute();
$stmt->bind_result($ap_account_number);
// Constructs the name of the statement (PDF) file to be sent
while($output = $stmt->fetch()) $file_names[] = $ap_account_number . '_' . $formatted_date . '.pdf';
// Send e-mails
include('Mail.php');
include('Mail/mime.php');
// Include SMTP authentication parameters
include('../path/to/email/info.php');
// Set the e-mail recipients
$recipients = 'example#example.com';
// Set the e-mail subject
$subject = 'Monthly Account Statement';
// Create the e-mail body
$html =
'<html>
<body>
<p>Test E-mail</p>
</body>
</html>';
// Construct the message headers
$headers = array(
'From' => $from,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8',
'MIME-Version' => '1.0'
);
$mimeparams = array();
$mimeparams['text_encoding'] = '8bit';
$mimeparams['text_charset'] = 'UTF-8';
$mimeparams['html_charset'] = 'UTF-8';
$mimeparams['head_charset'] = 'UTF-8';
// Create a new instance
$mime = new Mail_mime();
// Specify the e-mail body
$mime->setHTMLBody($html);
// Attach the statements (PDF)
foreach($file_names as $attached_file) {
$file = '../path/to/the/pdf/file/' . $attached_file;
$file_name = $attached_file;
$content_type = "Application/pdf";
$mime->addAttachment ($file, $content_type, $file_name, 1);
}
// Create the body
$body = $mime->get($mimeparams);
// Add the headers
$headers = $mime->headers($headers);
// Create SMTP connect array to be passed
$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
// Send the message
$mail = $smtp->send($recipients, $headers, $body);
if(PEAR::isError($mail)) echo 'Error';
else echo 'Sent';
// Close this account and cycle through the rest
$stmt->close();
}
$mysqli->close();
}
break;
}
}
Now I thought maybe I wasn't giving the script enough time to execute - so I set it ridiculously high set_time_limit(99999999) to ensure it had plenty of time, although it normally times out within 10-15 seconds. So basically it works like this, I have an internal DB that stores customer account numbers and e-mail addresses. Accounts can have the same e-mail address (It's sent to their company's AP department) - aka one e-mail address receives statements for multiple branches. From their each statement is already constructed with the format being ACCOUNTNUMBER_MM_DD_YYYY.pdf.
So I'm simply trying to have a short message in the body, and attach the monthly statements. Again, not sure why it's failing, and even though the script halts, I do receive ONE of the e-mails (I'm sending them all to myself at the moment just to test). Can anyone see where I may have an issue?
I discovered the issue. As of PHP 5.0+ you cannot have multiple instances of the same include file - aka Mail.php was included as it looped. Once it was moved outside of the loop, the issue was resolved.

Categories