PEAR Mail, Mail_Mime and headers() overwrite - email

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.

Related

How can i recieve pushed message from google pubsub

I Have created new topic and new subscription and set delivery type: push and set end point URL :
index.php :
<?php
print_r($_POST);
$data = json_encode($_POST);
print_R($data);
$fp = fopen('data.txt', 'a+');
fwrite($fp, $data);
fclose($fp);
?>
When publish message i want to process the data from this end point as an example save data to file.
the file is created but with empty array [].
any issue in my php code, does the data store in $_POST or i need to use another way.
To fetch Pub/Sub messages, you need to use the Google Pub/Sub library. Given that you've set your subscription endpoint to your URL, the code should look like something similar to this:
use Google\Cloud\PubSub\PubSubClient;
$projectId = "YOUR-PROJECT-ID";
$subscriptionName = "YOUR-SUBSCRIPTION-NAME";
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
$subscription = $pubsub->subscription($subscriptionName);
$pullMessages = [];
foreach ($subscription->pull(['returnImmediately' => true]) as $pullMessage) {
$pullMessages[] = $pullMessage;
$msg = $pullMessage->data();
$fp = fopen('data.txt', 'a+');
fwrite($fp, $msg);
fclose($fp);
}
// acknowledge PULL messages
if ($pullMessages) {
$subscription->acknowledgeBatch($pullMessages);
}
You can find an example here. As well as a more in-detail explanation here.

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.

Magento mailing feature in custom script

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.

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>"))));
}