Home » Python » mail.py 用python发送邮件
  • 24
  • 10月

mail.py 用python发送邮件

用法:

$ echo "hello" | ./mail.py -a 1.py -a 2.py -s "hello" xxx@yyy.com
$ cat filename | ./mail.py -a 1.py -a 2.py -s "hello" xxx@yyy.com
$ ./mail.py -a 1.py -a 2.py -s "hello" xxx@yyy.com
$ cat filename | ./mail.py -a 1.py -a 2.py -s "hello" xxx@yyy.com | ./sendmail.py

源码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from base64 import b64encode
from os.path import abspath,basename
from getopt import getopt
from hashlib import md5
from base64 import b64encode
import smtplib,mimetypes,sys
import email
def to_utf8(data):
    """change into utf-8."""
    for c in ('mbcs','utf-8'):
        try:
            unicode(data,c)
            if c in ('utf-8'):
                return data
            else:
                return data.decode(c).encode('utf-8')
        except:
            pass
def b64_utf8(data):
    """encode into base64."""
    return '=?utf-8?B?%s?=' % b64encode(data)
def md5sum(FILE):
    """return a file's md5sum."""
    m=md5()
    file=open(FILE,'r')
    bytes=file.read(1024)
    while(bytes != b''):
        m.update(bytes)
        bytes = file.read(1024)
    file.close()
    md5value=m.hexdigest()
    return md5value
class mail:
    def __init__(self, FROM, TO, SUBJECT='', CHARSET='utf-8'):
        self.FROM=FROM
        self.TO=TO
        self.SUBJECT=SUBJECT
        self.CHARSET=CHARSET
        self.text=''
        self.fileinfo='/n/n--------/n'
        self.files=[]
        self.msg = MIMEMultipart()
        self.msg['From'] = self.FROM
        self.msg['To'] = self.TO
        pass
    def addtext(self,text=''):
        self.text += text
        pass
    def addfile(self,FILE):
        #添加二进制附件
        fileName = r"%s" % abspath(FILE)
        f2= basename(fileName)
        f1= to_utf8(f2)
        ctype, encoding = mimetypes.guess_type(fileName)
        if ctype is None or encoding is not None:
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        att = MIMEImage((lambda f: (f.read(), f.close())) /
                        (open(fileName, 'rb'))[0], _subtype = subtype)
        att.add_header('Content-Disposition', 'attachment', /
                       filename = b64_utf8(f1))
        att.set_charset(self.CHARSET)
        self.files.append(att)
        if not self.SUBJECT:
            self.SUBJECT += f1
        self.fileinfo += '%s/t%s/n' % (md5sum(fileName),f1)
        pass
    def makemail(self):
        self.msg['Subject'] = b64_utf8(self.SUBJECT)
        txt=MIMEText(self.text + self.fileinfo,'plain',self.CHARSET)
        self.msg.attach(txt)
        for x in self.files:
            self.msg.attach(x)

def main():
    FROM='xxx@163.com'
    TO='xxx@qq.com'
    FLAGS1='a:s:h'
    FLAGS2=['help']
    '''Usage: appname [options] [address] /n
    options:
    -a <file> /t/t add file to email
    -s <subject> /t set the subject of email
    -h /t/t/t just for help
    '''
    opts,args=getopt(sys.argv[1:],FLAGS1,FLAGS2)
    atts=[]
    if not args:
        mailto=TO
    else:
        mailto=args[0]
    subject=''
    for x,a in opts:
        if x in ('-a'):
            atts.append(a)
        elif x in ('-s'):
            subject=a
        elif x in ('-h','--help'):
            print main.__doc__
            return
        else:
            print( 'none argvs!!!')
    mymail=mail(FROM,mailto,subject)
    for file in atts:
        mymail.addfile(file)
    text=sys.stdin.read()
    mymail.addtext(text)
    mymail.makemail()
    print mymail.msg.as_string()
    pass

if __name__ == '__main__' :
    main()
    pass