使用python发送带附件的邮件

Posted by 4Aiur on 04/06/2010 in Python |

使用python发送带附件的邮件

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import utils, encoders
import mimetypes, sys
import smtplib
import re
import datetime

def attachment(filename):
    fd = open(filename, "rb")
    mimetype, mimeencoding = mimetypes.guess_type(filename)
    if mimeencoding or (mimetype is None):
        mimetype = "application/octet-stream"
    maintype, subtype = mimetype.split("/")
    if maintype == "text":
        retval = MIMEText(fd.read(), _subtype=subtype)
    else:
        retval = MIMEBase(maintype, subtype)
        retval.set_payload(fd.read())
        encoders.encode_base64(retval)
    retval.add_header("Content-Disposition", "attachment", filename = filename)
    fd.close()
    return retval

today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)

message = """Hello,

today: %s

yesterday: %s

""" %(today, yesterday)

msg = MIMEMultipart()
msg["To"] = "foo@example.com, bar@example.com"
msg["From"] = "foo_bar@example.com"
msg["Subject"] = "MySubject"
msg["Date"] = utils.formatdate(localtime = 1)
msg["Message-ID"] = utils.make_msgid()

body = MIMEText(message, _subtype="plain")
msg.attach(body)
for filename in sys.argv[1:]:
    msg.attach(attachment(filename))
#print msg.as_string()

# Send mail
smtp = smtplib.SMTP()
#smtp.set_debuglevel(1)
smtp.connect("mail.example.com")
smtp.ehlo()
#smtp.login("user", "password")
To = re.split(r", *", msg["To"])
smtp.sendmail(msg["From"], To, msg.as_string())
smtp.quit()

Tags: ,

Copyright © 2010-2024 4Aiur All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.