Python發送郵件

#!/usr/bin/python
import sys
import glob
import codecs
import smtplib
import mimetypes
from os.path import basename, join
from argparse import ArgumentParser
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders
from time import sleep


def guess_type(path):
    ctype, encoding = mimetypes.guess_type(path)

    if ctype is None or encoding is not None:

        return 'application', 'octet-stream'

    else:

        maintype, subtype = ctype.split('/', 1)

        return maintype, subtype


def slurp(filename, encoding=None):
    with codecs.open(filename, 'rb', encoding, 'replace') as handle:
        return handle.read()


def send_email(args):
    parser = ArgumentParser(usage='%(prog)s [options] recipients')

    parser.add_argument('--server', dest='Server', default='smtp.163.com',
                        help='Host name of the SMTP server, default "smtp.163.com".')

    parser.add_argument('--port', dest='Port', type=int, default=25, help='TCP port of the SMTP server, default 25.')

    parser.add_argument('--user', dest='Username', required=True, help='Username for SMTP authentication.')

    parser.add_argument('--password', dest='Password', required=True, help='Password forSMTP authentication.')

    parser.add_argument('--from', dest='From', required=True, help='Email address of sender.')

    parser.add_argument('--cc', dest='CC', action='append', help='Recipient to carbon copy')

    parser.add_argument('--subject', dest='Subject', help='Email subject line.')

    group1 = parser.add_mutually_exclusive_group()

    group1.add_argument('--content', dest='Content', help='Content to send as the body of the email')

    group1.add_argument('--file', dest='ContentFile', help='File to send as the body of the email!')

    parser.add_argument('--encoding', dest='Encoding', default='utf-8', help='Encoding of the file, default "utf-8".')

    parser.add_argument('--attachment', dest='Attachment', action='append',
                        help='File to send as attachments to the email.')

    parser.add_argument('recipients', nargs='+', help='Blank-separated list of recipients.')

    options = parser.parse_args(args)

    try:
        message = MIMEMultipart()
        message['From'] = options.From
        TO = ','.join(options.recipients)
        recipients = TO.split(',')
        message['To'] = TO

        if options.CC:
            CC = ','.join(options.CC)
            recipients += CC.split(',')
            message['Cc'] = CC

        if options.Subject:
            message['Subject'] = options.Subject

        if options.Content:
            msgText = MIMEText(options.Content, 'plain', options.Encoding)
            message.attach(msgText)

        if options.ContentFile:
            maintype, subtype = guess_type(options.ContentFile)

            if maintype == 'text':

                content = slurp(options.ContentFile, options.Encoding)

                mimebody = MIMEText(content, subtype, options.Encoding)

            else:

                content = slurp(options.ContentFile)

                mimebody = MIMEBase(maintype, subtype)

                mimebody.set_payload(content)

                encoders.encodebase64(mimebody)

                mimebody.add_header('Content-Disposition', 'attachment', filename=basename(options.ContentFile))

                message.attach(mimebody)

        if options.Attachment:

            for pattern in options.Attachment:

                for filename in glob.glob(pattern):
                    content = slurp(filename)

                    maintype, subtype = guess_type(filename)
                    mimebody = MIMEBase(maintype, subtype)

                    mimebody.set_payload(content)

                    encoders.encode_base64(mimebody)

                    mimebody.add_header('Content-Disposition', 'attachment', filename=basename(filename))

                    message.attach(mimebody)

        smtp = smtplib.SMTP(options.Server, options.Port, timeout=20)

        smtp.starttls()
        smtp.login(options.Username, options.Password)

        smtp.sendmail(options.From, recipients, message.as_string())

        sleep(2)

        smtp.quit()

        sleep(1)

    except smtplib.SMTPException as e:
        sys.stderr.write(str(e) + '\n')


if __name__ == '__main__':
    send_email(sys.argv[1:])

>>> python send_email.py  "[email protected]" --cc=="[email protected]" --from="[email protected]" --user="郵箱帳戶名" --password="客戶端授權碼" --subject="主題" --content="內容body"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章