python 发送邮件

来源:互联网 发布:华为mate8预装软件列表 编辑:程序博客网 时间:2024/06/05 07:16

原文:http://blog.csdn.net/marksinoberg/article/details/51506308

要发送邮件前需要做准备工作

1.启动邮箱的smtp/pop协议;开启时系统会提示给我们一个邮箱客户端的授权码,作用就是我们登陆的时候替代原来的登陆密码

如果没有启动smtp/pop协议则会提示:smtplib.SMTPAuthenticationError: (535 Error:authentication failed)

如果不是使用的授权码登录则会提示:smtplib.SMTPAuthenticationError: (550, b'User has no permission')


dome:

# !/usr/bin/env python# -*- coding: utf-8 -*-import smtplibfrom email.mime.text import MIMETextfrom email.header import Headerfrom email.mime.multipart import MIMEMultipartfrom email.mime.application import MIMEApplicationdef email_file():    # 获取邮箱服务器    mail_host = 'smtp.qq.com'    # 获取邮箱的登录邮箱    mail_user = "xxxxxxxx@qq.com"    # 邮箱授权码    mail_pass = "xxxxxxx"    # 接收邮箱,可设置为你的QQ邮箱或者其他邮箱格式为'xx.@qq.com,xx.@qq.com'    receivers = 'xxxxxx@qq.com'    # 构造多个部分    message = MIMEMultipart()    # 发件人(与登录邮箱一致)    message['From'] = mail_user    # 收件人    message['To'] = receivers    # 邮件主题    message['Subject'] = Header('python测试邮件', 'utf-8')    # 发送HTML格式的邮件    # mail_msg = """    #     <p>Python 邮件发送测试...</p>    #     <p><a href="http://www.runoob.com">这是一个链接</a></p>    # """    # html_c = MIMEText(mail_msg, 'html', 'utf-8')    # message.attach(html_c)    # 邮件内容    puretext = MIMEText('这是一个测试邮件', 'plain', 'utf-8')    message.attach(puretext)    # ------------------------附件-------------------------------------    # 构造附件    accessory = MIMEApplication(open('test_run.py', 'rb').read())    accessory.add_header('Content-Disposition', 'attachment', filename='test_run.py')    message.attach(accessory)    # ---------------------------发送邮件-------------------------------------------------    try:        smtpObj = smtplib.SMTP_SSL()        # 465为SMTP_SSL端口号        smtpObj.connect(mail_host, 465)        smtpObj.login(mail_user, mail_pass)        smtpObj.sendmail(mail_user, receivers, message.as_string())        print "邮件发送成功"    except Exception, e:        print eif __name__ == '__main__':    email_file()


原创粉丝点击