Magento mailing feature in custom script - email

I have created a custom script to import a bulk number of customers to magento database. What client needed is for each 100 customers import they needed a mail about whats going on and status of the importing.
So how can i use the magento mailing functionality so that i can create a template to send mail as like magento does. Please help me

I think you're looking for something along the following lines:
$store_id = $this->getStoreId();
$template = "import_script_email_template_name";
$from = Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $store_id);
$to = array( "name" => "Nick", "email" => "the#email.address" );
$template_variables = array(
"var1" => "somevalue",
"var2" => "someothervalue"
);
$mail = Mage::getModel("core/email_template");
$mail->setDesignConfig( array( "area" => "frontend", "store" => $store_id ))
->sendTransactional(
$template_name,
$from,
$to["email"],
$to["name"],
$template_variables
);
Note: This was lifted from Mage_Sales_Model_Order::sendNewOrderEmail() and hasn't been tested, but it should be more than enough to get you started. Treat it as pseudo-code :)

If you are just doing this from an import script, the PHP mail function should be more than sufficient.

Also can do the mailing functionality of ZEND
Here is the code
$mail_body = "<h3> These are ordered by you in the event - '".$customer_event."' </h3> <br/>". $email_body;
$to_email = $email;
$to_name = $customer_name;
$subject = 'Orders';
$Body = $body;
$sender_email = "info#mail.com";
$sender_name = "mail";
$html = new Zend_View();
$html->setScriptPath('app/locale/en_US/template/email/');
$html->assign('customer_name', $customer_name);
$html->assign('email', $to_email);
$html->assign('password', $password);
$html->assign('site_url', Mage::getUrl(""));
$html->assign('site_skin_url', Mage::getDesign()->getSkinUrl("images/"));
$html->assign('site_order_url', Mage::getUrl("").'Event.php?id='.$id.'&cart_id='.$cart_id);
$html->assign('site_name', 'Winecellarage');
$html->assign('site_data', $mail_body);
$Body_text= $html->render($template);
$mail = new Zend_Mail('utf-8');
$mail->setBodyHtml($Body_text);
$mail->setFrom($sender_email, $sender_name);
$mail->addTo($to_email, $to_name);
//$mail->addCc($cc, $ccname);
//$mail->addBCc($bcc, $bccname);
$mail->setSubject($subject);
try {
if($mail->send())
{
$msg .= "<p>Mail sent successfully to '$to_email' </p>";
}
}
catch(Exception $ex) {
$err .= '<p>'.$error_msg = $ex->getMessage()."</p>";
}
This one is working exactly what i wanted. So may be useful to some one.

Related

Newbie on Fb messenger Sender_action function

