python发送邮件源码 | the5fire的技术博客

python发送邮件源码 | the5fire的技术博客

python发送邮件源码

python发送邮件源码

这是之前一个公司的面试题中的一小部分。比较习惯把这中工具性的东西单独的写成一个函数,这样以后再用到,直接拿来就好。

这段代码的作用就是发送邮件可以添加附件,且可以是html样式的邮件。具体看代码吧

import smtplib
from email. MIMEText import MIMEText
from email. MIMEMultipart import MIMEMultipart

def send_mail (to , sub , content , from_email , mail_pass , filelist = [ ] ):
    '''
    to:发给谁
    sub:主题
    content:内容
    from_email:登录邮箱
    mail_pass:登录密码
    filelist:附件列表,文件路径
    send_mail("aaa@126.com","the5fire","welcome to the5fire.net","xxxx@xxx.com","xxxxxx")
    '''

   
    mail_postfix = from_email. split ( '@' ) [ 1 ]
    mail_host = "smtp.%s" % (mail_postfix , )
    mail_user = from_email. split ( '@' ) [ 0 ]

    me =mail_user+ "<"+mail_user+ "@"+mail_postfix+ ">"

    msgRoot = MIMEMultipart ( 'related' )
    msgRoot [ 'Subject' ] = sub. encode ( 'gbk' )
    msgRoot [ 'Form' ] = me
    msgRoot [ 'To' ] = to
    msgRoot. preamble = 'this is a multi-part message IN MIME format'
   
    msgAlternative = MIMEMultipart ( 'alternative' )
    msgRoot. attach (msgAlternative )

    msgText = MIMEText (content , 'html' , 'gbk' )
    msgAlternative. attach (msgText )
    for onefile in filelist:
        att = MIMEText ( open (onefile , 'rb' ). read ( ) , 'base64' , 'gb2312' )
        att [ "Content-Type" ] = 'application/octet-stream'
        att [ "Content-Disposition" ] = 'attachment;filename=%s' % onefile
        msgAlternative. attach (att )

    message = msgRoot. as_string ( )
    try:
        s = smtplib. SMTP ( )
        try:
            s. connect (mail_host )
        except Exception ,e:
            print str (e )
        s. starttls ( )
        s. login (mail_user ,mail_pass )
        s. sendmail (me , to , message )
        s. close ( )
        return True
    except Exception , e:
        print str (e )
        return False
posted on 2013-01-07 22:47  lexus 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lexus/archive/2013/01/07/2850283.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值