Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Postpone your own email
#!/usr/bin/env php
// Script to postpone your own email. Parses IMAP folders and moves emails to a folder named "Today"
// Run this from a crontab, for example at 6 AM
// BSD License
// (C) Carlos Fenollosa, 2011-2016
// Read more about this script:
// Please leave comments and feedback for bugs and ideas!
// Modify these
$username = "gmailusername";
$gmPassword = "gmailpassword";
// If you are using the folder structured proposed in the blogpost (Deadlines/Today, Deadlines/Tomorrow, etc.)
// you don't need to modify anything below
// Connect and retry 3 times, because it sometimes fails and we don't want to miss our email
$retry = 0;
$inbox = imap_open($hostname, $username, $gmPassword, NULL, 1);
while (! $inbox && $retry < 3) {
$inbox = imap_open($hostname, $username, $gmPassword, NULL, 1);
if (! $inbox) die('Unable to connect to inbox');
// You may modify these if you use a different folder or date structure
$mboxes = imap_getmailboxes($inbox, $hostname, 'Deadlines/%');
$date = date("Y-m-d");
// Iterate through mailboxes and move email to "Today"
foreach ($mboxes as $mbox) {
$name = $mbox->name;
$name = explode("/", $name);
$name = end($name);
if ($name == $date || $name == "Tomorrow") {
$res = imap_open($mbox->name, $username, $gmPassword, NULL, 1)
or die("Can't open the mailbox " . $mbox->name ."\n");
if ($emails = imap_search($res, "ALL", SE_UID)) {
foreach ($emails as $email) {
imap_mail_move($res, $email, "Deadlines/Today", CP_UID)
or die("Couldn't move some emails, please check it manually\n");
imap_close($res, CL_EXPUNGE);
// Now delete past mailboxes if they are empty
if (strcmp($date, $name) >= 0) {
$res = imap_open($mbox->name, $username, $gmPassword, NULL, 1)
or die("Can't open the mailbox " . $mbox->name ."\n");
if (! $emails = imap_search($res, "ALL", SE_UID)) imap_deletemailbox($res, $mbox->name);
imap_close($res, CL_EXPUNGE);
Copy link

eli-oat commented Jan 14, 2016

I'm excited to give this a shot, especially now that Mailbox is in its sunset. Quick question: will I need to modify $hostname='{}?

I'm not 100% certain what that is. Is it some sort of token/id unique to my gmail account?


Copy link

cfenollosa commented Jan 15, 2016

That's just Gmail's standard IMAP path, it's not tied to any account -- otherwise, I wouldn't have posted there. If you use another provider, change it accordingly.

Copy link

eli-oat commented Jan 15, 2016

Awesome, thanks so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment