您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python发送邮件示例(支持中文邮件标题)

5b51 2022/1/14 8:17:43 python 字数 5233 阅读 355 来源 www.jb51.cc/python

复制代码代码如下:defsendmail(login={},mail={}):???\'\'\'\\???@paramloginlogin[\'user\']login[\'passwd\']???@parammailmail[\'to_addr\']mail[\'subject\']mail

概述

    user_info = login['user'].split('@')
    mail_configure = {}
    mail_configure['mail_encoding'] = 'utf-8'
    mail_configure['mail_supplier'] = user_info[1]
    mail_configure['from_addr'] = login['user']
    mail_configure['server_host'] = 'smtp.%s' % mail_configure['mail_supplier']
    error = None

    try:
        email = MIMEMultipart()
        email['from'] = mail_configure['from_addr']
        email['to'] = mail['to_addr']
        email['subject'] = '=?%s?B?%s?=' % (mail_configure['mail_encoding'],b64encode(mail['subject']))
        email_content = MIMEText(mail['content'],_charset=mail_configure['mail_encoding'])
        email.attach(email_content)

        if 'attach' in mail:
            for i in mail['attach']:
                ctype,encoding = mimetypes.guess_type(i)
                if ctype is None or not encoding is None:
                    ctype = 'application/octet-stream'
                maintype,subtype = ctype.split('/',1)
                att = MIMEImage((lambda f: (f.read(),f.close()))(open(i,'rb'))[0],_subtype = subtype)
                att.add_header('Content-Disposition','attachment',filename = i)
                email.attach(att)

        smtp = smtplib.SMTP()
        smtp.connect(mail_configure['server_host'])
        smtp.login(user_info[0],login['passwd'])
        smtp.sendmail(mail_configure['from_addr'],mail['to_addr'],email.as_string())
        smtp.quit()
    except Exception as e:
        error = e

    return (mail_configure['from_addr'],error)

测试

    login = {
        'user':'hellot@sina.com',
        'passwd':'hello#world'
    }
    mail = {
        'to_addr':'tom12@sina.com;tom12@21cn.com',
        'subject':'带附件的测试邮件',
        'attach':['e:/a/a.txt']
    }
    print sendmail(login,mail)

总结

以上是编程之家为你收集整理的python发送邮件示例(支持中文邮件标题)全部内容,希望文章能够帮你解决python发送邮件示例(支持中文邮件标题)所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