基本需求是,把一个文件读取显示到邮件的正文,代码如下:

#!/usr/bin/env python  

#coding:utf-8

  

import smtplib  

import sys  

import os  

  

from email.MIMEMultipart import MIMEMultipart  

from email.MIMEBase import MIMEBase  

  

from email.MIMEText import MIMEText  

import email.Encoders as encoders  

  

  

def send_mail(mail_from, mail_to, subject, files):  

    msg = MIMEMultipart('alternative')  

    msg['Subject'] = subject  

    msg['From'] = mail_from  

    msg['To'] = mail_to  


    with open(files,'r') as f:

        content=f.read().replace('\n','\r\n')

    part3=MIMEText(content, 'plain')#'plain'是文字(有换行的)  'html' 是网页  'text' 是附件形式发送文件   

    msg.attach(part3)


    s = smtplib.SMTP('mail.fastweb.com.cn')  


    mailto_list = mail_to.strip().split(",")  

    if len(mailto_list) > 1:  

        for mailtoi in mailto_list:  

            s.sendmail(mail_from, mailtoi.strip(), msg.as_string())  

    else:  

        s.sendmail(mail_from, mail_to, msg.as_string())  

  

    s.quit()  

    return True  

  

  

def main():  

    files = '1.py'  #这里是读取的文件,用绝对路径

    mail_from = "fantefei@163.com"  #发件人

    mail_to = "wangrf@fastweb.com.cn"   #收件人,多人用逗号分隔

    subject = "This is test" #标题 

    send_mail(mail_from, mail_to, subject, files)  

  

if __name__ == "__main__":  

    main()