I am working on a Cron job script that collects Unseen emails from Google imap server to my database. But sometimes, some emails are not read, so they don't get saved into the database.
Here is the code:
$connection = imap_open ($imapaddressandbox, $imapuser, $imappassword)
or die("Can't connect to '" . $imapaddress .
"' as user '" . $imapuser .
"' with password '" . $imappassword .
"': " . imap_last_error());
$m_search=imap_search ($connection, 'UNSEEN');
if($m_search === false){
email_log("No New Messages ");
}
It seams like for some reason some emails get skipped although they are unread.
Can anyone have an idea why?
Just a note, email is like me#mydomain.com, but using google email.
Thanks
use
imap_open($incoming_server,$username, $password,FT_PEEK);
Try
if (!$m_search) {
// No new mails found
}
Related
So my current code is this in PHP:
$mailbox = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'example#gmail.com', 'password') or die('Cannot connect to Gmail: ' . imap_last_error());
This code allows PHP to see my email inbox using IMAP and it works fine.
Now my question is, how to make it so that It checks all the new emails in my inbox and outputs "n New Emails!" and marks each of them as seen automatically.
I would really appreciate It If someone were to shed some light on this as I am very new to IMAP and handling emails programmatically in general.
You could use a combination of imap_search1 and imap_setflag_full2
$mailbox = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'example#gmail.com', 'password');
// This gives an array of message IDs for all messages that are UNSEEN
$unseenMessages = imap_search($mailbox, 'UNSEEN');
// Keep in mind that imap_search returns false, if it doesn't find anything
$unseenCount = !$unseenMessages ? 0 : count($unseenMessages);
echo "$unseenCount New Emails!\n";
if ($unseenMessages) {
// The second parameter of imap_setflag_full function is a comma separated string of message IDs
// It can also be a range eg 1:5, which would be the same as 1,2,3,4,5
imap_setflag_full($mailbox, implode(',', $unseenMessages), '\Seen');
}
I am currently using TeamSpeak's ServerQuery feature to display all channels and connected users via PHP on my website. Right now it looks like this: (apologies for the crude usernames/channel titles)
It works to display channels and user names. However, I do not want it to do this.
Instead of showing all channels and user names that have connected, I would prefer it just to fetch the amount of users that are currently connected and the maximum amount of users that can connect and display them as seen above. (Along with the server status, i.e online or offline.)
This is the API I am using to connect to the TeamSpeak server via PHP.
Discovered a solution by myself!
Framework
TeamSpeak PHP Framework.
We only really need the libraries folder for this situation, so feel free to delete the docs and images folders.
--
PHP (Thanks to SilentStorm)
<?php
date_default_timezone_set("Europe/London");
require_once("libraries/TeamSpeak3/TeamSpeak3.php");
TeamSpeak3::init();
header('Content-Type: text/html; charset=utf8');
$status = "offline";
$count = 0;
$max = 0;
try {
$ts3 = TeamSpeak3::factory("serverquery://<USER>:<PASSWORD>#<SERVER IP>:<QUERY PORT>/?server_port=<SERVER PORT>&use_offline_as_virtual=1&no_query_clients=1");
$status = $ts3->getProperty("virtualserver_status");
$count = $ts3->getProperty("virtualserver_clientsonline") - $ts3->getProperty("virtualserver_queryclientsonline");
$max = $ts3->getProperty("virtualserver_maxclients");
}
catch (Exception $e) {
echo '<div style="background-color:red; color:white; display:block; font-weight:bold;">QueryError: ' . $e->getCode() . ' ' . $e->getMessage() . '</div>';
}
echo '<span class="ts3status">TS3 Server Status: ' . $status . '</span><br/><span class="ts3_clientcount">Clients online: ' . $count . '/' . $max . '</span>';
?>
Customise
- ServerQuery username (Can be found in TeamSpeak, Tools -> ServerQuery Login
- ServerQuery password (Can be found in TeamSpeak, Tools -> ServerQuery Login
- The server's IP address
- The ServerQuery port (Default - 10011)
- The server's port (Default - 9987)
Save the file appropriately, in the same directory that includes the libraries folder. To display it on a page put the code:
<?php
include('path/to/file/filename.php');
?>
This will then display the TeamSpeak server information on the page! Hope I could help.
i want to send email to my 600 clients through php email. but the loop works till 20 contacts, after that it show 500 internal server error...
i am using go daddy server.
<?php
for($x=1;$x<=600;$x++)
{
$con = mysqli_connect("host","database","password");
if (!$con){die('Could not connect: ' . mysqli_error($con));}
mysqli_select_db($con,"database");
$sql="SELECT email FROM emails Where id = ".$x;
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$to = $row['email'];
if ($to == "NULL")
{
}
else
{
echo $row['email'];
mysqli_close($con);
// mail($to,"subject","message");
sleep(2);
}
}
?>
Trying to send unlimited mails in a short period time is restricted by most of the hosting servers. If u continuously try to do this, they may even block ur hosting account temporarily or permanent.
But if u want to send unlimited mails there are lot of third party mail services available. U can use those to send unlimited mails.
I'm using the following code which you may recognise from php.net to delete all the emails in my inbox:
function deleteEmails($emailAddress)
{
// connect to gmail with your credentials
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = $emailAddress; # e.g somebody#gmail.com
$password = '****************';
// try to connect
$inbox = imap_open($hostname,$username,$password) or die('Cannot download information: ' . imap_last_error());
$check = imap_mailboxmsginfo($inbox);
echo "Messages before delete: " . $check->Nmsgs . "<br />\n";
imap_delete($inbox, '1:*');
$check = imap_mailboxmsginfo($inbox);
echo "Messages after delete: " . $check->Nmsgs . "<br />\n";
imap_expunge($inbox);
$check = imap_mailboxmsginfo($inbox);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";
imap_close($inbox);
}
which helps deal with a clog in my account that happens on occasion if I let it get out of hand. However, what I really need is for it to delete all my email except the most recent one. I have tried to change imap_delete($inbox, '1:*'); to imap_delete($inbox, '2:*'); but this just caused it to not work at all.
What am I missing?
EDIT
With advise below I tried the following:
imap_delete($inbox, "2:$check->Nmsgs");
But interestingly it deleted all but one of the 'conversations' but in gmail 'conversations' can max out at 61 emails! I'm not sure how to get around this. Also, the deleted ones returned after a few mins...
I know gmail does some interesting stuff with just tagging it differently and putting it in an All Mail folder, since there aren't actual "Folders" like on most IMAP systems. Have you tried just giving it a range, such as
imap_delete($inbox,2:$check->Nmsgs);
If that doesn't work, you might have to just loop through marking them for deletion and then expunge after that.
I found the issue. Gmail by default is set up using 'conversations' meaning any emails coming in with the same subject get grouped together. This screws with everything but it can be turned off in gmail settings. Once done I needed to make sure I was deleting all but the most recent. using imap_delete($inbox,2:$check->Nmsgs); deleted all but the oldest. so the following code did it for me:
$emails = ($check->Nmsgs)-1;
imap_delete($inbox, '1:' . $emails);
so that I was getting the numbers but was deleting all up to the last one to come in (the most recent)
Done
I am hoping that there is a standard class/php script that we can use for the "forgot password" functionality. It seems almost every website has one, and I'd like to reduce the development time on it.
It appears that a common approach is:
click on Forgot password
User receives via email a "reset password" link
Click on the link allows typing in "new password" "retype password"
life is good
I don't want to do it from scratch, hoping someone who has thought through any nuances can point me to pre-existing code. It would seem that this is a pretty standardized.
All: got some responses, but I'm hoping perhaps someone can recommend a pretty standard class or CMS that meets generally accepted security guidelines.
I use my own scripts for password resetting.
I create a table to store a user_id, a random key and a time that the password reset initiated:
// query is my own SQLite3 wrapper function which ensures I have a valid database connection then executes the SQL.
// I would imagine small changes will be needed to the SQL for MY SQL.
query("create table reset_password (user_id integer not null default 0, key text not null default '', time integer not null default 0)");
query("create unique index reset_password_user_id on reset_password (user_id)");
query("create index reset_password_key on reset_password (key)");
Then when a password needs to be reset, the following code is called:
// $user_id must be an integer that matches a valid user's ID.
function reset_password($user_id) {
query("delete from reset_password where user_id = $user_id");
$key = substr(base64_encode(crypt('', '')), 0, 32);
query("insert into reset_password values ($user_id, '$key', " . time() . ")");
// fetch is my own wrapper function to fetch a row from the query.
$f = fetch(query("select username from users where id = $user_id"));
// smtp is my own function, you will probably want to use the php mail function.
smtp(
"do-not-reply#example.com", // sender
$f['username'], // recepient
"From: The example.com Web Site <do-not-reply#example.com>\r\n" . // email headers
"To: {$f['username']} <{$f['username']}>\r\n" . // actual email address <put a nice friendly name in here if you have the the information>
'Subject: Reset Password' . "\r\n" .
"\r\n" .
"Hello\r\n" . // email body
"\r\n" .
"A request has been made to reset your example.com web site password.\r\n" .
"\r\n" .
"To complete the request, click on the following link within 48 hours of the transmision of this email and follow the on screen instructions.\r\n" .
"\r\n" .
/// URL is defined as the root of the URL used in the email, in this example it would be "http://example.com/"
URL . "index.php?page=reset-password&user_id=" . urlencode($user_id) . "&key=" . urlencode($key) . "\r\n" .
"\r\n" .
"Kind regards,\r\n" .
"\r\n" .
"The example.com Web Site"
);
}
When the link in the email is clicked a page is displayed which contains the following:
// form, input_hidden, table, tr, td, label, input_password and input_submit are my own wrappers which return the appropriate HTML with escaped values where required.
echo
form('reset-password/ok',
input_hidden('user_id', $_GET['user_id']) .
input_hidden('key', $_GET['key']) .
table(
tr(
td(label('New Password')) .
td(input_password('new_password', ''))
) .
tr(
td(label('Confirm Password')) .
td(input_password('confirm_password', ''))
)
) .
input_submit('ok', 'OK')
);
When the above form is submitted, the following is executed:
// The reset_password_message function displays the message to the user.
if (!isset($_POST['user_id'])) {
reset_password_message('You must enter a user ID. Please try again.');
} else if (!isset($_POST['key'])) {
reset_password_message('You must enter a key. Please try again.');
} else if (!isset($_POST['new_password']) || !$_POST['new_password']) {
reset_password_message('You must enter a new password. Please try again');
} else if (!isset($_POST['confirm_password']) || $_POST['new_password'] != $_POST['confirm_password']) {
reset_password_message('The new password and the confirmation do not match. Please try again.');
} else if (!$f = fetch(query("select time from reset_password where user_id = " . (integer)$_POST['user_id'] . " and key = '" . escape($_POST['key']) . "'"))) {
reset_password_message('The user ID and key pair are invalid. Please try again.');
} else if ($f['time'] < time() - 60 * 60 * 24 * 2) { // 60 seconds * 60 minutes * 24 hours * 2 days (48 hours as explained in the email sent to the user above).
reset_password_message('The user ID and key pair have expired. Please try again.');
} else {
query("update users set password = '" . crypt($_POST['new_password']) . "' where id = " . (integer)$_POST['user_id']);
reset_password_message('Your password has been reset. Please login.');
}
You're welcome to use this code instead of "rolling your own", but you will need to make a few changes or add a few functions to make it complete.
You can steal it from a wide variety of frameworks/CMSs. Drupal, Kohana, etc...