Double Sms issue in my Php Sms API - php

I've a Php SMS API which send SMS to my client. All is OK right now but it's send 2 sms once i submit the form. I can't understand why it's send 2 SMS. Can you guys tell me why its send 2 sms ?
Api Code:
<?php
class Sender{
var $host;
var $port;
/*
* Username that is to be used for submission
*/
var $strUserName;
/*
* password that is to be used along with username
*/
var $strPassword;
/*
* Sender Id to be used for submitting the message
*/
var $strSender;
/*
* Message content that is to be transmitted
*/
var $strMessage;
/*
* Mobile No is to be transmitted.
*/
var $strMobile;
/*
* What type of the message that is to be sent
* <ul>
* <li>0:means plain text</li>
* <li>1:means flash</li>
* <li>2:means Unicode (Message content should be inHex)</li>
* <li>6:means Unicode Flash (Message content shouldbe in Hex)</li>
* </ul>
*/
var $strMessageType;
/*
* Require DLR or not
* <ul>
* <li>0:means DLR is not Required</li>
* <li>1:means DLR is Required</li>
* </ul>
*/
var $strDlr;
private function sms__unicode($message){
$hex1='';
if (function_exists('iconv')) {
$latin = #iconv('UTF-8', 'ISO-8859-1', $message);
if (strcmp($latin, $message)) {
$arr = unpack('H*hex', #iconv('UTF-8', 'UCS-2BE', $message));
$hex1 = strtoupper($arr['hex']);
}
if($hex1 ==''){
$hex2='';
$hex='';
for ($i=0; $i < strlen($message); $i++){
$hex = dechex(ord($message[$i]));
$len =strlen($hex);
$add = 4 - $len;
if($len < 4){
for($j=0;$j<$add;$j++){
$hex="0".$hex;
}
}
$hex2.=$hex;
}
return $hex2;
}
else{
return $hex1;
}
}
else{
print 'iconv Function Not Exists !';
}
}
//Constructor..
public function Sender ($host,$port,$username,$password, $sender, $message,
$mobile,$msgtype,$dlr){
$this->host=$host;
$this->port=$port;
$this->strUserName = $username;
$this->strPassword = $password;
$this->strSender= $sender;
$this->strMessage=$message; //URL Encode The Message..
$this->strMobile=$mobile;
$this->strMessageType=$msgtype;
$this->strDlr=$dlr;
}
public function Submit(){
if($this->strMessageType=="2" ||
$this->strMessageType=="6") {
//Call The Function Of String To HEX.
$this->strMessage = $this->sms__unicode(
$this->strMessage);
try{
//Smpp http Url to send sms.
$live_url="http://".$this->host.":".$this->port."/bulksms
/bulksms?username=".$this->strUserName."&password=".$this->strPassword."&
type=".$this->strMessageType."&dlr=".$this->strDlr."&destination=".$this->strMobile."&
source=".$this->strSender."&message=".$this->strMessage."";
$parse_url=file($live_url);
//echo $parse_url[0];
}catch(Exception $e){
//echo 'Message:' .$e->getMessage();
}
}
else
$this->strMessage=urlencode($this->strMessage);
try{
//Smpp http Url to send sms.
$live_url="http://".$this->host.":".
$this->port."/bulksms/bulksms?username=".$this->strUserName."&password=".$this->strPassword."&
type=".$this->strMessageType."&dlr=".$this->strDlr."&destination=".$this->strMobile."&
source=".$this->strSender."&message=".$this->strMessage."";
$parse_url=file($live_url);
//echo $parse_url[0];
}
catch(Exception $e){
//echo 'Message:' .$e->getMessage();
}
}
}
//Call The Constructor.
$obj = new Sender("mywebserver","myport","username","password","sender name", "my message",
"mobile number","2","1");
$obj->Submit();
?>
Thanks.

You forgot to put the routine in case of "else" in braces. it should be like:
else {
$this->strMessage=urlencode( $this->strMessage );
try {
//Smpp http Url to send sms.
$live_url = "http://".$this->host . ":" .
$this->port."/bulksms/bulksms?username = ".$this->strUserName."&password=".$this->strPassword."&
type = ".$this->strMessageType."&dlr=".$this->strDlr."&destination=".$this->strMobile."&
source = ".$this->strSender."&message=".$this->strMessage."";
$parse_url = file( $live_url );
//echo $parse_url[0];
} catch( Exception $e ) {
//echo 'Message:' .$e->getMessage();
}
}
Note the braces for "else".

Related

Returning value from callback

After registering a new user, I receive a selector and token for account verification.
I want to be able to know whether or not a confirmation mail was sent, but I'm having troubles returning the value from the callback. Here's what I have:
try {
$callback = function ($selector, $token) {
$msg = "some message";
if(mail($_POST['email'],"Please verify your account",$msg))
{
return "success";
}
else
{
return "mail_not_sent";
}
};
$auth->registerWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username'], $callback);
$output['result']=$callback; //this is the array where I want to store the result in ("success" of "mail_not_sent").
}
catch ($e) {
}
It doesn't look like Auth::registerWithUniqueUsername() gives you access to the result of the callback, so if I had to do this, I would do something like this:
$callback_result = '';
$callback = function ($selector, $token) use (&$callback_result) {
/* Other code here */
$callback_result = 'whatever';
/* Other code here */
};
$auth->registerWithUniqueUsername(/* Other args here */, $callback);
$output['result'] = $callback_result;
This is a bit odd way but:
try {
$mailFlag = null;
$callback = function ($selector, $token) use (&$mailFlag) {
$msg = "some message";
if(mail($_POST['email'],"Please verify your account",$msg))
{
$mailFlag = "success";
}
else
{
$mailFlag = "mail_not_sent";
}
};
$auth->registerWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username'], $callback);
$output['result'] = $mailFlag; //this is the array where I want to store the result in ("success" of "mail_not_sent").
}
catch ($e) {
}

email exist or not working in gmail only not in other domains

i am trying to check email exist or not but its giving correct result while i am checking gmail and on other domain it's giving available for all email
is there any php class which can used for all domain names please suggest me.
<?php
/**
* Validate Email Addresses Via SMTP
* This queries the SMTP server to see if the email address is accepted.
* #copyright http://creativecommons.org/licenses/by/2.0/ - Please keep this comment intact
* #author gabe#fijiwebdesign.com
* #contributers adnan#barakatdesigns.net
* #version 0.1a
*/
class SMTP_validateEmail {
/**
* PHP Socket resource to remote MTA
* #var resource $sock
*/
var $sock;
/**
* Current User being validated
*/
var $user;
/**
* Current domain where user is being validated
*/
var $domain;
/**
* List of domains to validate users on
*/
var $domains;
/**
* SMTP Port
*/
var $port = 25;
/**
* Maximum Connection Time to an MTA
*/
var $max_conn_time = 30;
/**
* Maximum time to read from socket
*/
var $max_read_time = 5;
/**
* username of sender
*/
var $from_user = 'user';
/**
* Host Name of sender
*/
var $from_domain = 'localhost';
/**
* Nameservers to use when make DNS query for MX entries
* #var Array $nameservers
*/
var $nameservers = array(
'192.168.0.1'
);
var $debug = false;
/**
* Initializes the Class
* #return SMTP_validateEmail Instance
* #param $email Array[optional] List of Emails to Validate
* #param $sender String[optional] Email of validator
*/
function SMTP_validateEmail($emails = false, $sender = false) {
if ($emails) {
$this->setEmails($emails);
}
if ($sender) {
$this->setSenderEmail($sender);
}
}
function _parseEmail($email) {
$parts = explode('#', $email);
$domain = array_pop($parts);
$user= implode('#', $parts);
return array($user, $domain);
}
/**
* Set the Emails to validate
* #param $emails Array List of Emails
*/
function setEmails($emails) {
foreach($emails as $email) {
list($user, $domain) = $this->_parseEmail($email);
if (!isset($this->domains[$domain])) {
$this->domains[$domain] = array();
}
$this->domains[$domain][] = $user;
}
}
/**
* Set the Email of the sender/validator
* #param $email String
*/
function setSenderEmail($email) {
$parts = $this->_parseEmail($email);
$this->from_user = $parts[0];
$this->from_domain = $parts[1];
}
/**
* Validate Email Addresses
* #param String $emails Emails to validate (recipient emails)
* #param String $sender Sender's Email
* #return Array Associative List of Emails and their validation results
*/
function validate($emails = false, $sender = false) {
$results = array();
if ($emails) {
$this->setEmails($emails);
}
if ($sender) {
$this->setSenderEmail($sender);
}
// query the MTAs on each Domain
foreach($this->domains as $domain=>$users) {
$mxs = array();
// retrieve SMTP Server via MX query on domain
list($hosts, $mxweights) = $this->queryMX($domain);
// retrieve MX priorities
for($n=0; $n < count($hosts); $n++){
$mxs[$hosts[$n]] = $mxweights[$n];
}
asort($mxs);
// last fallback is the original domain
array_push($mxs, $this->domain);
$this->debug(print_r($mxs, 1));
$timeout = $this->max_conn_time/(count($hosts)>0 ? count($hosts) : 1);
// try each host
while(list($host) = each($mxs)) {
// connect to SMTP server
$this->debug("try $host:$this->port\n");
if ($this->sock = fsockopen($host, $this->port, $errno, $errstr, (float) $timeout)) {
stream_set_timeout($this->sock, $this->max_read_time);
break;
}
}
// did we get a TCP socket
if ($this->sock) {
$reply = fread($this->sock, 2082);
$this->debug("<<<\n$reply");
preg_match('/^([0-9]{3})/ims', $reply, $matches);
$code = isset($matches[1]) ? $matches[1] : '';
if($code != '220') {
// MTA gave an error...
foreach($users as $user) {
$results[$user.'#'.$domain] = false;
}
continue;
}
// say helo
$this->send("HELO ".$this->from_domain);
// tell of sender
$this->send("MAIL FROM: <".$this->from_user.'#'.$this->from_domain.">");
// ask for each recepient on this domain
foreach($users as $user) {
// ask of recepient
$reply = $this->send("RCPT TO: <".$user.'#'.$domain.">");
// get code and msg from response
preg_match('/^([0-9]{3}) /ims', $reply, $matches);
$code = isset($matches[1]) ? $matches[1] : '';
if ($code == '250') {
// you received 250 so the email address was accepted
$results[$user.'#'.$domain] = true;
} elseif ($code == '451' || $code == '452') {
// you received 451 so the email address was greylisted (or some temporary error occured on the MTA) - so assume is ok
$results[$user.'#'.$domain] = true;
} else {
$results[$user.'#'.$domain] = false;
}
}
// quit
$this->send("quit");
// close socket
fclose($this->sock);
}
}
return $results;
}
function send($msg) {
fwrite($this->sock, $msg."\r\n");
$reply = fread($this->sock, 2082);
$this->debug(">>>\n$msg\n");
$this->debug("<<<\n$reply");
return $reply;
}
/**
* Query DNS server for MX entries
* #return
*/
function queryMX($domain) {
$hosts = array();
$mxweights = array();
if (function_exists('getmxrr')) {
getmxrr($domain, $hosts, $mxweights);
} else {
// windows, we need Net_DNS
require_once 'Net/DNS.php';
$resolver = new Net_DNS_Resolver();
$resolver->debug = $this->debug;
// nameservers to query
$resolver->nameservers = $this->nameservers;
$resp = $resolver->query($domain, 'MX');
if ($resp) {
foreach($resp->answer as $answer) {
$hosts[] = $answer->exchange;
$mxweights[] = $answer->preference;
}
}
}
return array($hosts, $mxweights);
}
/**
* Simple function to replicate PHP 5 behaviour. http://php.net/microtime
*/
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function debug($str) {
if ($this->debug) {
echo htmlentities($str);
}
}
}
?>
<?php
require_once("smtpvalidateclass.php");
// the email to validate
$emails = array('infodhcjkdshjkhdksrahul#yahoo.com');
// an optional sender
$sender = 'user#example.com';
// instantiate the class
$SMTP_Valid = new SMTP_validateEmail();
// do the validation
$result = $SMTP_Valid->validate($emails, $sender);
// view results
var_dump($result);
echo ' is '.($result ? 'valid' : 'invalid')."\n";
// send email?
if ($result) {
//mail(...);
}
?>

Codeigniter emailing - adding BCC

I'm new so please bear with me.
I am trying to add a BCC recipient to one of codeigniter applications' email.php config file. The original was created by an employee who has since left our business and I am struggling to add a bcc recipient into the code.
I have searched stackoverflow and tried endless variations but I am not having any luck. All I want to do is define one bcc email recipient.
I would really really really appreciate anybody's help :)
Here is a portion of the the current code I think is relevant:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Email Class
*
* Permits email to be sent using Mail, Sendmail, or SMTP.
*
* #package CodeIgniter
* #subpackage Libraries
* #category Libraries
* #author ExpressionEngine Dev Team
* #link http://codeigniter.com/user_guide/libraries/email.html
*/
class CI_Email {
var $useragent = "CodeIgniter";
var $mailpath = "/usr/sbin/sendmail"; // Sendmail path
var $protocol = "mail"; // mail/sendmail/smtp
var $smtp_host = ""; // SMTP Server. Example: mail.earthlink.net
var $smtp_user = ""; // SMTP Username
var $smtp_pass = ""; // SMTP Password
var $smtp_port = "25"; // SMTP Port
var $smtp_timeout = 5; // SMTP Timeout in seconds
var $smtp_crypto = ""; // SMTP Encryption. Can be null, tls or ssl.
var $wordwrap = TRUE; // TRUE/FALSE Turns word-wrap on/off
var $wrapchars = "76"; // Number of characters to wrap at.
var $mailtype = "text"; // text/html Defines email formatting
var $charset = "utf-8"; // Default char set: iso-8859-1 or us-ascii
var $multipart = "mixed"; // "mixed" (in the body) or "related" (separate)
var $alt_message = ''; // Alternative message for HTML emails
var $validate = FALSE; // TRUE/FALSE. Enables email validation
var $priority = "3"; // Default priority (1 - 5)
var $newline = "\n"; // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822)
var $crlf = "\n"; // The RFC 2045 compliant CRLF for quoted-printable is "\r\n". Apparently some servers,
// even on the receiving end think they need to muck with CRLFs, so using "\n", while
// distasteful, is the only thing that seems to work for all environments.
var $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override. Set to FALSE for Yahoo.
var $bcc_batch_mode = FALSE; // TRUE/FALSE Turns on/off Bcc batch feature
var $bcc_batch_size = 200; // If bcc_batch_mode = TRUE, sets max number of Bccs in each batch
var $_safe_mode = FALSE;
var $_subject = "";
var $_body = "";
var $_finalbody = "";
var $_alt_boundary = "";
var $_atc_boundary = "";
var $_header_str = "";
var $_smtp_connect = "";
var $_encoding = "8bit";
var $_IP = FALSE;
var $_smtp_auth = FALSE;
var $_replyto_flag = FALSE;
var $_debug_msg = array();
var $_recipients = array();
var $_cc_array = array();
var $_bcc_array = array();
var $_headers = array();
var $_attach_name = array();
var $_attach_type = array();
var $_attach_disp = array();
var $_protocols = array('mail', 'sendmail', 'smtp');
var $_base_charsets = array('us-ascii', 'iso-2022-'); // 7-bit charsets (excluding language suffix)
var $_bit_depths = array('7bit', '8bit');
var $_priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
/**
* Constructor - Sets Email Preferences
*
* The constructor can be passed an array of config values
*/
public function __construct($config = array())
{
if (count($config) > 0)
{
$this->initialize($config);
}
else
{
$this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
$this->_safe_mode = ((boolean)#ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
}
log_message('debug', "Email Class Initialized");
}
// --------------------------------------------------------------------
/**
* Initialize preferences
*
* #access public
* #param array
* #return void
*/
public function initialize($config = array())
{
foreach ($config as $key => $val)
{
if (isset($this->$key))
{
$method = 'set_'.$key;
if (method_exists($this, $method))
{
$this->$method($val);
}
else
{
$this->$key = $val;
}
}
}
$this->clear();
$this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
$this->_safe_mode = ((boolean)#ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
return $this;
}
// --------------------------------------------------------------------
/**
* Initialize the Email Data
*
* #access public
* #return void
*/
public function clear($clear_attachments = FALSE)
{
$this->_subject = "";
$this->_body = "";
$this->_finalbody = "";
$this->_header_str = "";
$this->_replyto_flag = FALSE;
$this->_recipients = array();
$this->_cc_array = array();
$this->_bcc_array = array();
$this->_headers = array();
$this->_debug_msg = array();
$this->_set_header('User-Agent', $this->useragent);
$this->_set_header('Date', $this->_set_date());
if ($clear_attachments !== FALSE)
{
$this->_attach_name = array();
$this->_attach_type = array();
$this->_attach_disp = array();
}
return $this;
}
// --------------------------------------------------------------------
/**
* Set FROM
*
* #access public
* #param string
* #param string
* #return void
*/
public function from($from, $name = '')
{
if (preg_match( '/\<(.*)\>/', $from, $match))
{
$from = $match['1'];
}
if ($this->validate)
{
$this->validate_email($this->_str_to_array($from));
}
// prepare the display name
if ($name != '')
{
// only use Q encoding if there are characters that would require it
if ( ! preg_match('/[\200-\377]/', $name))
{
// add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
$name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"';
}
else
{
$name = $this->_prep_q_encoding($name, TRUE);
}
}
$this->_set_header('From', $name.' <'.$from.'>');
$this->_set_header('Return-Path', '<'.$from.'>');
return $this;
}
// --------------------------------------------------------------------
/**
* Set Reply-to
*
* #access public
* #param string
* #param string
* #return void
*/
public function reply_to($replyto, $name = '')
{
if (preg_match( '/\<(.*)\>/', $replyto, $match))
{
$replyto = $match['1'];
}
if ($this->validate)
{
$this->validate_email($this->_str_to_array($replyto));
}
if ($name == '')
{
$name = $replyto;
}
if (strncmp($name, '"', 1) != 0)
{
$name = '"'.$name.'"';
}
$this->_set_header('Reply-To', $name.' <'.$replyto.'>');
$this->_replyto_flag = TRUE;
return $this;
}
// --------------------------------------------------------------------
/**
* Set Recipients
*
* #access public
* #param string
* #return void
*/
public function to($to)
{
$to = $this->_str_to_array($to);
$to = $this->clean_email($to);
if ($this->validate)
{
$this->validate_email($to);
}
if ($this->_get_protocol() != 'mail')
{
$this->_set_header('To', implode(", ", $to));
}
switch ($this->_get_protocol())
{
case 'smtp' :
$this->_recipients = $to;
break;
case 'sendmail' :
case 'mail' :
$this->_recipients = implode(", ", $to);
break;
}
return $this;
}
// --------------------------------------------------------------------
/**
* Set CC
*
* #access public
* #param string
* #return void
*/
public function cc($cc)
{
$cc = $this->_str_to_array($cc);
$cc = $this->clean_email($cc);
if ($this->validate)
{
$this->validate_email($cc);
}
$this->_set_header('Cc', implode(", ", $cc));
if ($this->_get_protocol() == "smtp")
{
$this->_cc_array = $cc;
}
return $this;
}
// --------------------------------------------------------------------
/**
* Set BCC
*
* #access public
* #param string
* #param string
* #return void
*/
public function bcc($bcc, $limit = '')
{
if ($limit != '' && is_numeric($limit))
{
$this->bcc_batch_mode = TRUE;
$this->bcc_batch_size = $limit;
}
$bcc = $this->_str_to_array($bcc);
$bcc = $this->clean_email($bcc);
if ($this->validate)
{
$this->validate_email($bcc);
}
if (($this->_get_protocol() == "smtp") OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
{
$this->_bcc_array = $bcc;
}
else
{
$this->_set_header('Bcc', implode(", ", $bcc));
}
return $this;
}
// --------------------------------------------------------------------
Could you please try below that code in your any controller index function and run it.
$this->load->library('email');
$this->email->from('your#example.com', 'Your Name');
$this->email->to('someone#example.com');
$this->email->cc('another#another-example.com');
$this->email->bcc('them#their-example.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send();
echo $this->email->print_debugger();
Simple var $bcc_batch_mode = TRUE;
Edit FALSE to TRUE and give a try!!

Changing Impresspages to use SMTP

I need to change the code below that belongs to Impresspages CMS to use SMTP instead of sendmail. How can I do this?
<?php
/**
* Queue controls the amount of emails per hour.
* All emails ar placed in queue and send as quiq as possible.
* Parameter "hourlyLimit" defines how much emails can be send in one hour.
* If required amount of emails is bigger than this parameter, part of messages will wait until next hour.
*
* #package ImpressPages
*
*
*/
namespace Ip\Internal\Email;
/**
* Class to send emails. Typically all emails should be send trouht this class.
* #package ImpressPages
*/
class Module
{
/**
* Adds email to the queue
*
* Even if there is a big amount of emails, there is always reserved 20% of traffic for immediate emails.
* Such emails are: registration cofirmation, contact form data and other.
* Newsletters, greetings always can wait a litle. So they are not immediate and will not be send if is less than 20% of traffic left.
*
* #param string $from email address from whish an email should be send
* #param $fromName
* #param string $to email address where an email should be send
* #param $toName
* #param $subject
* #param string $email email html text
* #param bool $immediate indicate hurry of an email.
* #param bool $html true if email message should be send as html
* #param array $files files that should be attached to the email. Files should be accessible for php at this moment. They will be cached until send time.
* #internal param $string #fromName
* #internal param $string #toName
*/
function addEmail($from, $fromName, $to, $toName, $subject, $email, $immediate, $html, $files = null)
{
$cached_files = [];
$cached_fileNames = [];
$cached_fileMimeTypes = [];
if ($files) {
if (is_string($files)) {
$files = array($files);
}
foreach ($files as $fileSetting) {
$file = [];
if (is_array($fileSetting)) {
$file['real_name'] = $fileSetting[0];
$file['required_name'] = basename($fileSetting[1]);
} else {
$file['real_name'] = $fileSetting;
$file['required_name'] = basename($fileSetting);
}
$new_name = 'contact_form_' . rand();
$new_name = \Ip\Internal\File\Functions::genUnoccupiedName($new_name, ipFile('file/tmp/'));
if (copy($file['real_name'], ipFile('file/tmp/' . $new_name))) {
$cached_files[] = ipFile('file/tmp/' . $new_name);
$cached_fileNames[] = $file['required_name'];
$tmpMimeType = \Ip\Internal\File\Functions::getMimeType($file['real_name']);
if ($tmpMimeType == null) {
$tmpMimeType = 'Application/octet-stream';
}
$cached_fileMimeTypes[] = $tmpMimeType;
} else {
trigger_error('File caching failed');
}
}
}
$cachedFilesStr = implode("\n", $cached_files);
$cachedFileNamesStr = implode("\n", $cached_fileNames);
$cachedFileMimeTypesStr = implode("\n", $cached_fileMimeTypes);
$email = str_replace('src="' . ipConfig()->baseUrl(), 'src="', $email);
Db::addEmail(
$from,
$fromName,
$to,
$toName,
$subject,
$email,
$immediate,
$html,
$cachedFilesStr,
$cachedFileNamesStr,
$cachedFileMimeTypesStr
);
}
/**
* Checks if there are some emails waiting in queue and sends them if possible.
*/
function send()
{
$alreadySent = Db::sentOrLockedCount(60);
if ($alreadySent !== false) {
$available = floor(ipGetOption('Email.hourlyLimit') * 0.8 - $alreadySent); //20% for immediate emails
$lockKey = md5(uniqid(rand(), true));
if ($available > 0) {
if ($available > 5 && !defined('CRON')) { //only cron job can send many emails at once.
$available = 5;
}
$locked = Db::lock($available, $lockKey);
} else {
$available = 0;
$locked = 0;
}
if ($locked == $available) { //if in queue left some messages
if (ipGetOption('Email.hourlyLimit') - ($alreadySent + $available) > 0) {
$locked = $locked + Db::lockOnlyImmediate(
ipGetOption('Email.hourlyLimit') - ($alreadySent + $available),
$lockKey
);
}
}
if ($locked) {
$emails = Db::getLocked($lockKey);
foreach ($emails as $key => $email) {
if (function_exists('set_time_limit')) {
set_time_limit((sizeof($emails) - $key) * 10 + 100);
}
$mail = new \PHPMailer();
/* $mail->Sender = $email['from'];
$mail->addCustomHeader("Return-Path: " . $email['from']);*/
$mail->From = $email['from'];
$mail->FromName = $email['fromName'];
$mail->AddReplyTo($email['from'], $email['fromName']);
$mail->WordWrap = 50; // set word wrap
$mail->CharSet = ipConfig()->get('charset');
$mail->Subject = $email['subject'];
/* foreach($this->posted_files as $file){
if(isset($_FILES[$file]['tmp_name']) && $_FILES[$file]['error'] == 0){
$mail->AddAttachment($_FILES[$file]['tmp_name'], $_FILES[$file]['name']);
}
}*/
$files = explode("\n", $email['files']);
$fileNames = explode("\n", $email['fileNames']);
$fileMimeTypes = explode("\n", $email['fileMimeTypes']);
$fileCount = min(count($files), count($fileNames), count($fileMimeTypes));
for ($i = 0; $i < $fileCount; $i++) {
if ($files[$i] != '') {
if ($fileMimeTypes[$i] == '') {
$answer = $mail->AddAttachment($files[$i], $fileNames[$i]);
} else {
$answer = $mail->AddAttachment(
$files[$i],
$fileNames[$i],
"base64",
$fileMimeTypes[$i]
);
}
if (!$answer) {
ipLog()->error(
'Email.addAttachmentFailed: {subject} to {to}',
array(
'to' => $email['to'],
'subject' => $email['subject'],
'filename' => $fileNames[$i],
)
);
return false;
}
}
}
if ($email['html']) {
$mail->IsHTML(true); // send as HTML
$mail->MsgHTML($email['email']);
try {
$altBody = \Ip\Internal\Text\Html2Text::convert($email['email']);
} catch (\Ip\Internal\Text\Html2TextException $e) {
$altBody = $email['email'];
}
$mail->AltBody = $altBody;
} else {
/*$h2t = new \Ip\Internal\Text\Html2Text($content, false);
$mail->Body = $h2t->get_text();*/
$mail->Body = $email['email'];
}
$mail->AddAddress($email['to'], $email['toName']);
$mail = ipFilter('ipSendEmailPHPMailerObject', $mail, $email);
if (!$mail->Send()) {
ipLog()->error(
'Email.sendFailed: {subject} to {to}',
array('to' => $email['to'], 'subject' => $email['subject'], 'body' => $email['email'])
);
return false;
}
if (sizeof($emails) > 5) {
sleep(1);
}
Db::unlockOne($email['id']);
}
}
}
return null;
}
}

Move mail from Trash to Inbox Gmail PHP Imap

I have never played with fetching and moving emails before using IMAP and PHP, so im struggeling with moving emails that are sent to the trash back to the inbox.
Ok, so i'm fetching my emails from Gmail correctly, and i am able to delete them, or move them to trash rather.
When i try to move them back to Inbox i get the following error:
Notice: Unknown: [TRYCREATE] No folder [Gmail]/Inbox (Failure) (errflg=2) in Unknown on line 0
So obviously there is something i dont quite get, and i have been searching the web and stackoverflow for the answer the last couple of hours with no luck. Does anyone know why this particular action does not succeed?
Any help is as usual much appreciated, i would love to get the hang of this and make myself a little email app.
Below is the class i have made, see the method undo(), thats where this particular warning pops up.
class Gmail {
public $emailsexists = false;
public $emailarray = '';
private $username;
private $password;
private $inbox;
public function __construct($username,$password) {
/* connect to gmail using imap */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$this->username = $username;
$this->password = $password;
/* try to connect using username and password set in core/init.php (gmail_credentials) */
$this->inbox = imap_open($hostname,$this->username,$this->password) or die('Cannot connect to Gmail: ' . imap_last_error());
}
public function delete($email) {
if ($email !== '' && is_numeric($email)) {
if (imap_mail_move($this->inbox, $email, '[Gmail]/Trash')) {
return true;
} else {
return false;
}
} else {
return false;
}
imap_close($this->inbox);
}
public function undo($email) {
if ($email !== '' && is_numeric($email)) {
if (imap_mail_move($this->inbox, $email, '[Gmail]/Inbox')) { // FIX Throws back a warning
return true;
} else {
return false;
}
} else {
return false;
}
imap_close($this->inbox);
}
public function unseen($number = false) {
/* grab emails */
$emails = imap_search($this->inbox,'UNSEEN');
/* if emails are returned, cycle through each... */
if($emails) {
/* statement that tells that emails exist */
$this->emailsexists = true;
/* put the newest emails on top */
rsort($emails);
/* Start the counter */
$x = 0;
/* Open up the accordion */
$this->emailarray.= '<div id="accordion">';
/* for every email... */
foreach($emails as $email) {
/* get information specific to this email */
$overview = imap_fetch_overview($this->inbox,$email,0);
$structure = imap_fetchstructure($this->inbox, $email);
$message = imap_fetchbody($this->inbox,$email,1,FT_PEEK);
if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
$part = $structure->parts[1];
$message = imap_fetchbody($this->inbox,$email,2,FT_PEEK);
}
/* escape and decode the mimeheaders */
$subject = escape(str_replace("_"," ", mb_decode_mimeheader($overview[0]->subject)));
/* decode and put the subject into the accordion header */
$this->emailarray.= '<h3>'.html_entity_decode(escape($subject)).'</h3>';
$this->emailarray.= '<div>';
$this->emailarray.= '<div class="btn-group pull-right">';
$this->emailarray.= '<span class="glyphicon glyphicon-share-alt text-success"></span>';
$this->emailarray.= '<span class="glyphicon glyphicon-send text-success"></span>';
$this->emailarray.= '<span class="glyphicon glyphicon-fire text-danger"></span>';
$this->emailarray.= '</div>';
$this->emailarray.= '<p>';
/* decode the email body using the built in quoted_printable_decode function */
$this->emailarray.= quoted_printable_decode($message);
$this->emailarray.= '</p>';
$this->emailarray.= '</div>';
/* if the counter reaches a certain number, break out and continue the script */
$x++;
if ($number) {
if ($x >= $number) {
break;
}
}
}
/* close off the accordion */
$this->emailarray.= '</div>';
/* If no emails are found return a message */
} else {
echo "No emails";
}
/* close the imap connection */
imap_close($this->inbox);
}
}
I found that if i connect to the Trash and then use an asterix to get the last message it works as intended.
public function undo($email) {
// check if message id exists and is numeric
if ($email !== '' && is_numeric($email)) {
// set hostname to trash
$hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/Trash';
$this->inbox = imap_open($hostname,$this->username,$this->password) or die('Cannot connect to Gmail: ' . imap_last_error());
// return true if the message was moved
if (imap_mail_move($this->inbox, '*', 'Inbox')) {
return true;
} else {
return false;
}
} else {
return false;
}
imap_close($this->inbox,CL_EXPUNGE);
}
Move mail INBOX To TRASH THROUGH IMAP using node-imap.
const Imap = require("imap");
const mailBox = new Imap({
host: "imap.gmail.com",
password: "password",
port: 993,
user: "email",
tls: true,
connTimeout: 30000,
authTimeout: 30000,
keepalive: false,
tlsOptions: {
rejectUnauthorized: false,
},
});
mailBox.once("error", console.error);
mailBox.once("ready", () => {
mailBox.openBox("INBOX", false, (error, box) => {
if (error) throw error;
mailBox.search(
[
// "UNSEEN",
["SUBJECT", "When to say 'sorry' at work"],
["FROM", "taco#trello.com"]
],
(error, results) => {
if (error) throw error;
console.log("results",results);
for (const uid of results) {
const mails = mailBox.fetch(uid, {
bodies: ""
// markSeen: true
});
mails.once("end", () => mailBox.end());
mails.on("message", (message, seq) => {
console.log('message',message);
message.on("body", stream => {
console.log("results123456--------",uid);
let buffer = "";
stream.on("data", chunk => (buffer += chunk.toString("utf8")));
stream.once("end", () => mailBox.move(uid, "[Gmail]/Trash"));
});
});
}
}
);
});
});
mailBox.connect();

Categories