[python snippets] 邮件发送 (带附件,多收件人, 支持SMTP 和Postfix )

来源:互联网 发布:windows 9 编辑:程序博客网 时间:2024/06/02 11:56
#!/usr/bin/env python#coding:utf-8# Author:   asdf--<># Purpose:  Send emailfrom itertools import chainfrom smtplib import SMTPfrom errno import ECONNREFUSEDfrom email.mime.base import MIMEBasefrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.encoders import encode_base64from mimetypes import guess_typefrom socket import error as SocketErrorfrom subprocess import Popen, PIPEfrom os.path import abspath, basename, expandusermailto_list=["root@wooyun.org"]###################### setup mail servermail_host="smtp.wooyun.org"mail_user="root"mail_pass="wooyun"mail_postfix="wooyun.org"######################def get_mimetype(filename):    """Returns the MIME type of the given file.    :param filename: A valid path to a file    :type filename: str    :returns: The file's MIME type    :rtype: tuple    """    content_type, encoding = guess_type(filename)    if content_type is None or encoding is not None:        content_type = "application/octet-stream"    return content_type.split("/", 1)def mimify_file(filename):    """Returns an appropriate MIME object for the given file.    :param filename: A valid path to a file    :type filename: str    :returns: A MIME object for the givne file    :rtype: instance of MIMEBase    """    filename = abspath(expanduser(filename))    basefilename = basename(filename)    msg = MIMEBase(*get_mimetype(filename))    msg.set_payload(open(filename, "rb").read())    msg.add_header("Content-Disposition", "attachment", filename=basefilename)    encode_base64(msg)    return msg    def send_mail(to_list, subject, content, **params):    '''Just send mail'''        # Default Parameters    cc = params.get("cc", [])    bcc = params.get("bcc", [])    files = params.get("files", [])    sender = mail_user+"<"+mail_user+"@"+mail_postfix+">"      recipients = list(chain(to_list, cc, bcc))        # Prepare Message    msg = MIMEMultipart()    msg.preamble = subject    msg.add_header("From", sender)    msg.add_header("Subject", subject)    msg.add_header("To", ", ".join(to_list))    cc and msg.add_header("Cc", ", ".join(cc))        # Attach the main text    msg.attach(MIMEText(content))        # Attach any files    [msg.attach(mimify_file(filename)) for filename in files]        # Contact SMTP server and send Message    try:        s = SMTP()        s.connect(mail_host)        s.login(mail_user,mail_pass)        s.sendmail(sender, recipients, msg.as_string())        s.quit()        return True            except SocketError as e:        if e.args[0] == ECONNREFUSED:            p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)            p.communicate(msg.as_string())        else:            raise    def test():    if send_mail(mailto_list, "Test subject", "Test Message"):        print "Done."    else:        print "Failed."    def test1():    if send_mail(mailto_list, "Test subject", "Test Message",files=['CVE-2014-0226.py']):        print "Done."    else:        print "Failed."    if __name__ == '__main__':    test() 


0 0