Python发送带附件的邮件的实现代码

发布时间:2020-10-24编辑:脚本学堂
本文介绍下,使用python实现的带附件邮件的发送代码,用到了python的smtplib模块, email.MIMEMultipart,email.mime.application模块等。有需要的朋友参考学习下。

python发送邮件的例子,可以带附件。
代码:
 

复制代码 代码示例:

#!/bin/python
#site: www.jb200.com
#
import os
import sys
from smtplib import SMTP
from email.MIMEMultipart import MIMEMultipart
from email.mime.application import MIMEApplication
import time

def sendFildByMail(config):

    print 'Preparing...',

    message = MIMEMultipart( )
    message['from'] = config['from']
    message['to'] = config['to']
    message['Reply-To'] = config['from']
    message['Subject'] = config['subject']
    message['Date'] = time.ctime(time.time())

    message['X-Priority'] =  '3'
    message['X-MSMail-Priority'] =  'Normal'
    message['X-Mailer'] =  'Microsoft Outlook Express 6.00.2900.2180'
    message['X-MimeOLE'] =  'Produced By Microsoft MimeOLE V6.00.2900.2180'

    #注意这一段
    f=open(config['file'], 'rb')
    file = MIMEApplication(f.read())
    f.close()
    file.add_header('Content-Disposition', 'attachment', filename= os.path.basename(config['file']))
    message.attach(file)

    print 'OK'
    print 'Logging...',

    smtp = SMTP(config['server'], config['port'])
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login(config['username'], config['password'])

    print 'OK'
    print 'Sending...',

    smtp.sendmail (config['from'], [config['from'], config['to']], message.as_string())

    print 'OK'

    smtp.close()

    time.sleep(1)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print 'Usage: python %s <file path>' % os.path.basename(sys.argv[0])
        #sys.exit(-1)
    else:
        #587,  25
        sendFildByMail({
            'from': "xxx@xxx.com", #发件人
            'to': 'xxx@xxx.com', #收件人
            'subject': '[pysend]Send file %s' % sys.argv[1], #邮件主题
            'file': sys.argv[1],
            'server': 'smtp.xxx.com', #smtp
            'port': 587,
            'username': 'username',
            'password': 'password'})
    wait=raw_input("end.")

您可能感兴趣的文章:
分享:python发邮件的综合实例
python邮件发送模块smtplib的实例详解
python smtplib发送邮件的例子 python使用126邮箱发送邮件
python smtplib模块发邮件(带附件)的例子
python 发送邮件乱码的解决方法
python从文件读取邮件地址输出的例子
python使用gmail发送邮件的实例代码
python smtplib模块发送邮件的实例详解
python smtp模块发送邮件的代码
python发送邮件的脚本一例
python结合php解决发送邮件乱码的问题
python发送邮件的例子
python发送邮件的实例代码
python 发送邮件的代码