前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python发送邮件源码

python发送邮件源码

作者头像
the5fire
发布2019-02-28 16:30:57
6660
发布2019-02-28 16:30:57
举报
文章被收录于专栏:Python程序员杂谈

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

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

代码语言:javascript
复制
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.com","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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2012-10-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档