Commit a0bb55f0 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
9781565924796
\ No newline at end of file
/*
* JBiff : A simple program to notify you when new mail has arrived,
* specifically using the IMAP protocol. Minimal error
* checking is done to reduce code size.
* To run this code, you will need mail.jar and activation.jar
* from JavaMail and Java Activation Framework (JAF) respectively.
* This code draws heavily on the "Monitoring a Mailbox"
* example in the JavaMail API v 1.1 (Appendix B, page 71)
*
* Author : Chris Ryan (cryan@plugged.net.au)
* Plugged In Software
*
* Copyright (c) 1999 Plugged In Software Pty Ltd.
* Released under the GNU GPL - see http://www.gnu.org/copyleft/gpl.html
*
* Usage : JBiff <username> <password> <host> <mailbox> <frequency, in seconds>
* e.g. java JBiff fnerk foobar mailin inbox 60
*
* inbox refers to the username's default mailbox. It's case
* insensitive.
*/
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class JBiff extends Frame {
// Labels to print some info onto...
public Label display_label;
/*
* Constructor. Creates the various AWT components required
* in the system.
*/
public JBiff() {
// create the simple GUI
display_label = new Label("Please wait...",Label.LEFT);
add(display_label);
pack();
setSize(600,30);
display_label.setSize(600,30);
setTitle("JBiff");
setVisible(true);
// create a handler to close the application
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent w) {
// time to leave
System.exit(0);
}
});
}
public final static void main(String[] args) throws Exception {
// Check that the right number of parameters have been passed
if (args.length != 5) {
System.out.println("JBiff: Monitor the state of an IMAP mailbox.");
System.out.println("usage: java JBiff <username> <password> <host> <mailbox> <frequency (sec)>");
System.exit(1);
}
// Get the parameters from the command line.
String username = args[0];
String password = args[1];
String host = args[2];
String mailbox = args[3]; // use inbox for user's default/main box
int frequency;
try {
frequency = Integer.parseInt(args[4]) * 1000;
} catch (NumberFormatException nfe) {
// bad number, just check every 5 mins.
frequency = 300000;
System.err.println("Your frequency value was bogus. Using 5 minutes instead");
}
// create the gui system
JBiff jbiff = new JBiff();
/*
* Get the system properties. A number of properties can be
* set that are useful to the JavaMail system, including
* mail.host. If mail.host is not set, JavaMail will use
* localhost for the default mail server.
*/
Properties system_properties = System.getProperties();
// get the default JavaMail Session instance
Session session = Session.getDefaultInstance(system_properties,null);
// switch on the session debugging to see what's happening
//session.setDebug(true);
try {
// get the Store object for IMAP
Store store = session.getStore("imap");
// connect to the specified host
store.connect(host,username,password);
// get the Folder for this mailbox
Folder folder = store.getFolder(mailbox);
// ensure we got an existing folder that holds messages
// not a sub folder!
if (folder == null || !folder.exists() || folder.getType() == Folder.HOLDS_FOLDERS) {
System.err.println("Invalid folder, or folder does not exist, or folder holds other folders!");
System.exit(1);
}
// loop forever until the user kills us
while (true) {
/*
* While the operations below can be done on a closed folder,
* it's best to have the folder open, since each operation
* would open & close the folder itself - not efficient!
*
* Another option would be to open the folder and register
* a listener for a MessageCountEvent, however this would
* require the folder to be held continually open in
* READ_WRITE mode. This could conflict with another
* program trying to access the folder, e.g. a mail reader.
*/
folder.open(Folder.READ_ONLY);
// Get the current total number of messages
int total_nr_messages = folder.getMessageCount();
// Get the current number of unread messages
int unread_nr_messages = folder.getUnreadMessageCount();
// get the number of new messages
int new_nr_messages = folder.getNewMessageCount();
// display a status message...
jbiff.display_label.setText("You have "+new_nr_messages+" new messages, "+unread_nr_messages+" unread messages and "+total_nr_messages+" total messages in your mailbox: "+mailbox);
// close the folder, expunging messages is not our problem.
folder.close(false);
// try to sleep for a while
try {
Thread.sleep(frequency);
} catch (InterruptedException ie) {
// just ignore and continue on...
}
}
} catch (MessagingException me) {
System.err.println("Error: "+me.getMessage());
System.exit(1);
}
}
}
/*
* MailOut: a simple program to email a message with an optional file
* attachment using the JavaMail API. Minimal error checking
* is done to reduce code size. To run this code, you will
* need mail.jar and activation.jar from JavaMail and Java
* Activation Framework (JAF) respectively.
*
* Author : Chris Ryan (cryan@plugged.net.au)
* Plugged In Software
*
* Copyright (c) 1999 Plugged In Software
* Released under GNU GPL - see http://www.gnu.org/copyleft/gpl.html
*
* Usage : MailOut <from> <to> <subject> <message_text> [<filename>]
* e.g. java -Dmail.host=mailhost.somewhere.net MailOut me@somewhere.net you@elsewhere.com "Funny Jokes" "See the attached file for some funny jokes." jokes.txt
*
*/
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.io.*;
import java.util.*;
public class MailOut {
public final static void main(String[] args) throws Exception {
// Check that the right number of parameters have been passed
if (!(args.length == 4 || args.length == 5)) {
System.out.println("Usage: MailOut <from> <to> <subject> <message_text> [<filename>]");
System.exit(1);
}
// Get the parameters from the command line.
String from = args[0];
String to = args[1];
String subject = args[2];
String message_text = args[3];
String filename = null;
// set the filename if we've got one.
if (args.length == 5) {
filename = args[4];
}
/*
* Get the system properties. A number of properties can be
* set that are useful to the JavaMail system, including
* mail.host. If mail.host is not set, JavaMail will use
* localhost for the default mail server.
*/
Properties system_properties = System.getProperties();
// get the default JavaMail Session instance
Session session = Session.getDefaultInstance(system_properties,null);
// switch on the session debugging to see what's happening
session.setDebug(true);
try {
// create a new MIME message
Message message = new MimeMessage(session);
/*
* Create Internet style addresses for 'from' & 'to'. The
* assumption is that the default transport being used in
* this session uses RFC822 addresses.
*/
InternetAddress from_internet_address = new InternetAddress(from);
// assume there might be more than one recipient
InternetAddress[] recipients = InternetAddress.parse(to);
// set the 'from' in the message
message.setFrom(from_internet_address);
// set the recipient for the message - assume there might be more than one
message.setRecipients(Message.RecipientType.TO,recipients);
// set the subject for the message
message.setSubject(subject);
// do we have a file to send?
if (filename != null) {
// yes - create the individual parts of the MIME message
// first, create the plain text message body
MimeBodyPart message_body = new MimeBodyPart();
message_body.setContent(message_text,"text/plain");
/*
* next, create the attachment body part.
*
* This requires using the Java Activation Framework to create
* a DataHandler for the file. DataHandler provides a consistent interface
* to data available in many different sources and formats.
* In this case, we're using a local filename, so our DataSource for
* the DataHandler is FileDataSource. A DataSource provides a type
* for the data (file) and access to it - I/O streams. Refer to the
* JAF API for more details.
*/
DataSource file_data_source = new FileDataSource(filename);
DataHandler file_data_handler = new DataHandler(file_data_source);
MimeBodyPart file_attachment = new MimeBodyPart();
file_attachment.setDataHandler(file_data_handler);
// create the Multipart message
Multipart multipart_message = new MimeMultipart();
// add the two bodies to this multipart
multipart_message.addBodyPart(message_body);
multipart_message.addBodyPart(file_attachment);
// set the content type of this message to indicate multipart
message.setContent(multipart_message);
} else {
// no - send a plain message
message.setContent(message_text,"text/plain");
}
// send the message using the default transport for this session
Transport.send(message);
} catch (MessagingException me) {
System.err.println("Error sending message: "+me.getMessage());
System.exit(1);
}
}
}
## Example files for the title:
# Programming Internet Email, by David Wood
[![Programming Internet Email, by David Wood](http://akamaicovers.oreilly.com/images/9781565924796/cat.gif)](https://www.safaribooksonline.com/library/view/title/9780596802585//)
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.
logo.png

3.2 KB

This diff is collapsed.
#!/usr/bin/perl
#
# ------------------------------------------------------------
# script: mboxscrub.pl
# Authors: David Wood (dwood@plugged.net.au)
# Date: 15 January 1999
#
# Purpose: Removes unwanted MIME attachments from an mbox-style
# electronic mailbox.
#
# Usage:
# 1. Adheres to mbox format as most commonly used; therefore may
# introduce extra blank lines at the end of messages into NS mailboxes.
# 2. Uses whatever From_ line found in the original box, whether 'std'
# mbox format or not.
#
# Location of the script: Immaterial to operation.
#
# Copyright (c) 1999 Plugged In Software Pty Ltd.
# Released under the GNU GPL - see http://www.gnu.org/copyleft/gpl.html
#
# Modification History:
#
# ------------------------------------------------------------
# ---------------------------------------------------------
# | MAIN PROGRAM |
# ---------------------------------------------------------
# Packages
use MIME::Parser; # The MIME-Tools Parser (reads/writes
# MIME entities).
use Term::ReadLine; # Readline library (used for user input).
use Getopt::Std; # Used to get command line arguments.
# Set initial variables.
$debug = 0; # Set to non-zero to show debugging info.
$archive = 0; # Set to non-zero if compressing output.
$archiver = '/bin/gzip'; # Program to use for file compression.
$archive_subscript = '.gz'; # File extension for compressed files.
$allowed_length = 0; # Size in bytes above which MIME entities
# are checked.
$mbox_file = ""; # Mailbox filename.
# Variables used with the Term::ReadLine module to get user input:
$term = new Term::ReadLine; # The Readline object.
$length_prompt = "Enter the maximum size in bytes of attachments " .
"you wish to keep. [#/q] ";
$file_prompt = "Please enter the filename of your mailbox. [#/q] ";
$attach_prompt = "Do you wish to delete this attachment? [y/N/q] ";
$OUT = $term->OUT || STDOUT; # Where the terminal output goes.
# Variables related to the current message.
$msg = ""; # Current message contents
$msg_num = 0; # The (linear) number of the current message.
$from_ = ""; # The From_ line for the current message.
$date = localtime(time); # The current time/date.
# The message created when an attachment is deleted.
$info_start = "This attachment has been deleted by $0 on $date. " .
"The original attachment's headers were:\n\n";
# Variables used with MIME-Tools.
my($parser) = new MIME::Parser; # The Parser object.
$parser->output_dir("/tmp"); # The temporary directory to use
# when creating temporary files for
# messages and MIME entities.
# Get command line arguments.
# Options: -l sets the allowed length of attachments,
# -f takes a filename of an mbox.
# -u shows the usage statement.
# -a compresses the output file.
# -d shows debugging information.
getopts('ul:f:ad');
# Return a usage statement if asked.
if ( $opt_u ) {
print<<ENDOFUSAGE;
$0 - an interactive script which allows you to scrub
mbox-style mailboxes of unwanted MIME attachments.
Synopsis: $0 [-u] [-l <length>] [-f <file>]
where <length> is the maximum size of attachments to ignore; and
<file> is the path and filename of an mbox-style mailbox.
ENDOFUSAGE
exit(0);
}
print "\nWelcome to $0!\n\n";
# Turn on debugging reports, if we have been requested to.
if ( $opt_d ) { $debug = 1; }
# If we don't have an allowed attachment length, ask for it.
$allowed_length = $opt_l;
unless ( $allowed_length ) {
$answer = $term->readline($length_prompt);
warn $@ if $@;
$term->addhistory($_) if /\S/;
if ( $answer =~ /^q/i ) {
print "ABORTED by user\n";
exit(0);
} else {
$allowed_length = $answer;
}
}
# If we don't have a mailbox file, ask for it.
$mbox_file = $opt_f;
unless ( $mbox_file ) {
$answer = $term->readline($file_prompt);
warn $@ if $@;
$term->addhistory($_) if /\S/;
if ( $answer =~ /^q/i ) {
print "ABORTED by user\n";
exit(0);
} else {
$mbox_file = $answer;
$mbox_file =~ s/\s$//;
}
}
# Check to see if we can read the input file.
# NOTE that Win32 may place pwd in perl dir...
unless ( -r $mbox_file ) {
print "File $mbox_file is not readable: $! Exiting...\n";
exit(0);
}
if ( $opt_a ) { $archive = 1; }
# Open a mailbox and step through it, one message at a time.
open(MBOX, $mbox_file) or die "Can't open $mbox_file: $!";
# Open a new mailbox file, so that we can write to it.
$newfile = $mbox_file . "_scrubbed";
open(NEWBOX, ">$newfile") or die "Can't open $newfile: $!";
$msg_started = 0;
while(<MBOX>) {
# Read in one message, then write it to a temporary
# file and operate on it.
# The current line.
$line = $_;
if ( ($line =~ /^From /) && (! $msg_started) ) {
# Note that we've found the start of the first message.
$msg_started = 1;
# Keep the From_ line.
$from_ = $line;
} elsif ( ($line =~ /^From - /) && ($msg_started) ) {
# We found the end of a message and the start of
# a new one. We now operate on the completed message.
# Increment the message number.
$msg_num++;
# Operate on current message.
&check_message();
# Set the From_ line for the next message.
$from_ = $line;
} else {
# We're in the middle of reading a message, so just append
# to the current message.
$msg .= $line;
}
} # end while reading MBOX.
# Need to handle the last message read!
$msg_num++;
&check_message();
# Archive (compress) the output mailbox if the user so requested.
if ( $archive ) {
&close_fhs();
`$archiver $newfile`;
$newfile .= $archive_subscript;
}
# Tell the user the filename that was created.
print "\nYour scrubbed mailbox is in the file " . $newfile . ".\n";
&exit();
# ---------------------------------------------------------------
# | Everything below here is a subroutine. |
# ---------------------------------------------------------------
sub abort {
print "\nABORTED by user.\n";
# Delete output file!
&close_fhs();
unlink($newfile);
&clean();
&exit();
} # end sub abort
sub clean {
# Clean up any temporary files left on disk.
#$entity->purge;
# Forget about the current message.
undef($entity);
undef(@parts_to_keep);
undef($msg);
} # end sub clean
sub close_fhs {
# Close the mailboxes.
close(MBOX);
close(NEWBOX);
} # end sub close_fhs
sub exit {
&close_fhs();
# Say Goodbye.
print "Finished.\n\n";
exit(0);
} # end sub exit
sub check_message {
# Operate on a given message, asking the user
# for each large attachment found.
# DBG
print "Message #" . $msg_num . ":\n" if $debug;
$entity = $parser->parse_data($msg) or die
"ERROR: Couldn't parse MIME stream: $!";
# Compute Content-Length headers for each body part.
$entity->sync_headers(Length=>'COMPUTE');
# Prepare some explanatory information.
$summarized = 0;
$head = $entity->head;
$msg_summary = " Message Summary for message #" . $msg_num . ":\n" .
" From : " . $head->get('From') .
" To : " . $head->get('To') .
" Subject: " . $head->get('Subject') .
" Date : " . $head->get('Date') . "\n";
# DBG
print "Dumping skeleton for message #" . $msg_num . ":\n" if $debug;
$entity->dump_skeleton if $debug;
@parts = $entity->parts;
$i = 0;
foreach $part (@parts) {
$part_head = $part->head;
# DBG
print "PART $i:\n\n" if $debug;
print $part_head->print . "\n\n" if $debug;