Attachment sent as encoded text - php

I am trying to forward the attachment sin my email to another account automatically using this script and swift mailer library. Thing seems to be working for certain extent but the attachments are sent as encoded text. I wanted to send the attachments as it is. I am new to php and unable to figure out where the issue is. Please help me.
<?php
require_once 'lib/swift_required.php';
$hostname = '{imap.asd.com:993/imap/ssl}INBOX';
$username = 'abc#as.com';
$password = 'ppwppw';
/* try to connect */
$connection = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' . imap_last_error());
ini_set('memory_limit', '256M');
function Message_Parse($id)
{
global $connection;
if (is_resource($connection))
{
$result = array
(
'text' => null,
'html' => null,
'attachments' => array(),
);
$structure = imap_fetchstructure($connection, $id, FT_UID);
if (is_array($structure) && array_key_exists('parts', $structure))
{
foreach ($structure->parts as $key => $part)
{
if (($part->type >= 2) || (($part->ifdisposition == 1) && ($part->disposition == 'ATTACHMENT')))
{
$filename = null;
if ($part->ifparameters == 1)
{
$total_parameters = count($part->parameters);
for ($i = 0; $i < $total_parameters; $i++)
{
if (($part->parameters[$i]->attribute == 'NAME') || ($part->parameters[$i]->attribute == 'FILENAME'))
{
$filename = $part->parameters[$i]->value;
break;
}
}
if (is_null($filename))
{
if ($part->ifdparameters == 1)
{
$total_dparameters = count($part->dparameters);
for ($i = 0; $i < $total_dparameters; $i++)
{
if (($part->dparameters[$i]->attribute == 'NAME') || ($part->dparameters[$i]->attribute == 'FILENAME'))
{
$filename = $part->dparameters[$i]->value;
break;
}
}
}
}
}
$result['attachments'][] = array
(
'filename' => $filename,
'content' => str_replace(array("\r", "\n"), '', trim(imap_fetchbody($connection, $id, ($key + 1), FT_UID))),
);
}
else
{
if ($part->subtype == 'PLAIN')
{
$result['text'] = imap_fetchbody($connection, $id, ($key + 1), FT_UID);
}
else if ($part->subtype == 'HTML')
{
$result['html'] = imap_fetchbody($connection, $id, ($key + 1), FT_UID);
}
else
{
foreach ($part->parts as $alternative_key => $alternative_part)
{
if ($alternative_part->subtype == 'PLAIN')
{
echo '<h2>' . $alternative_part->subtype . ' ' . $alternative_part->encoding . '</h2>';
$result['text'] = imap_fetchbody($connection, $id, ($key + 1) . '.' . ($alternative_key + 1), FT_UID);
}
else if ($alternative_part->subtype == 'HTML')
{
echo '<h2>' . $alternative_part->subtype . ' ' . $alternative_part->encoding . '</h2>';
$result['html'] = imap_fetchbody($connection, $id, ($key + 1) . '.' . ($alternative_key + 1), FT_UID);
}
}
}
}
}
}
else
{
$result['text'] = imap_body($connection, $id, FT_UID);
}
$result['text'] = imap_qprint($result['text']);
$result['html'] = imap_qprint(imap_8bit($result['html']));
return $result;
}
return false;
}
$emails = imap_search($connection,'ALL');
rsort($emails);
foreach($emails as $email_number) {
$result = Message_Parse($email_number);
$data = $result['attachments'];
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$attachment = Swift_Attachment::newInstance($data, 'recorded.mp3', 'audio/mp3');
$message = Swift_Message::newInstance('new messaeg')
->setFrom(array('aaa#bbb.com' => 'name'))
->setTo(array('aaa#ccc.com'))
->setBody($result['text'], 'Here is the message itself')
->attach($attachment);
$result1 = $mailer->send($message);
?>

What is $data after $data = $result['attachments'];? Think it is an attachment container object of some sort. You might need to dig in a little more to get the right property (the attachment) to then reattach it. See: http://dev.kayako.com/browse/SWIFT-2341

This doesn't look right:
$data = $result['attachments'];
...
$attachment = Swift_Attachment::newInstance($data, 'recorded.mp3', 'audio/mp3');
When you create an attachment with this method, I think $data is supposed to be a string that contains the contents of the attachment. But $result['attachments'] is an array of all the attachments in the original message. It seems like you should be looping through these attachments, creating a separate Swift_Attachment for each of them. You also should save the filename and content type from the original message, not hard-code them to recorded.mp3 and audio/mp3 (unless the application ensures that this is all there will be).
As for them being encoded -- MP3's aren't plain text, so what do you expect?

Related

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (Drupal + PHPexcel)

<?php
function import_sales_request(){
$hostname = '****';
$username = '****';
$password = '*****';
global $base_url;
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox, 'UNSEEN', SE_UID);
$emailDates = array();
if ($emails) {
//$count = 1;
rsort($emails);
foreach ($emails as $email_number) {
$overview = imap_fetch_overview($inbox, $email_number, FT_UID);
$message = imap_fetchbody($inbox, $email_number, 2, FT_UID);
$structure = imap_fetchstructure($inbox, $email_number, FT_UID);
$emailDates[$email_number] = $overview[0]->date;
$message_header = imap_fetchheader($inbox, $email_number, 1);
$message_body = imap_fetchbody($inbox, $email_number, "1.1", FT_UID);
//file_put_contents(drupal_get_path('module', 'pricecal') . "/mail/" . $email_number . ".htm", nl2br($message_header) . $message_body);
$attachments = array();
if (isset($structure->parts) && count($structure->parts)) {
for ($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array('is_attachment' => false, 'filename' => '', 'name' => '', 'attachment' => '');
if ($structure->parts[$i]->ifdparameters) {
foreach ($structure->parts[$i]->dparameters as $object) {
if (strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if ($structure->parts[$i]->ifparameters) {
foreach ($structure->parts[$i]->parameters as $object) {
if (strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if ($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i + 1, FT_UID);
if ($structure->parts[$i]->encoding == 3) {
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
} elseif ($structure->parts[$i]->encoding == 4) {
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
foreach ($attachments as $attachment) {
if ($attachment['is_attachment'] == 1) {
$filename = $attachment['name'];
$fileinfo = pathinfo($filename);
if (in_array($fileinfo['extension'], array('csv', 'xls', 'xlsx'))) {
if (empty($filename))
$filename = $attachment['filename'];
if (empty($filename))
$filename = time() . ".dat";
$fp = fopen(drupal_get_path('module', 'pricecal') . "/mail/".$email_number."-".clean($overview[0]->from). "-" . clean($filename), "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}
}
//if($count++ >= $max_emails) break;
imap_setflag_full($inbox, $email_number, "\\Seen \\Flagged", ST_UID);
}
}
imap_close($inbox);
import_sales_request_into_database($emailDates);
return true;
}
/*
* Insert new and revised request into database
*/
function import_sales_request_into_database($emailDates = '', $flag = false) {
global $user;
global $base_url;
include_once(drupal_get_path('module', 'pricecal') . '/excel/Classes/PHPExcel/IOFactory.php');
$filelist = file_scan_directory(drupal_get_path('module', 'pricecal') . '/mail', '/^.*\.(csv|CSV|xls|XLS|xlsx|XLSX)$/');
if (!empty($filelist)) {
foreach ($filelist as $list) {
$objPHPExcel = PHPExcel_IOFactory::load($list->uri);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$resultArray = array();
$part_no = array();
$start_part_no = 0;
$temp = 0;
$ctoarray = array();
$transaction = db_transaction(); //start database transaction
try {
/*
* Prepare array structure to insert as a new or revised request
* $flag = true - it is not importing, it is from home page browse button
*/
$resultArray['requester_name'] = empty($sheetData[1]['B']) ? '' : $sheetData[1]['B'];
$resultArray['requester_email'] = empty($sheetData[2]['B']) ? '' : $sheetData[2]['B'];
$resultArray['request_number'] = empty($sheetData[3]['B']) ? '' : $sheetData[3]['B'];
$resultArray['customer_name'] = empty($sheetData[4]['B']) ? '' : $sheetData[4]['B'];
$resultArray['segment'] = empty($sheetData[5]['B']) ? '' : $sheetData[5]['B'];
$resultArray['dmu_cmr'] = empty($sheetData[6]['B']) ? '' : $sheetData[6]['B'];
$resultArray['cyborg_no'] = empty($sheetData[7]['B']) ? '' : $sheetData[7]['B'];
$resultArray['duty_type'] = empty($sheetData[8]['B']) ? '' : $sheetData[8]['B'];
$resultArray['country_code'] = empty($sheetData[9]['B']) ? '' : $sheetData[9]['B'];
$resultArray['billing_type'] = empty($sheetData[10]['B']) ? '' : $sheetData[10]['B'];
$resultArray['tier_1_partner'] = empty($sheetData[11]['B']) ? '' : $sheetData[11]['B'];
$resultArray['tier_2_partner'] = empty($sheetData[12]['B']) ? '' : $sheetData[12]['B'];
$resultArray['requested_tp'] = empty($sheetData[13]['B']) ? '' : (float)str_replace(',', '', $sheetData[13]['B']);
$resultArray['deal_justification'] = empty($sheetData[14]['B']) ? '' : $sheetData[14]['B'];
$cto_counter = 0 ;
$ctocounterarray = array();
if (!empty($sheetData)) {
foreach ($sheetData as $key => $value) {
if (!empty($resultArray)) {
if ($value['B'] == 'Part Number*') {
$start_part_no = $key;
}
if ($start_part_no != 0 && $key > $start_part_no && $value['B'] != '') {
if (($value['A'] == 'CTO' || $value['A'] == 'Regular') && $temp == 0) {
if($value['A'] == 'CTO'){
$part_no[] = array($value['B'] => array($value['C'], 'primary-cto'));
$cto_counter++;
$ctocounterarray[] = $value['B'];
}else{
$part_no[] = array($value['B'] => array($value['C'], 'primary'));
}
}
if ($value['A'] == 'Bundle-Base' && trim($value['B']) != "" && !empty($value['B'])) {
$temp = 1;
$new_part_number = $value['B'];
}
if ($temp) {
if($value['A'] == "Bundle-Remove"){
$value['C'] = -1 * abs($value['C']);
}
$part_no[] = array($value['B'] => array($value['C'], $value['A']));
$ctoarray[$new_part_number][] = array($value['B'] => array($value['C'], $value['A']));
}
if ($value['A'] == 'CTO' && $temp == 1 && in_array($value['B'], $ctocounterarray)) {
$temp = 0;
$cto_counter--;
}
}
$resultArray['part_no'] = $part_no;
}
}
}
$continue_flag = true;
if($cto_counter !== 0){
$transaction->rollback();
drupal_set_message(t($list->filename . ' import failed' . PHP_EOL), 'error');
import_sales_request_logfile($list->filename, 0,$resultArray['requester_email'],$resultArray['requester_name']);
$continue_flag = false;
$mail_id = ($flag) ? 0 : strstr($list->filename, '-', true); //split email id
}
$newRequest = '';
$quotationSummary = '';
$quotationLineItems = array();
$mail_id = ($flag) ? 0 : strstr($list->filename, '-', true); //split email id
$date = date("Y-m-d H:i:s"); //insert current date time in database
$email_date = (isset($emailDates) && isset($emailDates[$mail_id]) && array_key_exists($mail_id, $emailDates)) ? date("Y-m-d H:i:s", strtotime($emailDates[$mail_id])) : $date;
if (!$flag) {
$result = db_select('quotation_request', 'qr')->fields('qr', array('email_number'))->condition('email_number', $mail_id, '=')->execute()->fetchAssoc();
if (!empty($result)) {
drupal_set_message(t($list->filename . ' already imported.' . PHP_EOL), 'warning');
//import_sales_request_logfile($list->filename, 2);
$continue_flag = false;
}
}
$request_type = 'new';
if ($continue_flag && !empty($resultArray)) {
$request_number = '';
if (empty($resultArray['request_number'])) {
$request_number = import_sales_request_number(); //if the request is new
} else {
$revision = '';
$revise_request_number = array(trim($resultArray['request_number']),trim($resultArray['request_number']).'_R1',trim($resultArray['request_number']).'_R2',trim($resultArray['request_number']).'_R3',trim($resultArray['request_number']).'_R4',trim($resultArray['request_number']).'_R5',trim($resultArray['request_number']).'_R6',trim($resultArray['request_number']).'_R7',trim($resultArray['request_number']).'_R8',trim($resultArray['request_number']).'_R19',trim($resultArray['request_number']).'_R10',trim($resultArray['request_number']).'_R11',trim($resultArray['request_number']).'_R12',trim($resultArray['request_number']).'_R13',trim($resultArray['request_number']).'_R14',trim($resultArray['request_number']).'_R15',trim($resultArray['request_number']).'_R16',trim($resultArray['request_number']).'_R17');
$result = db_select('quotation_request', 'qr')->fields('qr', array('request_number'))->condition('request_number',$revise_request_number , 'IN')->execute();
$revision = $result->rowCount();
if (!empty($revision) && $revision > 0) {
$request_number = $resultArray['request_number'] . '_R' . $revision;
$request_type = 'revise';
} else {
drupal_set_message(t($list->filename . ' has invalid request number.' . PHP_EOL), 'warning');
import_sales_request_logfile($list->filename, 3,$resultArray['requester_email'],$resultArray['requester_name']);
$continue_flag = false;
}
}
/*
* If all OK then it will create a new or revised request in database
*/
if ($continue_flag) {
/*
* $newRequest - will have inserted request number
*/
try {
$newRequest = db_insert('quotation_request')->fields(array('email_number' => $mail_id, 'request_number' => $request_number,'request_type'=>$request_type, 'requester_name' => $resultArray['requester_name'], 'requester_email' => $resultArray['requester_email'], 'customer_name' => $resultArray['customer_name'], 'duty_type' => $resultArray['duty_type'], 'billing_type' => $resultArray['billing_type'], 'segment' => $resultArray['segment'],'request_file' => $list->filename, 'request_date_time' => $email_date, 'dmu_cmr' => $resultArray['dmu_cmr'], 'cyborg_no' => $resultArray['cyborg_no'], 'country_code' => $resultArray['country_code'], 'tier_1_partner' => $resultArray['tier_1_partner'], 'tier_2_partner' => $resultArray['tier_2_partner'], 'requested_tp' => $resultArray['requested_tp'], 'deal_justification' => $resultArray['deal_justification'], 'status' => 'generate quotation', 'created' => $date, 'uid' => $user->uid))->execute();
} catch (PDOException $e) {
drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}
if (!empty($newRequest)) {
try {
$quotationSummary = db_insert('quotation_summary')->fields(array('quotation_request_id' => $newRequest, 'created' => $date, 'uid' => $user->uid))->execute();
} catch (PDOException $e) {
drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}
if (!empty($quotationSummary) && !empty($resultArray['part_no'])) {
$base_part_no_id = 0;
foreach ($resultArray['part_no'] as $key => $value) {
$part_no = key($value);
$quantity = (isset($value[$part_no][0])) ? $value[$part_no][0] : 0;
$part_no_behaviour = (isset($value[$part_no][1])) ? $value[$part_no][1] : 'primary';
$query = db_select('cost_tape', 'ct')->fields('ct', array('cost_tape_id'))->fields('ctp', array('bmc_price'))->condition('ct.part_number', $part_no);
$query->leftJoin('cost_tape_price', 'ctp', 'ct.cost_tape_id=ctp.cost_tape_id');
$query->orderBy('ctp.created', 'DESC')->range(0, 1);
$resultArrayAssoc = $query->execute()->fetchAll();
if (count($resultArrayAssoc) > 0) {
foreach ($resultArrayAssoc as $node) {
$cost_tape_id = $node->cost_tape_id;
$bmc_price = $node->bmc_price;
$not_found_part_number = "";
}
} else {
$not_found_part_number = $part_no;
$cost_tape_id = null;
$bmc_price = 0.0;
}
if($part_no_behaviour == 'CTO' || $part_no_behaviour == 'primary-cto'){
$not_found_part_number = $part_no;
$not_found_part_desc = "Server";
$cost_tape_id = null;
}else{
$not_found_part_desc = "";
}
try {
$quotationLineItem = db_insert('quotation_lineitems')->fields(array('quotation_request_id' => $newRequest, 'quotation_summary_id' => $quotationSummary, 'cost_tape_id' => $cost_tape_id, 'not_found_part_no' => $not_found_part_number, 'not_found_desc' => $not_found_part_desc, 'part_behavior' => $part_no_behaviour, 'ref_id' => $base_part_no_id, 'bmc_price' => $bmc_price, 'qty' => $quantity, 'created' => $date, 'uid' => $user->uid))->execute();
$quotationLineItems[] = $quotationLineItem;
if ($part_no_behaviour == 'Bundle-Base' && isset($quotationLineItem)) {
$base_part_no_id = $quotationLineItem;
// $quotationLineItems[] = $quotationLineItem;
$num_updated = db_update('quotation_lineitems') // Table name no longer needs {}
->fields(array('ref_id' => $base_part_no_id))
->condition('quotation_lineitems_id', $base_part_no_id, '=')
->execute();
}
if ($part_no_behaviour == 'CTO' && $base_part_no_id != 0) {
$base_part_no_id = 0;
}
} catch (PDOException $e) {
drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}
}
}
}
}
}
if ($continue_flag && $newRequest && $quotationSummary && !empty($quotationLineItems)) {
drupal_set_message(t($list->filename . ' imported successfully' . PHP_EOL));
import_sales_request_logfile($list->filename, 1);
$requester_name = $resultArray['requester_name'];
$requester_email_id = $resultArray['requester_email'];
$params = array(
'subject' => "Price quote request has been received successfully. Customer Name :- ".$resultArray['customer_name']. " Request No :- ".$request_number,
'body' => "<p>Hi ".$requester_name.",<br/></p>
<p>Thanks for your email. DCG Pricing team will work on your price quote request and will shortly share the quotation with you.</p>
<p>Your request number is ".$request_number.".</p>
<p>Customer Name : ".$resultArray['customer_name'].".</p>
<p>
<strong>Attachment: </strong><a href='" . $base_url . "/sites/all/modules/pricecal/tmp/" . $list->filename . "'>Click here</a><br/>
</p>
<p>The dcgpricing#lenovo.com mailbox is dedicated to handle only price quote requests. For any other queries, please reach out to respective pricers.</p>
<p>*** This is a system generated email, please do not reply to this email ***</p>
<p>Thanks,<p/><p>DCG Pricing Team</p>",
);
drupal_mail('pricecal', 'success_sales_request', $resultArray['requester_email'], language_default(), $params);
$customer_name = $resultArray['customer_name'];
$params = array(
'subject' => "New price quote request received",
'body' => "<p>Hi Team,<br/></p>
<p>The DCG pricing tool has successfully uploaded a price quote input request and is now available for your working.</p>
<ul>
<li>Request Number : ".$request_number."</li>
<li>Customer name : ".$customer_name."</li>
<li>Requestor name : ".$requester_name."</li>
<li>Requestor email id : ".$requester_email_id."</li>
<li>Deal justification : ".$resultArray['deal_justification']."</li>
</ul>
<p>
<strong>Attachment: </strong><a href='" . $base_url . "/sites/all/modules/pricecal/tmp/" . $list->filename . "'>Click here</a><br/>
</p>
<p>*** This is a system generated email, please do not reply to this email ***</p>
<p>Thanks,<p/><p>DCG Pricing Team</p>",
);
//drupal_mail('pricecal', 'import_success_email', 'chintan.p#blueoceanmi.com', language_default(), $params);
} else if ($continue_flag) {
$transaction->rollback();
//drupal_set_message(t($list->filename . ' import failed' . PHP_EOL), 'error');
import_sales_request_logfile($list->filename, 0, $resultArray['requester_email'],$resultArray['requester_name']);
}
} catch (Exception $e) {
$transaction->rollback();
drupal_set_message(t($list->filename . ' import failed' . PHP_EOL), 'error');
import_sales_request_logfile($list->filename, 0, $resultArray['requester_email'],$resultArray['requester_name']);
}
rename($list->uri, drupal_get_path('module', 'pricecal') . '/tmp/' . $list->filename);
}
} else {
drupal_set_message(t('No email founds.' . PHP_EOL), 'warning'); //if no email found with unread status
}
return true;
}
/*
* Create new request number and check weather request number already exists
*/
function import_sales_request_number($length = 6) {
$selectPartId = db_query("select count(request_number) as request_number from quotation_request")->fetchAssoc();
if(empty($selectPartId['request_number'])){
$token = 101;
}else{
$token = $selectPartId['request_number'] + 101;
}
return $token;
}
function import_sales_request_logfile($filename = '', $update = 0,$requester_emailId = '',$requesterName = '') {
global $base_url;
$log_file_path = drupal_get_path('module', 'pricecal') . '/logs/' . date('Y-M-d') . '.dat';
$msg = ($update) ? $filename . ' imported success' . PHP_EOL : $filename . ' import failed' . PHP_EOL;
if ($update == 0) {
$msg = $filename . ' import failed' . PHP_EOL;
} else if ($update == 1) {
$msg = $filename . ' imported success' . PHP_EOL;
} else if ($update == 2) {
$msg = $filename . ' already imported' . PHP_EOL;
} else if ($update == 3) {
$msg = $filename . ' invalid request number' . PHP_EOL;
}
file_put_contents($log_file_path, date('h:i:sa ') . $msg, FILE_APPEND | LOCK_EX);
if(empty($requesterName)){
$requesterName = "Team";
}
if (in_array($update, array(0, 2, 3))) {
$mail_id = strstr($filename, '-', true);
$params = array(
'subject' => $msg,
'body' => "<p>Hi ".$requesterName.",<br/></p>
<p>The DCG pricing tool has failed to upload a price quote input request(attached here) . Request you to please review and correct the template.
</p>
<p>
<strong>Attachment: </strong><a href='" . $base_url . "/sites/all/modules/pricecal/tmp/" . $filename . "'>Click here</a><br/>
</p>
<p>*** This is a system generated email, please do not reply to this email ***</p>
<p>Thanks,<br/>DCG Pricing Team</p>",
);
if(!empty($requester_emailId)){
//drupal_mail('pricecal', 'import_success_email', 'chintan.p#blueoceanmi.com,'.$requester_emailId, language_default(), $params);
}else{
// drupal_mail('pricecal', 'import_success_email', 'chintan.p#blueoceanmi.com', language_default(), $params);
}
}
}
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-#.]/', '', $string); // Removes special chars.
}
?>
I'm facing really serious issue on live server this code works fine 2 days before but now its saying memory exhausted, i tried to increase memory but still not working. Can you please somebody help me.

Locate HTML and plain text using imap_fetchstructure

I want to locate the html and/or the plain text using the imap_fetchstructure.
I tried several solutions but the emails don't have always the same structure.
I'm actually using:
$message=imap_fetchbody($inbox, $number, "1.2.1");
if ($message== "") {
$message =imap_fetchbody($inbox, $number, "1.1");
}
if ($message== "") {
$message = imap_fetchbody($inbox, $number, "1");
}
$message = imap_qprint($body);
When trying this; the result is sometimes correct and sometimes returning The content of the attachements depending on the mail server.
So I want a solution based on Imap_fetchstructure.
I found an answer for my question:
function getBody($uid, $imap) {
$body = $this->get_part($imap, $uid, "TEXT/HTML");
// if HTML body is empty, try getting text body
if ($body == "") {
$body = $this->get_part($imap, $uid, "TEXT/PLAIN");
}
return $body;
}
function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) {
if (!$structure) {
$structure = imap_fetchstructure($imap, $uid, FT_UID);
}
if ($structure) {
if ($mimetype == $this->get_mime_type($structure)) {
if (!$partNumber) {
$partNumber = 1;
}
$text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
switch ($structure->encoding) {
case 3: return imap_base64($text);
case 4: return imap_qprint($text);
default: return $text;
}
}
// multipart
if ($structure->type == 1) {
foreach ($structure->parts as $index => $subStruct) {
$prefix = "";
if ($partNumber) {
$prefix = $partNumber . ".";
}
$data = $this->get_part($imap, $uid, $mimetype, $subStruct,
$prefix. ($index + 1));
if ($data) {
return $data;
}
}
}
}
return false;
}
function get_mime_type($structure) {
$primaryMimetype = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION",
"AUDIO", "IMAGE", "VIDEO", "OTHER");
if ($structure->subtype) {
return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
}
return "TEXT/PLAIN";
}
You can use like this to separate from html and plaintext:
$inbox = imap_open($hostName,$userName,$pwd) or die('Cannot connect (Allow gmail IMAP): ' . imap_last_error());
$emails = imap_search($inbox,'UNSEEN');
if($emails){
rsort($emails);
foreach($emails as $email_number){
$structure = imap_fetchstructure($inbox, $email_number);
if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {// IF HTML
$part = $structure->parts[1];
$receivedEmailContent = imap_fetchbody($inbox,$email_number,2);
if($part->encoding == 3) {
$receivedEmailContent = imap_base64($receivedEmailContent);
} else if($part->encoding == 1) {
$receivedEmailContent = imap_8bit($receivedEmailContent);
} else {
$receivedEmailContent = imap_qprint($receivedEmailContent);
}
}else{//IF NOT HTML
$receivedEmailContent = imap_fetchbody($inbox,$email_number,1);
if($structure->type == 0){
$receivedEmailContent = imap_base64($receivedEmailContent);
}else{
$receivedEmailContent = imap_qprint($receivedEmailContent);
}
}
$receivedEmailContent = strip_tags($receivedEmailContent);
$header = imap_headerinfo ( $inbox, $email_number);
$receivedEmailTitle = $header->subject;
$receivedEmailSenderName = $header->from[0]->personal;
$receivedEmailSenderEmail = $header->from[0]->mailbox . "#" . $header->from[0]->host;
}
}
imap_close($inbox);

How to fetch all unread mail with attachment as an array ? i am using following code

I am trying to use this code, but I don't understand how we fetch the attachment with the sender's email . This is my code, and I tried so many times with different-2 code but yet I get no solutions.
public function myresume(&$response)
{
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'My gmail username';
$password = 'password';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox,'ALL');
if($emails)
{
$output = '';
rsort($emails);
foreach($emails as $email_number) {
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
$output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
$output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
$output.= '<span class="from">'.$overview[0]->from.'</span>';
$output.= '<span class="date">on '.$overview[0]->date.'</span>';
$output.= '</div>';
$output.= '<div class="body">'.$message.'</div>';
}
echo $output ;
}
imap_close($inbox);
}
Try this way to get unseen email and store in any folder
$server = '{imap.gmail.com:993/imap/ssl}INBOX';
$login = 'username';
$password = 'password';
/* try to connect */
$connection = imap_open($server,$login,$password) or die('Cannot connect to your sever: ' . imap_last_error());
/*get only unseen mail from inbox*/
$result = imap_search($connection, 'UNSEEN');
$max_emails = 1;
/* if any emails found, iterate through each email */
if($emails) {
$count = 1;
/* put the newest emails on top */
rsort($emails);
$attachments = array();
/* for every email... */
foreach($emails as $email_number)
{
/* get mail structure */
$structure = imap_fetchstructure($inbox, $email_number);
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
/* 4 = QUOTED-PRINTABLE encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 3 = BASE64 encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
}
imap_close($inbox);
/*store mail attachments to locally*/
foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename))
$filename = $attachment['filename'];
if(empty($filename))
$filename = time() . ".dat";
$fp = fopen($path." ".$email_number . "-" . $filename, "w+");
$csvFileName=$path." ".$email_number . "-" . $filename;
fwrite($fp, $attachment['attachment']);
fclose($fp);
$array=$fields=array();
$i=0;
}
}
}
You can use imap_fetchstructure to understand the mail structure and fetch the attachments. Below is a example copied from http://www.php.net/manual/en/function.imap-fetchstructure.php
(code to parse and decode all types of messages, including attachments.)
<?php
function getmsg ($mbox, $mid)
{
// input $mbox = IMAP stream, $mid = message id
// output all the following:
global $charset, $htmlmsg, $plainmsg, $attachments;
$htmlmsg = $plainmsg = $charset = '';
$attachments = array();
// HEADER
$h = imap_header($mbox, $mid);
// add code here to get date, from, to, cc, subject...
// BODY
$s = imap_fetchstructure($mbox, $mid);
if (! $s->parts) // simple
getpart($mbox, $mid, $s, 0); // pass 0 as part-number
else { // multipart: cycle through each part
foreach ($s->parts as $partno0 => $p)
getpart($mbox, $mid, $p, $partno0 + 1);
}
}
function getpart ($mbox, $mid, $p, $partno)
{
// $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
global $htmlmsg, $plainmsg, $charset, $attachments;
// DECODE DATA
$data = ($partno) ? imap_fetchbody($mbox, $mid, $partno) : // multipart
imap_body($mbox, $mid); // simple
// Any part may be encoded, even plain text messages,
// so check everything.
if ($p->encoding == 4)
$data = quoted_printable_decode($data);
elseif ($p->encoding == 3)
$data = base64_decode($data);
// PARAMETERS
// get all parameters, like charset, filenames of attachments, etc.
$params = array();
if ($p->parameters)
foreach ($p->parameters as $x)
$params[strtolower($x->attribute)] = $x->value;
if ($p->dparameters)
foreach ($p->dparameters as $x)
$params[strtolower($x->attribute)] = $x->value;
// ATTACHMENT
// Any part with a filename is an attachment,
// so an attached text file (type 0) is not mistaken as the message.
if ($params['filename'] || $params['name']) {
// filename may be given as 'Filename' or 'Name' or both
$filename = ($params['filename']) ? $params['filename'] : $params['name'];
// filename may be encoded, so see imap_mime_header_decode()
$attachments[$filename] = $data; // this is a problem if two files have
// same name
}
// TEXT
if ($p->type == 0 && $data) {
// Messages may be split in different parts because of inline attachments,
// so append parts together with blank row.
if (strtolower($p->subtype) == 'plain')
$plainmsg.
trim($data) . "\n\n";
else
$htmlmsg. =
$data . "<br><br>";
$charset = $params['charset']; // assume all parts are same charset
}
// EMBEDDED MESSAGE
// Many bounce notifications embed the original message as type 2,
// but AOL uses type 1 (multipart), which is not handled here.
// There are no PHP functions to parse embedded messages,
// so this just appends the raw source to the main message.
elseif ($p->type == 2 && $data) {
$plainmsg. =
$data . "\n\n";
}
// SUBPART RECURSION
if ($p->parts) {
foreach ($p->parts as $partno0 => $p2)
getpart($mbox, $mid, $p2, $partno . '.' . ($partno0 + 1)); // 1.2, 1.2.1, etc.
}
}
?>

Fatal error: Using $this when not in object context error [duplicate]

This question already has answers here:
Fatal error: Using $this when not in object context
(4 answers)
Closed 9 years ago.
I am getting Fatal error: Using $this when not in object context when running this below code. I am writing a script to forward my emails to another account. Please help me. I am a newbie to php. The error points the if (is_resource($this->connection)) line. but as far as I know things are fine there.
$hostname = '{imap.xyz.com:993/imap/ssl}INBOX';
$username = 'aaaaa#xyz.com';
$password = 'xxxxxxxxx';
$connection = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' . imap_last_error());
function Message_Parse($id)
{
if (is_resource($this->connection))
{
$result = array
(
'text' => null,
'html' => null,
'attachments' => array(),
);
$structure = imap_fetchstructure($this->connection, $id, FT_UID);
if (array_key_exists('parts', $structure))
{
foreach ($structure->parts as $key => $part)
{
if (($part->type >= 2) || (($part->ifdisposition == 1) && ($part->disposition == 'ATTACHMENT')))
{
$filename = null;
if ($part->ifparameters == 1)
{
$total_parameters = count($part->parameters);
for ($i = 0; $i < $total_parameters; $i++)
{
if (($part->parameters[$i]->attribute == 'NAME') || ($part->parameters[$i]->attribute == 'FILENAME'))
{
$filename = $part->parameters[$i]->value;
break;
}
}
if (is_null($filename))
{
if ($part->ifdparameters == 1)
{
$total_dparameters = count($part->dparameters);
for ($i = 0; $i < $total_dparameters; $i++)
{
if (($part->dparameters[$i]->attribute == 'NAME') || ($part->dparameters[$i]->attribute == 'FILENAME'))
{
$filename = $part->dparameters[$i]->value;
break;
}
}
}
}
}
$result['attachments'][] = array
(
'filename' => $filename,
'content' => str_replace(array("\r", "\n"), '', trim(imap_fetchbody($this->connection, $id, ($key + 1), FT_UID))),
);
}
else
{
if ($part->subtype == 'PLAIN')
{
$result['text'] = imap_fetchbody($this->connection, $id, ($key + 1), FT_UID);
}
else if ($part->subtype == 'HTML')
{
$result['html'] = imap_fetchbody($this->connection, $id, ($key + 1), FT_UID);
}
else
{
foreach ($part->parts as $alternative_key => $alternative_part)
{
if ($alternative_part->subtype == 'PLAIN')
{
echo '<h2>' . $alternative_part->subtype . ' ' . $alternative_part->encoding . '</h2>';
$result['text'] = imap_fetchbody($this->connection, $id, ($key + 1) . '.' . ($alternative_key + 1), FT_UID);
}
else if ($alternative_part->subtype == 'HTML')
{
echo '<h2>' . $alternative_part->subtype . ' ' . $alternative_part->encoding . '</h2>';
$result['html'] = imap_fetchbody($this->connection, $id, ($key + 1) . '.' . ($alternative_key + 1), FT_UID);
}
}
}
}
}
}
else
{
$result['text'] = imap_body($this->connection, $id, FT_UID);
}
$result['text'] = imap_qprint($result['text']);
$result['html'] = imap_qprint(imap_8bit($result['html']));
return $result;
}
return false;
}
$to = 'aaaa#gmail.com';
$subject = 'the subject';
$message = 'test';
$id=1;
Message_Parse($id);
$headers = 'From: aaa#xyz.com' . "\r\n" .
'Reply-To: aaa#xyz.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$mail = mail($to, $subject, $result, $headers);
if($mail){
echo "YES";
} else{
echo "NO";
}
Just change $this->connection to $connection. $this only applies when you're in a class. Also, you may need to call global $connection; at the top of your function. I believe any variables that aren't passed in to the parameters need this keyword called.
See information on "global keyword" at: http://php.net/manual/en/language.variables.scope.php
As all others said, you are not inside an object, so you cannot use $this.
But you are inside a function, so you also cannot access any variables outside of this function unless you make it accessible.
The solution using global works, but it will bring you to hell if you someday decide that your global variable $connection should be renamed.
A better solution is to pass it as a second parameter to your function.
function Message_Parse($id) should become function Message_Parse($id, $connection)
if (is_resource($this->connection)) should become if (is_resource($connection))
$id=1; Message_Parse($id); should become $id=1; Message_Parse($id, $connection);
Done.
$this only exists inside methods that are part of classes. $this does not exist in functions or anywhere else that is not part of a class. Take a look at the PHP manual page about basic OOP for more about this.
If you want to refer to the global variable $connection instead, you can do that by changing the beginning of the function to:
function Message_Parse($id)
{
global $connection;
if (is_resource($connection))
{
Do note though that using global variables is bad programming practice in any language.

Bad message number error

I am using a script to forward email addresses and getting bad message number error. the message number is parsed as an argument for the function and i am not sure how to get the message number and insert it as the argument. Please help. I am new to php. The error points out $structure = imap_fetchstructure($connection, $id, FT_UID); and $result['text'] = imap_body($connection, $id, FT_UID); parts. Please help me.
<?php
require_once '../swift/lib/swift_required.php';
$hostname = '{imap.xyz.com:993/imap/ssl}INBOX';
$username = 'email';
$password = 'password';
/* try to connect */
$connection = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' . imap_last_error());
ini_set('memory_limit', '256M');
function Message_Parse($id)
{
global $connection;
if (is_resource($connection))
{
$result = array
(
'text' => null,
'html' => null,
'attachments' => array(),
);
$structure = imap_fetchstructure($connection, $id, FT_UID);
//print_r($structure);
//array_key_exists — Checks if the given key or index exists in the array
if (is_array($structure) && array_key_exists('parts', $structure))
{
foreach ($structure->parts as $key => $part)
{
if (($part->type >= 2) || (($part->ifdisposition == 1) && ($part->disposition == 'ATTACHMENT')))
{
$filename = null;
if ($part->ifparameters == 1)
{
$total_parameters = count($part->parameters);
for ($i = 0; $i < $total_parameters; $i++)
{
if (($part->parameters[$i]->attribute == 'NAME') || ($part->parameters[$i]->attribute == 'FILENAME'))
{
$filename = $part->parameters[$i]->value;
break;
}
}
if (is_null($filename))
{
if ($part->ifdparameters == 1)
{
$total_dparameters = count($part->dparameters);
for ($i = 0; $i < $total_dparameters; $i++)
{
if (($part->dparameters[$i]->attribute == 'NAME') || ($part->dparameters[$i]->attribute == 'FILENAME'))
{
$filename = $part->dparameters[$i]->value;
break;
}
}
}
}
}
$result['attachments'][] = array
(
'filename' => $filename,
'content' => str_replace(array("\r", "\n"), '', trim(imap_fetchbody($connection, $id, ($key + 1), FT_UID))),
);
}
else
{
if ($part->subtype == 'PLAIN')
{
$result['text'] = imap_fetchbody($connection, $id, ($key + 1), FT_UID);
}
else if ($part->subtype == 'HTML')
{
$result['html'] = imap_fetchbody($connection, $id, ($key + 1), FT_UID);
}
else
{
foreach ($part->parts as $alternative_key => $alternative_part)
{
if ($alternative_part->subtype == 'PLAIN')
{
echo '<h2>' . $alternative_part->subtype . ' ' . $alternative_part->encoding . '</h2>';
$result['text'] = imap_fetchbody($connection, $id, ($key + 1) . '.' . ($alternative_key + 1), FT_UID);
}
else if ($alternative_part->subtype == 'HTML')
{
echo '<h2>' . $alternative_part->subtype . ' ' . $alternative_part->encoding . '</h2>';
$result['html'] = imap_fetchbody($connection, $id, ($key + 1) . '.' . ($alternative_key + 1), FT_UID);
}
}
}
}
}
}
else
{
$result['text'] = imap_body($connection, $id, FT_UID);
}
$result['text'] = imap_qprint($result['text']);
$result['html'] = imap_qprint(imap_8bit($result['html']));
return $result;
}
return false;
}
$emails = imap_search($connection,'ALL');
// rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
echo $email_number;
$result = Message_Parse($email_number);
//$data = $result['attachments'];
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
//$attachment = Swift_Attachment::newInstance($result['attachments'], $filename, 'audio/mp3');
$message = Swift_Message::newInstance('test message1 ')
->setFrom(array('from address' => 'name'))
->setTo(array('to address.com'))
->setBody($result['text']);
// ->attach($attachment);
$result1 = $mailer->send($message);
}
?>
The FT_UID flag means that you are using message uid, rather than message sequence id. In order to get the uid for a given message, you have to use the msg_uid() function.
Since you are beginner, I hardly think this was your question, so here is complete example how to get the headers and the content of a given message:
<?php
$emailAddress = 'postmaster#example.com';
$password = 'someSecretPassword';
$server = 'localhost';
$folder = 'Inbox';
$dsn = sprintf('{%s}%s', $server, $folder);
$mbox = imap_open($dsn, $emailAddress, $password);
if (!$mbox) {
die ('Unable to connect');
}
$status = imap_status($mbox, $dsn, SA_ALL);
$msgs = imap_sort($mbox, SORTDATE, 1, SE_UID);
foreach ($msgs as $msguid) {
$msgno = imap_msgno($mbox, $msguid);
$headers = imap_headerinfo($mbox, $msgno);
$structure = imap_fetchstructure($mbox, $msguid, FT_UID);
var_dump($headers);
var_dump($structure);
}
I was getting the same error when inside the loop, after processing the email, I was moving the message to a different folder.
After I comment out the imap_move the error went away.

Categories