Solved

Send an email with attachments from the command line

Posted on 2001-08-30
9
1,898 Views
Last Modified: 2008-06-04
How can I send and email with file attachments from the command line.

Thanks Phil.
0
Comment
Question by:phil2_curtis
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 3

Expert Comment

by:jnbkze
ID: 6443740
you can do something like this:

$ uuencode my_attachment a_new_file_name | mail -s "this is the subject" me@mymail.com

This will send me@mymail.com an email with an attachment called a_new_file_name

Hope this helps
0
 
LVL 17

Expert Comment

by:dorward
ID: 6444310
You can use the mutt email client.

mutt email@ddress -a filename.to.attache -s "Subject of email" < file.containing.message.body

or

Another program that produces output that you want as the message body | mutt email@ddress -a filename.to.attache -s "Subject of email"

0
 
LVL 1

Expert Comment

by:elniniokev
ID: 6445254
mail whoever@wherever.com -s "hello there" < attachment
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 17

Expert Comment

by:dorward
ID: 6445839
Isn't 'mail whoever@wherever.com -s "hello there" < attachment' only suitable for plain text attachments?
0
 
LVL 5

Accepted Solution

by:
moonbeam012200 earned 50 total points
ID: 6448232
The problem with using the easy uuencode or other "unix style" encodings is that it lacks the proper mime boundries and the correct mime types to allow the proper application by graphical mailers. Also needed is the capability to send a multipart text header, perform the proper base64 encoding for binary content, allow for multiple documents and multiple recipients.

To solve this problem, I wrote my own command line mailer out of perl, mime_mail. Perl version 5.005 or better is required. The "man" page is is printed with 'mime_mail -h'

-->mime_mail -h
NAME
    mime_mail

DISCRIPTION
    This program is a command line mailer that sends a text file
    description and one or more files in mime attachments. On success,
    mime_mail will work silently.

SYNOPSIS
    mime_mail -h | -d document.txt -s "mail subject"
              -u "user1 [,user2 ...]" -f "file1 [,file2 ...]"

OPTIONS
    -h
        Displays a man page.

    -d document.txt
        Sends "document.txt" in the mail message body. The file must
        be a normal text file. If a "-" is provided as an argument,
        the input will be taken from stdin. If no "-d" argument is
        supplied, the attachment will be sent with the message
        "Please see the attached.".

    -s "mail subject"
        Sets the mail subject. The mail subject must be quoted if the
        subject contains any spaces.

    -u user1,user2 ...
        A comma separated list of email addresses or aliases. Quotes
        are required if the list contains any spaces.

    -f file1,file2 ...
        A comma separaed list of files to attach. Quotes are required
        if the list contains any spaces. The files can be of any type.
        The recognised application content types are ".doc", ".html",
        ,"htm",".xls", ".csv", ".pdf", ".rtf", and ".mdb".

William Julien

Here is the source.

-->cat /home/moonbeam/cmd/mime_mail
#!/usr/bin/perl -w
#
# simple program to send a text message with an attachment
#
# William Julien
###

use strict;             # turn on the strict pragma
use Getopt::Std;        # use standard getopt to parse options

$/ = undef;             # turn on slurp mode

#
# scope local variables
#
my ($date,              # the current date
    $sendmail,          # the sendmail command
    $document,          # the document text
    %options,           # program options
    $filename,          # a file to send
    $file,              # the content of a file
    @filelist,          # list files to send
    $tolist,            # list of comma separated email addresses
    $today,             # today's date
    $usage,             # program usage
    $man,               # program man page
    $subject,           # email subject
    $extent,            # file extension
    %mime_type,         # list of supported application context mime types
    $mime_type,         # current mime application content type
    );

#
# variable initializations
#
$man = <<MAN;
NAME
    mime_mail

DISCRIPTION
    This program is a command line mailer that sends a text file
    description and one or more files in mime attachments. On success,
    mime_mail will work silently.

SYNOPSIS
    mime_mail -h | -d document.txt -s "mail subject"
              -u "user1 [,user2 ...]" -f "file1 [,file2 ...]"

OPTIONS
    -h
        Displays a man page.

    -d document.txt
        Sends "document.txt" in the mail message body. The file must
        be a normal text file. If a "-" is provided as an argument,
        the input will be taken from stdin. If no "-d" argument is
        supplied, the attachment will be sent with the message
        "Please see the attached.".

    -s "mail subject"
        Sets the mail subject. The mail subject must be quoted if the
        subject contains any spaces.

    -u user1,user2 ...
        A comma separated list of email addresses or aliases. Quotes
        are required if the list contains any spaces.

    -f file1,file2 ...
        A comma separaed list of files to attach. Quotes are required
        if the list contains any spaces. The files can be of any type.
        The recognised application content types are ".doc", ".html",
        ,"htm",".xls", ".csv", ".pdf", ".rtf", and ".mdb".

