python发送邮件

来源:互联网 发布:新疆如何绕过网络管制 编辑:程序博客网 时间:2024/06/07 06:24

1.使用模块:smtplib模块

2.代码示例如下:

import smtplibdef send_mail(request):    msg = MIMEMultipart()    if request.method == "POST":        project = request.POST["project"]        address = request.POST["address"]        exampleInputFile = request.FILES.get("exampleInputFile", "")        filename = exampleInputFile.name.encode('gb2312')        file_url = filename        file_obj = open(file_url, "wb")        for chunck in exampleInputFile.chunks():            file_obj.write(chunck)        file_obj.close()        text = request.POST["text"]        txt = MIMEText(text, 'plain', 'utf-8')        msg.attach(txt)        # 构造附件        if exampleInputFile:            att1 = MIMEText(open(file_url, 'rb').read(), 'base64', 'utf-8')            att1["Content-Type"] = 'application/octet-stream'            att1["Content-Disposition"] = "attachment;filename='%s'" % filename            msg.attach(att1)        # 加邮件头        msg['to'] = address        msg['from'] = "发件人"        msg['subject'] = project        # 发送邮件        try:            server = smtplib.SMTP()            server.connect('smtp.163.com')            server.starttls()            server.login("用户名", "密码")            server.sendmail(msg['from'], msg['to'], msg.as_string())            server.quit()            response.write("发送成功!")            return response        except:            response.write("发送失败!")            return response


1 0
原创粉丝点击