超級網迷

超級網迷+ 電腦迷+ 音樂迷
個人資料
正文

用Python腳本發送電子郵件舉例

(2013-09-13 19:03:04) 下一個

我的任務是通過電子郵件發送200多M的電子書。嗬嗬,我的郵箱可沒有那麽大,能把整部書都容得下。那就把“月餅”先切成14塊,再一個一個發出去。步驟如下:

1)用7zip分割成14份。每份18M嗬嗬~~

2)我的運行環境是RedHat 5.7。Python腳本如下:

#! /usr/bin/env python

import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import COMMASPACE, formatdate
from email.mime.base import MIMEBase
from email import Encoders

def send_mail(From, To, Subject, Body, Files=[], Server = 'localhost', File_As_Body = None):
    assert type(To) == list
    assert type(Files) == list
   
    msg = MIMEMultipart()
    msg['Subject'] = Subject
    msg['From'] = From
    msg['To'] = COMMASPACE.join(To)
    msg['Date'] = formatdate(localtime=True)
   
    if File_As_Body:
        fab = open(File_As_Body, 'rb')
        f = fab.read()   
        msg.attach(MIMEText(f))
    else:
        msg.attach(MIMEText(Body))
   
    for f in Files:
        part = MIMEBase('application', 'octet-stream')
        fp = open(f, 'rb')
        part.set_payload(fp.read())
        fp.close()
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' %os.path.basename(f))
        msg.attach(part)

    smtp = smtplib.SMTP(Server, 1025)
    smtp.login('quinn@email.com', 'password')
    #smtp.ehlo()
    #smtp.helo()
    smtp.sendmail(From, To, msg.as_string())
    smtp.close()

book = ['MySQL.7z.001','MySQL.7z.002','MySQL.7z.003','MySQL.7z.004','MySQL.7z.005','MySQL.7z.006','MySQL.7z.007', 'MySQL.7z.008','MySQL.7z.009','MySQL.7z.010','MySQL.7z.011','MySQL.7z.012','MySQL.7z.013','MySQL.7z.014']

for part in book:
    send_mail('quinn@email.com',
       ['user@user.com'],
        'MySQL book (14 parts)',
        'attached',
        [part],
        'smtp.server.com')

    print part + ' Sent OK!' 
print 'All done'

不用多說了,您一看就懂了:)

[ 打印 ]
閱讀 ()評論 (0)
評論
目前還沒有任何評論
登錄後才可評論.