Skip to content

Instantly share code, notes, and snippets.

@eli-oat
Forked from cfenollosa/email-deadlines.php
Created January 14, 2016 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eli-oat/635b144e41be4825afc2 to your computer and use it in GitHub Desktop.
Save eli-oat/635b144e41be4825afc2 to your computer and use it in GitHub Desktop.
Postpone your own email
#!/usr/bin/env php
<?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: http://cfenollosa.com/blog/a-simple-script-to-postpone-your-own-email.html
// Please leave comments and feedback for bugs and ideas!
// Modify these
$hostname='{imap.gmail.com:993/imap/ssl/novalidate-cert}';
$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) {
sleep(30);
$inbox = imap_open($hostname, $username, $gmPassword, NULL, 1);
$retry++;
}
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);
}
}
imap_close($inbox);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment