ActiveState Code

Recipe 65434: Sending mail with attachments


How to send an email using the SMTP and MIME packages in tcllib (part of ActiveTcl).

Tcl
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package require mime 1.0
package require smtp 1.0

# create an image
set imageT [mime::initialize -canonical image/gif -file logo.gif]

# parse a message
set messageT [mime::initialize -file example.msg]

# recursively traverse a message looking for primary recipients

proc traverse {token} {
    set result ""

    # depth-first search
    if {![catch { mime::getproperty $token parts } parts]} {
	foreach part $parts {
	    set result [concat $result [traverse $part]]
	}
    }

    # one value for each line occuring in the header
    foreach value [mime::getheader $token To] {
	foreach addr [mime::parseaddress $value] {
	    catch { unset aprops }
	    array set aprops $addr
	    lappend result $aprops(address)
	}
    }

    return $result
}

# create a multipart containing both, and a timestamp
set multiT [mime::initialize \
                -canonical multipart/mixed \
                -parts [list $imageT $messageT]]

# send it to some friends
smtp::sendmessage $multiT \
	-header [list From "Marshall Rose <mrose@dbc.mtview.ca.us>"] \
	-header [list To "Andreas Kupries <a.kupries@westend.com>"] \
	-header [list cc "dnew@messagemedia.com (Darren New)"] \
	-header [list Subject "test message..."]

# clean everything up
mime::finalize $multiT -subordinates all

Discussion

The following example creates a simple mail and then sends it to the local SMTP server. It is taken from the documentation of these packages. The home page for tcllib is http://tcllib.sourceforge.net/.

Comments

  1. 1. At 11:19 a.m. on 14 feb 2004, Gerald Lester said:

    Nice! Thanks Jeff!

    A short easy to follow solutions to problem that comes up often, but not often enough that "everyone" knows the answer!

  2. 2. At 7:27 a.m. on 8 apr 2008, jerome colinas said:

    painful code. I spent few hours to make the tcl code work (could not attach a document to the email) but to no avail. until I gave up and used the following tcl code that works perfectly fine on a linux machine:

    eval exec mutt "-s \"report\" -a my_file_to_send.pdf email@email.com I spent few hours to make the tcl code work (could not attach a document to the email) but to no avail. until I gave up and used the following tcl code that works perfectly fine on a linux machine:
    <pre>
    eval exec mutt "-s \"report\" -a my_file_to_send.pdf email@email.com
    

    </pre>

Sign in to comment