William Julien
MAN
$usage = <<USAGE;

Usage:
mime_mail -h | -d document.txt -s "mail subject"
          -u "user1 [,user2 ...]" -f "file1 [,file2 ...]"
USAGE
$sendmail = "/usr/lib/sendmail";
if ( ! -f $sendmail ) {
    die "Sorry -- cannot locate sendmail at $sendmail.\nYou must edit $0\n";
}
$today = scalar(localtime());
%mime_type = ("doc"   => "application/msword",
              "txt"   => "text/plain",
              "htm"   => "text/html",
              "html"  => "text/html",
              "xls"   => "application/vnd.ms-excel",
              "csv"   => "application/octet-stream",
              "pdf"   => "application/acrobat",
              "rtf"   => "application/rtf",
              "mdb"   => "application/vnd.ms-access",
             );

#
# process program options
#
getopts('d:s:u:f:h', \%options) or die "$usage\n";
if ( defined $options{"h"} ) {
    print "$man\n";
    exit;
}
if ( defined $options{"f"} ) {
    @filelist = split /\,/,$options{"f"};
    foreach $file (@filelist) {
        if (! -f $file) {
            die "$0: cannot open $file\n";
        }
    }
} else {
    die "$usage\n";
}
if ( defined $options{"d"} ) {
    $document = $options{"d"};
    if ( $document eq "-" ) {
        $document = <STDIN>;
    } else {
        if ( -f $document ) {
            open F, "$document";
            $document = <F>;
            close F;
        } else {
            die "$0 error: cannot open $document\n";
        }
    }
} else {
    $document = "Please see the attached.\n";
}
if ( defined $options{"s"} ) {
    $subject = $options{"s"};
} else {
    die "$usage\nError: No Subject\n";
}
if ( defined $options{"u"} ) {
    $tolist = $options{"u"};
} else {
    die "$usage\n$0 error: no subject specified\n";
}

open MAIL, "|$sendmail -t";
print MAIL <<HEADER;
To: $tolist
Subject: $subject
Date: $today
Mime-Version: 1.0
Content-Type: multipart/mixed;
        boundary="ThisRandomString"

This mail was formatted with mime_mail (wmj)

--ThisRandomString
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

$document
HEADER
foreach $filename (@filelist) {
    $extent = $filename =~ /\.(\w+)$/ ? "\L$1" : undef;
    $mime_type = "application/octet-stream";
    if ( defined $extent ) {
        if ( defined $mime_type{"$extent"} ) {
            $mime_type = $mime_type{"$extent"};
        } else {
            $mime_type = "application/octet-stream";
        }
    }
    open F,"$filename";
    $file = <F>;
    close F;
    $file = encode_base64($file);
    print MAIL <<FILE;
--ThisRandomString
Content-Type: $mime_type; name="$filename"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="$filename"

$file
FILE
}
print MAIL "--ThisRandomString--\n";
#
# send the mail
#
close MAIL;

#
# fin
###

sub encode_base64
{
    use integer;
    my $res = "";
    my $eol = $_[1];
    $eol = "\n" unless defined $eol;
    pos($_[0]) = 0;                          # ensure start at the beginning
    while ($_[0] =~ /(.{1,45})/gs) {
        $res .= substr(pack('u', $1), 1);
        chop($res);
    }
    $res =~ tr|` -_|AA-Za-z0-9+/|;            # `# help emacs
    # fix padding at the end
    my $padding = (3 - length($_[0]) % 3) % 3;
    $res =~ s/.{$padding}$/'=' x $padding/e if $padding;
    # break encoded string into lines of no more than 76 characters each
    if (length $eol) {
        $res =~ s/(.{1,76})/$1$eol/g;
    }
    return $res;
}
0
 

Expert Comment

by:drabaecus
ID: 6646685
*ping*
0
 
LVL 5

Expert Comment

by:moonbeam012200
ID: 6649482
I'm still here. Happy thanksgiving!
0
 

Author Comment

by:phil2_curtis
ID: 7137287
I will give you the points, even though I didn't use your example. My solution was along the same lines and that was to write my own program to do the task.

Phil
0
 

Expert Comment

by:jshandel
ID: 8560847
Compliments to the moonbeam chef. It worked like a charm!
0

Featured Post

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Linux users are sometimes dumbfounded by the severe lack of documentation on a topic. Sometimes, the documentation is copious, but other times, you end up with some obscure "it varies depending on your distribution" over and over when searching for …
Google Drive is extremely cheap offsite storage, and it's even possible to get extra storage for free for two years.  You can use the free account 15GB, and if you have an Android device..when you install Google Drive for the first time it will give…
Learn how to get help with Linux/Unix bash shell commands. Use help to read help documents for built in bash shell commands.: Use man to interface with the online reference manuals for shell commands.: Use man to search man pages for unknown command…
Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question