I am under a learning process in chatbot, and kinda new to coding overall ( learning by doing right? )
Trying to execute a messenger function so our chatbot gets the little "writing" bubble for x amount of time before it sends a template. = sender_action_typing_on.
I have tried sleep, await, wait, and so on but the code doesn´t seem to be executed, but the template still shows after the time I chose.
The json is also correct by the documentation from Facebook, and if it get´s executed alone it runs for 20 sek before a timeout.
Code:
if ( $response == "")
{
$jsonData = '{"recipient":{"id":"' . $sender . '"},"message":{"text":"' . $message_to_reply.'"}}';
$jsonDataEncoded = $jsonData;
}
else
if ( $response == "123456")
{
$sender_action_typing_on = '{
"recipient":{
"id":"<PSID>"
},
"sender_action":"Typing_on"
}';
$sender_action_typing_on = str_replace("<PSID>", $sender, $sender_action_typing_on);
$jsonDataEncoded = $sender_action_typing_on;
$velkommenTemplateJSON = str_replace("<PSID>", $sender, $velkommenTemplateJSON);
$jsonDataEncoded = $velkommenTemplateJSON;
}
I have now fixed this issue, this may be very self-explaining for many but for the "lost soul" looking for answers u can see the way i dealed with the problem here:
First i created a new function:
function sendToMessenger($access_token, $sender, $sender_actiontemplateJSON)
{
$content = str_replace("<PSID>", $sender, $sender_actiontemplateJSON);
$opts = array(
'http'=>array(
'method'=>"POST",
'header' => "Content-Type: application/json",
'content' => $content
)
);
$context = stream_context_create($opts);
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=' . $access_token;
// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
return $file;
Then i rearranged the way i´m sending template since the template got sent at det end of my code "Sender_action" would always be overwritten, Now with the "SendToMessenger" Function it gets sent right away.
else
if ( $response == "123456")
{
sendToMessenger($access_token, $sender, $sender_actiontemplateJSON);
sleep(1);
sendToMessenger($access_token, $sender, $velkommenTemplateJSON);
}
Now it works like a charm!

Laravel - How to send email to all users

Im struggling to make a code that sends email to my subscribed users. I want to pass body to view according to users default language, can anyone help me ?
My code:
if($newsletter->save())
{
//get users to send to
$users = User::where('newsletter', '=', '1')->Where('activated', '=', '1')->get();
//Send to all users subscribed
foreach($users as $user)
{
//set info according to user default lang
if($user->default_lang == 'pt')
{
$body = $newsletter_pt;
$subject = Input::get('subject_PT');
}
elseif($user->default_lang == 'de')
{
$body = $newsletter_de;
Input::get('subject_DE');
}
$data = array(
'body' => $body,
'subject' => $subject
);
$from_name = Input::get('from_name');
$from_email = Input::get('from_email');
//QUEUE The Newsletters to send
Mail::queue('admin.newsletters.template1', $data, function($message) use ($user, $subject, $from_name, $from_email)
{
$message->from($from_email, $from_name);
$message->bcc($user->email, $user->name);
$message->subject($subject);
});
} //end foreach
return Redirect::To('admin/newsletters')->with('message', array("1" => "Newsletter enviada com sucesso !"));
}
Thanks a lot ;)
Ensure that the $data array has the information you expect to pass into the view before you call Mail::queue(). It should pass both a $body and $subject variable to your view.
You might also try using Mail::send() instead of Mail::queue() and see if it makes a difference (if you're not using a queueing system). Sometimes the queue() method can trip up when serializing Eloquent models, so if $newsletter_pt or $newsletter_de are Eloquent models they might not make it to the view intact.

PEAR Mail, Mail_Mime and headers() overwrite

I'm currently working on a reminder PHP Script which will be called via Cronjob once a day in order to inform customers about smth.
Therefore I'm using the PEAR Mail function, combined with Mail_Mime. Firstly the script searches for users in a mysql database. If $num_rows > 0, it's creating a new Mail object and a new Mail_mime object (the code encluded in this posts starts at this point). The problem now appears in the while-loop.
To be exact: The problem is
$mime->headers($headers, true);
As the doc. states, the second argument should overwrite the old headers. However all outgoing mails are sent with the header ($header['To']) from the first user.
I'm really going crazy about this thing... any suggestions?
(Note: However it's sending the correct headers when calling $mime = new Mail_mime() for each user - but it should work with calling it only once and then overwriting the old headers)
Code:
// sql query and if num_rows > 0 ....
require_once('/usr/local/lib/php/Mail.php');
require_once('/usr/local/lib/php/Mail/mime.php');
ob_start();
require_once($inclPath.'/email/head.php');
$head = ob_get_clean();
ob_start();
require_once($inclPath.'/email/foot.php');
$foot = ob_get_clean();
$XY['mail']['params']['driver'] = 'smtp';
$XY['mail']['params']['host'] = 'smtp.XY.at';
$XY['mail']['params']['port'] = 25;
$mail =& Mail::factory('smtp', $XY['mail']['params']);
$headers = array();
$headers['From'] = 'XY <service#XY.at>';
$headers['Subject'] = '=?UTF-8?B?'.base64_encode('Subject').'?=';
$headers['Reply-To'] = 'XY <service#XY.at>';
ob_start();
require_once($inclPath.'/email/templates/files.mail.require-review.php');
$template = ob_get_clean();
$crfl = "\n";
$mime = new Mail_mime($crfl);
while($row = $r->fetch_assoc()){
$html = $head . $template . $foot;
$mime->setHTMLBody($html);
#$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <'.$row['email'].'>'; // for testing purpose i'm sending all mails to webmaster#XY.at
$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <webmaster#XY.at>';
$headers['To'] = $to; // Sets to in headers to a new
$body = $mime->get(array('head_charset' => 'UTF-8', 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8'));
$hdrs = $mime->headers($headers, true); // although the second parameters says true, the second, thrid, ... mail still includes the To-header form the first user
$sent = $mail->send($to, $hdrs, $body);
if (PEAR::isError($sent)) {
errlog('error while sending to user_id: '.$row['id']); // personal error function
} else {
// Write log file
}
}
There is no reason to keep the old object and not creating a new one.
Use OOP properly and create new objects - you do not know how they work internally.

Zend Mail and encodings, content-transfer etc. - Unified?

Is there any class in the Zend Framework that allows me to easily read emails?
The Zend_Mail class does allow me to easy get headers, subject and the content body. But transferring everything to UTF-8 and human-readable format is still a pain.
Or am I doing something wrong? As far as I can tell, Zend Framework does not allow me to easily get UTF-8 strings that I can just use, I still have to do some post-processing. Right?
The key thing is that you need to iterate over the parts within the Message and find the text. Once you have it, then you can use quoted_printable_decode to get the text itself in a useful way.
This is some rough and ready code that reads IMAP email boxes with Zend_Mail:
<?php
$mail = new Zend_Mail_Storage_Imap(array(
'host' => EMAIL_ACCOUNT_HOST,
'user' => EMAIL_ACCOUNT_USERNAME,
'password' => EMAIL_ACCOUNT_PASSWORD,
));
echo (int)$mail->countMessages() . " messages found\n";
foreach ($mail as $message) {
$from = $message->getHeader('from');
$subject = trim($message->subject);
$to = trim($message->to);
$body = getBody($message);
// do something with message here
}
function getBody(Zend_Mail_Message $message)
{
// find body
$part = $message;
$isText = true;
while ($part->isMultipart()) {
$foundPart = false;
$iterator = new RecursiveIteratorIterator($message);
foreach ($iterator as $part) {
// this detection code is a bit rough and ready!
if (!$foundPart) {
if (strtok($part->contentType, ';') == 'text/html') {
$foundPart = $part;
$isText = false;
break;
} else if (strtok($part->contentType, ';') == 'text/plain') {
$foundPart = $part;
$isText = true;
break;
}
}
}
if($foundPart) {
$part = $foundPart;
break;
}
}
$body = quoted_printable_decode($part->getContent());
}

Get email from Drupal CCK field and send mail using drupal_mail

Hi I'm using the Jobsearch module to build a recruitment site in Drupal 6. By default it sends applications to the email address of the user who posted the job. My problem is all jobs will be posted by a site admin - I need the applications to be sent to BOTH this admin and an email address specified in a CCK field (it's a CCK Email field to be precise).
Trying to extract the CCK field's value and use it in addition to the job poster's (admin's) email and send using drupal_mail but failing - email not sent to the custom CCK email field.
This is what I have attempted (and permutations of), from the Jobsearch module job.module file:
/**
* Implementation of hook_mail().
*/
function job_mail($key, &$message, $params) {
$result = theme('job_mail', $params['job_node'], $params['job_user'], $params['resume_node'], $params['resume_user']);
$message['subject'] = $result['subject'];
$message['body'] = $result['body'];
}
function job_send_email($job_nid, $resume_nid) {
global $user;
$params['job_node'] = $job_node = node_load(array('nid' => $job_nid));
$params['job_user'] = $job_user = user_load(array('uid' => $job_node->uid));
$params['resume_node'] = $resume_node = node_load(array('nid' => $resume_nid));
$params['resume_user'] = $resume_user = user_load(array('uid' => $resume_node->uid));
$from = $resume_user->mail;
$language = user_preferred_language($user);
$contactEmail = node_load($field_contact_email[0][nid]);
$to = "$job_user->mail, $contactEmail";
drupal_mail('job', 'job_apply', $to, $language, $params, $from);
watchdog('job', t("%name applied for job $job_node->nid.",
array('%name' => theme('placeholder', $resume_user->name . " <$from>"))));
}
It seems like it should be a simple thing to do, but I'm struggling!
Cracked it I think :) This sends to both the poster/user's email and one specified in my CCK email field.
function job_send_email($job_nid, $resume_nid) {
global $user;
$params['job_node'] = $job_node = node_load(array('nid' => $job_nid));
$params['job_user'] = $job_user = user_load(array('uid' => $job_node->uid));
$params['resume_node'] = $resume_node = node_load(array('nid' => $resume_nid));
$params['resume_user'] = $resume_user = user_load(array('uid' => $resume_node->uid));
$contactEmail = $job_node->field_contact_email[0]['email'];
$from = $resume_user->mail;
$language = user_preferred_language($user);
$to = "$job_user->mail, $contactEmail";
drupal_mail('job', 'job_apply', $to, $language, $params, $from);
watchdog('job', t("%name applied for job $job_node->nid.",
array('%name' => theme('placeholder', $resume_user->name . " <$from>"))));
}