<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: email code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 17 May 2008 02:59:36 GMT</pubDate>
    <description>DZone Snippets: email code</description>
    <item>
      <title>rails sendmail settings</title>
      <link>http://snippets.dzone.com/posts/show/5378</link>
      <description>&lt;code&gt;&lt;br /&gt;config.action_mailer.raise_delivery_errors = true&lt;br /&gt;ActionMailer::Base.delivery_method = :sendmail&lt;br /&gt;ActionMailer::Base.sendmail_settings = {&lt;br /&gt;    :location       =&gt; '/usr/sbin/sendmail',&lt;br /&gt;    :arguments      =&gt; '-i -t'&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 17 Apr 2008 13:23:44 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5378</guid>
      <author>indiehead (John)</author>
    </item>
    <item>
      <title>process email files like unix find</title>
      <link>http://snippets.dzone.com/posts/show/5248</link>
      <description>I call this program whitelist. It lets you run a command on a bunch of files depending on whether the file is an email and has a from address in a whitelist.&lt;br /&gt;&lt;br /&gt;It's useful for maintaining whitelisted mailboxes and analysing mailboxes. With a few more tests it might be a generically useful tool.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/bin/python&lt;br /&gt;# Copyright (C) 2008 by Tapsell-Ferrier Limited&lt;br /&gt;&lt;br /&gt;# This program is free software; you can redistribute it and/or modify&lt;br /&gt;# it under the terms of the GNU General Public License as published by&lt;br /&gt;# the Free Software Foundation; either version 2, or (at your option)&lt;br /&gt;# any later version.&lt;br /&gt;&lt;br /&gt;# This program is distributed in the hope that it will be useful,&lt;br /&gt;# but WITHOUT ANY WARRANTY; without even the implied warranty of&lt;br /&gt;# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the&lt;br /&gt;# GNU General Public License for more details.&lt;br /&gt;&lt;br /&gt;# You should have received a copy of the GNU General Public License&lt;br /&gt;# along with this program; see the file COPYING.  If not, write to the&lt;br /&gt;# Free Software Foundation, Inc.,   51 Franklin Street, Fifth Floor,&lt;br /&gt;# Boston, MA  02110-1301  USA&lt;br /&gt;&lt;br /&gt;import commands&lt;br /&gt;import email.Parser&lt;br /&gt;import sys&lt;br /&gt;import re&lt;br /&gt;import getopt&lt;br /&gt;import os&lt;br /&gt;import os.path&lt;br /&gt;&lt;br /&gt;try:&lt;br /&gt;    from email.utils import parseaddr&lt;br /&gt;except:&lt;br /&gt;    from rfc822 import parseaddr&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def help():&lt;br /&gt;    print """whitelist.py -h&lt;br /&gt;whitelist.py [-v] [-f whitelist filename] command ; filelist [-]&lt;br /&gt;&lt;br /&gt;Execute the specified command (which must be shell escaped if calling&lt;br /&gt;from shell) on all the files in the filelist or, if - is present in&lt;br /&gt;the filelist, read from stdin (like xargs) whenever the file is an&lt;br /&gt;email that contains a from address specified in the whitelist.&lt;br /&gt;&lt;br /&gt;Like xargs, or find, the command can include {} as a replacement token&lt;br /&gt;for the matched filename.&lt;br /&gt;&lt;br /&gt;The command can also be a header reference, for example:&lt;br /&gt;&lt;br /&gt;  $FROM&lt;br /&gt;&lt;br /&gt;will print the specified mails From address.&lt;br /&gt;&lt;br /&gt;Options:&lt;br /&gt;&lt;br /&gt; -v   specifies that the test is to be negated, executing the action if&lt;br /&gt;      the file does NOT contain a from address in the whiltelist.&lt;br /&gt;&lt;br /&gt; -f   specifies a whitelist, the default is $HOME/.addresses&lt;br /&gt;&lt;br /&gt;For example:&lt;br /&gt;&lt;br /&gt; whitelist.py -f .wlist wc \{} \: maildir/cur/*&lt;br /&gt;&lt;br /&gt;runs wc on each file in maildir/cur with a FROM address matching&lt;br /&gt;something in the whitelist; or:&lt;br /&gt;&lt;br /&gt; find maildir/INBOX/cur -type f | whitelist.py -v mv \{} mailbox/TRASH/cur \; -&lt;br /&gt;&lt;br /&gt;mv's all files in the INBOX with FROMs not matching the whitelist into&lt;br /&gt;a TRASH folder.&lt;br /&gt;&lt;br /&gt;  find maildir/Greylist/new -type f | whitelist.py -v $TO \; -&lt;br /&gt;&lt;br /&gt;displays the TO address of all messages where the from didn't match&lt;br /&gt;the whitelist.&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def read_whitelisted(filename):&lt;br /&gt;    fd = open(filename)&lt;br /&gt;    data = fd.read()&lt;br /&gt;    fd.close()&lt;br /&gt;    return data.split()&lt;br /&gt;&lt;br /&gt;def get_msg(filename):&lt;br /&gt;    fd = open(filename)&lt;br /&gt;    try:&lt;br /&gt;        msg = email.Parser.HeaderParser().parse(fd, True)&lt;br /&gt;        return msg&lt;br /&gt;    finally:&lt;br /&gt;        fd.close()&lt;br /&gt;&lt;br /&gt;action_re = re.compile("\{}")&lt;br /&gt;&lt;br /&gt;def handle(filenames_fn, action, whitelist, negate=False):&lt;br /&gt;    for filename in filenames_fn():&lt;br /&gt;        msg = get_msg(filename)&lt;br /&gt;        realname, addr = parseaddr(msg["from"])&lt;br /&gt;        result = addr in whitelist&lt;br /&gt;&lt;br /&gt;        if negate:&lt;br /&gt;            result = not result&lt;br /&gt;&lt;br /&gt;        if result:&lt;br /&gt;            try:&lt;br /&gt;                m = re.match("\$(.+)", action)&lt;br /&gt;                result = msg[m.group(1)]&lt;br /&gt;            except Exception:&lt;br /&gt;                cmd_str = action_re.sub(filename, action)&lt;br /&gt;                os.system(cmd_str)&lt;br /&gt;            else:&lt;br /&gt;                print result&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def main(args):&lt;br /&gt;    negate = False&lt;br /&gt;    whitelist_filename = os.path.join(os.environ["HOME"], ".addresses")&lt;br /&gt;    opts, args = getopt.getopt(args, "hv")&lt;br /&gt;    for o,a in opts:&lt;br /&gt;        if o == "-h":&lt;br /&gt;            help()&lt;br /&gt;            sys.exit(0)&lt;br /&gt;&lt;br /&gt;        elif o == "-v":&lt;br /&gt;            negate = True&lt;br /&gt;&lt;br /&gt;        elif o == "-f":&lt;br /&gt;            whitelist_filename = a&lt;br /&gt;&lt;br /&gt;    if not os.access(whitelist_filename, os.F_OK):&lt;br /&gt;        print &gt;&gt;sys.stderr, "whitelist.py   -  no whitelist filename\n"&lt;br /&gt;        help()&lt;br /&gt;        sys.exit(1)&lt;br /&gt;&lt;br /&gt;    cmdstr = " ".join(args)&lt;br /&gt;    m = re.match("(.*) ;([ ]*.*)", cmdstr)&lt;br /&gt;    if not m:&lt;br /&gt;        sys.exit(1)&lt;br /&gt;&lt;br /&gt;    cmd = m.group(1)&lt;br /&gt;    files = m.group(2).strip().split(" ")&lt;br /&gt;&lt;br /&gt;    def ffn():&lt;br /&gt;        for f in files:&lt;br /&gt;            if f == "-":&lt;br /&gt;                for innerf in sys.stdin:&lt;br /&gt;                    yield innerf.strip()&lt;br /&gt;            else:&lt;br /&gt;                yield f&lt;br /&gt;        return&lt;br /&gt;&lt;br /&gt;    whitelist = read_whitelisted(whitelist_filename)&lt;br /&gt;    handle(ffn, cmd, whitelist, negate)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;if __name__ == "__main__":&lt;br /&gt;    main(sys.argv[1:])&lt;br /&gt;&lt;br /&gt;# End&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 18 Mar 2008 16:54:19 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5248</guid>
      <author>nicferrier (Nic Ferrier)</author>
    </item>
    <item>
      <title>Ruby SMTP Server - Save to Database</title>
      <link>http://snippets.dzone.com/posts/show/5152</link>
      <description>This was something I've searched for in the past but have yet to find. It's a super simple server and I'm sure there's a few bugs left in it, but the idea is simple and in my opinion, necessary. It's easy to send email from websites, but receiving it still seems dubious.&lt;br /&gt;&lt;br /&gt;I've simply used Peter's(http://snippets.dzone.com/user/peter) ultra simplistic SMTP server and routed the email to a database table called "Emails" via ActiveRecord. It's running GServer so it should be able to handle a decent load. Like I mentioned earlier, it's probably still got some bugs, but it's a decent start.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;require 'gserver'&lt;br /&gt;require 'rubygems'  &lt;br /&gt;require 'active_record'  &lt;br /&gt;require 'yaml'&lt;br /&gt;   &lt;br /&gt;dbconfig = YAML::load_file(File.dirname(__FILE__) + '/config/database.yml')&lt;br /&gt;ActiveRecord::Base.establish_connection(dbconfig['development']) &lt;br /&gt;&lt;br /&gt;class Email &lt; ActiveRecord::Base   &lt;br /&gt;end &lt;br /&gt;&lt;br /&gt;class SMTPServer &lt; GServer&lt;br /&gt;  def serve(io)&lt;br /&gt;    @data_mode = false&lt;br /&gt;    @email_message = ""&lt;br /&gt;    puts "Connected"&lt;br /&gt;    io.print "220 hello\r\n"&lt;br /&gt;    loop do&lt;br /&gt;      if IO.select([io], nil, nil, 0.1)&lt;br /&gt;	      data = io.readpartial(4096)&lt;br /&gt;	      puts "&gt;&gt;" + data&lt;br /&gt;	      @email_message &lt;&lt; data&lt;br /&gt;	      ok, op = process_line(data)&lt;br /&gt;	      break unless ok&lt;br /&gt;	      puts "&lt;&lt;" + op&lt;br /&gt;	      io.print op&lt;br /&gt;      end&lt;br /&gt;      break if io.closed?&lt;br /&gt;    end&lt;br /&gt;    db_insert(@email_message)&lt;br /&gt;    io.print "221 bye\r\n"&lt;br /&gt;    io.close&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def process_line(line)&lt;br /&gt;    if (@data_mode) &amp;&amp; (line.chomp =~ /^\.$/)&lt;br /&gt;      @data_mode = false&lt;br /&gt;      return true, "220 OK\r\n"&lt;br /&gt;    elsif @data_mode&lt;br /&gt;      return true, ""&lt;br /&gt;    elsif (line =~ /^(HELO|EHLO)/)&lt;br /&gt;      return true, "220 and..?\r\n"&lt;br /&gt;    elsif (line =~ /^QUIT/)&lt;br /&gt;      return false, "bye\r\n"&lt;br /&gt;    elsif (line =~ /^MAIL FROM\:/)&lt;br /&gt;      return true, "220 OK\r\n"&lt;br /&gt;    elsif (line =~ /^RCPT TO\:/)&lt;br /&gt;      return true, "220 OK\r\n"&lt;br /&gt;    elsif (line =~ /^DATA/)&lt;br /&gt;      @data_mode = true&lt;br /&gt;      return true, "354 Enter message, ending with \".\" on a line by itself\r\n"&lt;br /&gt;    else&lt;br /&gt;      return true, "500 ERROR\r\n"&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;  def db_insert(email)&lt;br /&gt;    mail_from = (/^MAIL FROM\:&lt;(.+)&gt;.*$/).match(email)[1]&lt;br /&gt;    rcpt_to = (/^RCPT TO\:&lt;(.+)&gt;.*$/).match(email)[1]&lt;br /&gt;    subject = (/^Subject\: (.+)$/).match(email)[1]&lt;br /&gt;    Email.create(:mail_from =&gt; mail_from, :rcpt_to =&gt; rcpt_to, :subject =&gt; subject, :email =&gt; email)&lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;a = SMTPServer.new(25)&lt;br /&gt;a.start&lt;br /&gt;a.join&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 19 Feb 2008 07:56:06 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5152</guid>
      <author>markpercival (Mark Percival)</author>
    </item>
    <item>
      <title>Email in Bash</title>
      <link>http://snippets.dzone.com/posts/show/4868</link>
      <description>//Bash email&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/bin/bash&lt;br /&gt;&lt;br /&gt;function email&lt;br /&gt;{&lt;br /&gt;echo "this is a test" | mail -s "test" "$1"&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;if [ "$1" = "" ]; then&lt;br /&gt;echo "nothing in param"&lt;br /&gt;else&lt;br /&gt;echo "sending mail"&lt;br /&gt;&lt;br /&gt;#emailing attachment&lt;br /&gt;#uuencode statsNbaAllStarSim statssim | mail -s "test attachement" atayebali@foxsports.com&lt;br /&gt;#uuencode &lt;filename that will be send&gt; &lt;name for attached file that is sent&gt; |&lt;br /&gt;&lt;br /&gt;#passing the param to function&lt;br /&gt;email $1&lt;br /&gt;fi&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 11 Dec 2007 00:58:01 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4868</guid>
      <author>aniline (Aniline)</author>
    </item>
    <item>
      <title>PHP : Comprobar e-mail v&#225;lido / Check valid e-mail</title>
      <link>http://snippets.dzone.com/posts/show/4346</link>
      <description>Comprobar e-mail v&#225;lido / Check valid e-mail&lt;br /&gt;C&#243;digo fuente / Source code :&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;function esEmailValido($email)&lt;br /&gt;{&lt;br /&gt;    if (ereg("^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@([_a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]{2,200}\.[a-zA-Z]{2,6}$", $email ) )&lt;br /&gt;	{&lt;br /&gt;       return true;&lt;br /&gt;    }&lt;br /&gt;	else&lt;br /&gt;	{&lt;br /&gt;       return false;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 23 Jul 2007 11:11:17 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4346</guid>
      <author>Ricardo (Ricardo m. Garc&#237;a)</author>
    </item>
    <item>
      <title>PHP: Email All Form Values</title>
      <link>http://snippets.dzone.com/posts/show/4338</link>
      <description>If you need a very basic contact form and don't want to write extra code for putting the value of each field into the email, you can use this basic email. It works best if you name your form fields something legible, such as First_Name&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;if (isset($_POST['Submit'])) {&lt;br /&gt;	// Prepare message&lt;br /&gt;	$msg = "Time: " . date("m/d/y g:ia", time()) . "\n";&lt;br /&gt;	foreach ($_POST as $field=&gt;$value) {&lt;br /&gt;		if ($field != "submit") $msg .= $field . ": " . $value . "\n";&lt;br /&gt;	}&lt;br /&gt;	&lt;br /&gt;	if (mail("TOEMAIL", "SUBJECT", $msg, "From: FROM_NAME &lt;FROM@ADDRESS.com&gt;")) {&lt;br /&gt;		// Email was sent&lt;br /&gt;	} else {&lt;br /&gt;		// Erro sending email&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 19 Jul 2007 23:09:40 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4338</guid>
      <author>cornerblue (CornerBLUE, Inc.)</author>
    </item>
    <item>
      <title>email validation regex</title>
      <link>http://snippets.dzone.com/posts/show/4294</link>
      <description>&lt;code&gt;&lt;br /&gt;/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/ 		&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 12 Jul 2007 13:02:21 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4294</guid>
      <author>sbnet (Stephane BRUN)</author>
    </item>
    <item>
      <title>Check email in html form</title>
      <link>http://snippets.dzone.com/posts/show/4290</link>
      <description>// description of your code here&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt; &lt;script type="text/javascript"&gt;&lt;br /&gt;        function check_email(email_id,err_id){&lt;br /&gt;            emailRegExp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$/;&lt;br /&gt;            var err_mail='Email addres incorect!';&lt;br /&gt;            if(emailRegExp.test(document.getElementById(email_id).value)){&lt;br /&gt;                alert('true');&lt;br /&gt;                return true;&lt;br /&gt;            }else{&lt;br /&gt;                document.getElementById(err_id).innerHTML=err_mail;&lt;br /&gt;                alert(err_mail);&lt;br /&gt;                return false;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    &lt;/script&gt;&lt;br /&gt;&lt;br /&gt;        &lt;span id="err_msg" style="color: red;"&gt;&lt;/span&gt;&lt;br /&gt;    &lt;form id="myForm" name="myForm" action="./register.php" method="post" onsubmit="return check_email('email','err_msg');"&gt;&lt;br /&gt;        &lt;input type="text" name="email" id="email"/&gt;&lt;br /&gt;        &lt;input  type="submit" name="send" value="Send" /&gt;&lt;br /&gt;    &lt;/form&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 12 Jul 2007 10:04:11 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4290</guid>
      <author>bublik (Voloshin Ruslan)</author>
    </item>
    <item>
      <title>Using POP3 to Retrieve Email for Rails App</title>
      <link>http://snippets.dzone.com/posts/show/4214</link>
      <description>Put this in a file called "inbox" in the scripts/ directory of your Rails app. change the host, username, and password to match.&lt;br /&gt;&lt;br /&gt;Set up a cron job to run this script every so often (frequency depends on your needs).&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/bin/env ruby&lt;br /&gt;&lt;br /&gt;require 'net/pop'&lt;br /&gt;require File.dirname(__FILE__) + '/../config/environment'&lt;br /&gt;&lt;br /&gt;logger = RAILS_DEFAULT_LOGGER&lt;br /&gt;&lt;br /&gt;logger.info "Running Mail Importer..." &lt;br /&gt;Net::POP3.start("localhost", nil, "username", "password") do |pop|&lt;br /&gt;  if pop.mails.empty?&lt;br /&gt;    logger.info "NO MAIL" &lt;br /&gt;  else&lt;br /&gt;    pop.mails.each do |email|&lt;br /&gt;      begin&lt;br /&gt;        logger.info "receiving mail..." &lt;br /&gt;        Notifier.receive(email.pop)&lt;br /&gt;        email.delete&lt;br /&gt;      rescue Exception =&gt; e&lt;br /&gt;        logger.error "Error receiving email at " + Time.now.to_s + "::: " + e.message&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;logger.info "Finished Mail Importer." &lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 26 Jun 2007 17:40:30 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4214</guid>
      <author>timmorgan (Tim Morgan)</author>
    </item>
    <item>
      <title>Quick and dirty email server checker, python</title>
      <link>http://snippets.dzone.com/posts/show/4024</link>
      <description>// description of your code here&lt;br /&gt;This sends an email from a gmail account with a GUID for the subject to another email account, and then writes this GUID to file. On the other end, the other half of the program checks the GUID in the recieved message and matches it to the GUID in the file to verify that the message has been recieved. I schedule the sender to run every ten minutes, and the reciever/checker to run every minute. The reciever has a threshold value of 20 so if it has checked 20 times and not recieved the email it sends an IM to my gmail account. Whew is that contrived or what.  &lt;br /&gt;&lt;code&gt;&lt;br /&gt;// First part, email sender, schedule to run every 10 minutes or so&lt;br /&gt;// this uses GUID from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163604&lt;br /&gt;&lt;br /&gt;from smtplib import SMTP&lt;br /&gt;from socket import sslerror         #if desired&lt;br /&gt;import Guid&lt;br /&gt;import os&lt;br /&gt;&lt;br /&gt;guidSubj = Guid.generate()&lt;br /&gt;guidBod1 = Guid.generate()&lt;br /&gt;guidBod2 = Guid.generate()&lt;br /&gt;&lt;br /&gt;if not os.path.exists("sent.txt"):   #check whether the file exists, if not create it&lt;br /&gt;    fileHandle = open('sent.txt','w')&lt;br /&gt;    fileHandle.write (guidSubj)&lt;br /&gt;    fileHandle.close()&lt;br /&gt;    server = SMTP('smtp.gmail.com',587)&lt;br /&gt;    server.set_debuglevel(1) # or 1 for verbosity&lt;br /&gt;    server.ehlo('user@gmail.com')&lt;br /&gt;    server.starttls()&lt;br /&gt;    server.ehlo('user@gmail.com')  # say hello again&lt;br /&gt;    server.login('user@gmail.com', 'password')&lt;br /&gt;    # i have a suspicion that smptlib does not add the required newline dot newline so i do it myself&lt;br /&gt;    server.sendmail('user@gmail.com', 'user@place.com', "Subject:Ping," + guidSubj + '\n\n' + guidBod1 + '\n\n' + guidBod2 + '\n.\n')&lt;br /&gt;    # next line generates the ignorable socket.sslerror&lt;br /&gt;    server.quit()&lt;br /&gt;&lt;br /&gt;// Second email checker/reciever, check every minute or so&lt;br /&gt;# This script is a helper to clean POP3 mailboxes&lt;br /&gt;# containing malformed mails that hangs MUA's, that &lt;br /&gt;# are too large, or whatever...&lt;br /&gt;#&lt;br /&gt;# It iterates over the non-retrieved mails, prints&lt;br /&gt;# selected elements from the headers and prompt the &lt;br /&gt;# user to delete bogus messages.&lt;br /&gt;#&lt;br /&gt;# Written by Xavier Defrang &lt;xavier.defrang@brutele.be&gt;&lt;br /&gt;# &lt;br /&gt;&lt;br /&gt;# &lt;br /&gt;import getpass, poplib, re, os, fileinput, sys, xmpp&lt;br /&gt;&lt;br /&gt;def sendIM(toAddress=None):&lt;br /&gt;    &lt;br /&gt;    # Google Talk constants&lt;br /&gt;    FROM_GMAIL_ID = "user@gmail.com"&lt;br /&gt;    GMAIL_PASS = "pass"&lt;br /&gt;    GTALK_SERVER = "talk.google.com"&lt;br /&gt;    TO_GMAIL_ID = "user@gmail.com"&lt;br /&gt;    jid=xmpp.protocol.JID(FROM_GMAIL_ID)&lt;br /&gt;    cl=xmpp.Client(jid.getDomain(),debug=[])&lt;br /&gt;    if not cl.connect((GTALK_SERVER,5222)):&lt;br /&gt;        raise IOError('Can not connect to server.')&lt;br /&gt;    if not cl.auth(jid.getNode(),GMAIL_PASS):&lt;br /&gt;        raise IOError('Can not auth with server.')&lt;br /&gt;&lt;br /&gt;    cl.send( xmpp.Message( TO_GMAIL_ID ,"Fix your email!" ) )&lt;br /&gt;    cl.disconnect()&lt;br /&gt;&lt;br /&gt;# Change this to your needs&lt;br /&gt;POPHOST = "131.0.0.1"&lt;br /&gt;POPUSER = "user"&lt;br /&gt;POPPASS = "pass"&lt;br /&gt;&lt;br /&gt;# How many lines of message body to retrieve&lt;br /&gt;MAXLINES = 10&lt;br /&gt;&lt;br /&gt;# Headers we're actually interrested in&lt;br /&gt;rx_headers  = re.compile(r"^(Subject)")&lt;br /&gt;&lt;br /&gt;try:&lt;br /&gt;&lt;br /&gt;    # Connect to the POPer and identify user&lt;br /&gt;    pop = poplib.POP3(POPHOST)&lt;br /&gt;    pop.user(POPUSER)&lt;br /&gt;&lt;br /&gt;    if not POPPASS:&lt;br /&gt;        # If no password was supplied, ask for it&lt;br /&gt;        POPPASS = getpass.getpass("Password for %s@%s:" % (POPUSER, POPHOST))&lt;br /&gt;&lt;br /&gt;    # Authenticate user&lt;br /&gt;    pop.pass_(POPPASS)&lt;br /&gt;&lt;br /&gt;    # Get some general informations (msg_count, box_size)&lt;br /&gt;    stat = pop.stat()&lt;br /&gt;&lt;br /&gt;    bye = 0&lt;br /&gt;    count_del = 0&lt;br /&gt;    &lt;br /&gt;    #for n in range(stat[0]):&lt;br /&gt;&lt;br /&gt;    msgnum = stat[0]&lt;br /&gt;&lt;br /&gt;    # Retrieve headers&lt;br /&gt;    response, lines, bytes = pop.top(msgnum, MAXLINES)&lt;br /&gt;&lt;br /&gt;    # Print message info and headers we're interrested in&lt;br /&gt;    test = "".join(filter(rx_headers.match, lines))&lt;br /&gt;    num = test.split(',')&lt;br /&gt;    out = num[1]&lt;br /&gt;    &lt;br /&gt;&lt;br /&gt;    #Read the sent.txt file to get the GUID&lt;br /&gt;    fileHandle = open ( 'sent.txt' )&lt;br /&gt;    sentGuid = fileHandle.readline()&lt;br /&gt;    print sentGuid&lt;br /&gt;    fileHandle.close()&lt;br /&gt;    &lt;br /&gt;    if out == sentGuid:&lt;br /&gt;        print "They match!! yay"&lt;br /&gt;        pop.dele(msgnum)&lt;br /&gt;        print "Message %d marked for deletion" % msgnum&lt;br /&gt;        count_del += 1&lt;br /&gt;        #delete the retry.txt and sent.txt file&lt;br /&gt;        os.remove("retry.txt")&lt;br /&gt;        os.remove("sent.txt")&lt;br /&gt;    else:&lt;br /&gt;&lt;br /&gt;        #There are no messages yet, so we will increment the retry value&lt;br /&gt;        if not os.path.exists("retry.txt"):&lt;br /&gt;            fileHandle = open ( 'retry.txt','a')&lt;br /&gt;            fileHandle.write('1')&lt;br /&gt;            fileHandle.close()&lt;br /&gt;        else:&lt;br /&gt;        &lt;br /&gt;        fileHandle = open("retry.txt")&lt;br /&gt;        retryValue = fileHandle.readline()&lt;br /&gt;        fileHandle.close()&lt;br /&gt;        #delete the file then recreate with new value&lt;br /&gt;        os.remove('retry.txt')&lt;br /&gt;&lt;br /&gt;        if retryValue != '':&lt;br /&gt;            retryValue = int(retryValue) + 1&lt;br /&gt;            out = str(retryValue)&lt;br /&gt;            fileHandle = open ( 'retry.txt','a')&lt;br /&gt;            fileHandle.write(out)&lt;br /&gt;            fileHandle.close()&lt;br /&gt;            if retryValue &gt; 20 and retryValue &lt;25:&lt;br /&gt;                sendIM()&lt;br /&gt;&lt;br /&gt;   # Summary&lt;br /&gt;    print "Deleting %d message(s) in mailbox %s@%s" % (count_del, POPUSER, POPHOST)&lt;br /&gt;&lt;br /&gt;    # Commit operations and disconnect from server&lt;br /&gt;    print "Closing POP3 session"&lt;br /&gt;    pop.quit()&lt;br /&gt;&lt;br /&gt;except poplib.error_proto, detail:&lt;br /&gt;&lt;br /&gt;    # Fancy error handling&lt;br /&gt;    print "POP3 Protocol Error:", detail&lt;br /&gt;&lt;br /&gt;    #There are no messages yet, so we will increment the retry value&lt;br /&gt;    if not os.path.exists("retry.txt"):&lt;br /&gt;        fileHandle = open ( 'retry.txt','a')&lt;br /&gt;        fileHandle.write('1')&lt;br /&gt;        fileHandle.close()&lt;br /&gt;    else:&lt;br /&gt;        &lt;br /&gt;        fileHandle = open("retry.txt")&lt;br /&gt;        retryValue = fileHandle.readline()&lt;br /&gt;        fileHandle.close()&lt;br /&gt;        #delete the file then recreate with new value&lt;br /&gt;        os.remove('retry.txt')&lt;br /&gt;&lt;br /&gt;        if retryValue != '':&lt;br /&gt;            retryValue = int(retryValue) + 1&lt;br /&gt;            out = str(retryValue)&lt;br /&gt;            fileHandle = open ( 'retry.txt','a')&lt;br /&gt;            fileHandle.write(out)&lt;br /&gt;            fileHandle.close()&lt;br /&gt;            if retryValue &gt; 20 and retryValue &lt;25:&lt;br /&gt;                sendIM()&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 15 May 2007 18:26:50 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4024</guid>
      <author>mellerbeck (Michael Ellerbeck)</author>
    </item>
  </channel>
</rss>
