possibilité d'attacher un fichier

This commit is contained in:
Jephté Clain 2013-11-15 16:35:04 +04:00
parent c711598754
commit 89e180cd49
1 changed files with 53 additions and 5 deletions

View File

@ -6,12 +6,19 @@ u"""%(scriptname)s: Afficher un mail correctement encodé pour son envoi
USAGE
%(scriptname)s [options] [-f from] <subject> recipients... <<<"body" | /usr/sbin/sendmail -i"""
import os, sys
import i_need_py25 # nécessite module email version 4.0
import os, sys, mimetypes
from os import path
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.multipart import MIMEMultipart
from email.generator import Generator
from ulib.all import *
@ -22,18 +29,22 @@ def run_pyumail():
options, longoptions = build_options([
('h', 'help', "Afficher l'aide"),
('f:', 'from=', "Spécifier l'expéditeur"),
('a:', 'attach=', "Attacher un fichier"),
])
options, args = get_args(None, options, longoptions)
mfrom = 'no-reply@univ-reunion.fr'
subject = None
mtos = []
body = None
afiles = []
for option, value in options:
if option in ('-h', '--help'):
display_help()
sys.exit(0)
elif option in ('-f', '--from'):
mfrom = value
elif option in ('-a', '--attach'):
afiles.append(value)
if not args[0:1]: die("Vous devez spécifier le sujet")
subject = args[0]
@ -52,8 +63,45 @@ def run_pyumail():
body = MIMEText('\n'.join(lines), 'plain')
body.set_charset('utf-8')
msg.attach(body)
print msg.as_string()
for afile in afiles:
if not path.isfile(afile): die("%s: Fichier introuvable" % afile)
mimetype, encoding = mimetypes.guess_type(afile)
if mimetype is None or encoding is not None:
mimetype = 'application/octet-stream'
maintype, subtype = mimetype.split('/', 1)
if maintype == 'text':
inf = open(afile, 'rb')
try:
#XXX on considère que tous les fichiers texte sont encodés en
# utf-8. Ce n'est pas forcément vrai, mais cette approximation
# devrait être suffisante pour le moment
part = MIMEText(inf.read(), _subtype=subtype, _charset='utf-8')
finally:
inf.close()
elif maintype == 'image':
inf = open(afile, 'rb')
try:
part = MIMEImage(inf.read(), _subtype=subtype)
finally:
inf.close()
elif maintype == 'audio':
inf = open(afile, 'rb')
try:
part = MIMEAudio(inf.read(), _subtype=subtype)
finally:
inf.close()
else:
part = MIMEBase(maintype, subtype)
inf = open(afile, 'rb')
try:
part.set_payload(inf.read())
finally:
inf.close()
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=path.basename(afile))
msg.attach(part)
Generator(sys.stdout).flatten(msg)
if __name__ == '__main__':
run_pyumail()