python 发送邮件

来源:互联网 发布:js 移动端 上传照片 编辑:程序博客网 时间:2024/06/16 01:48
# coding: utf-8import smtplibfrom email.mime.text import MIMETextfrom email.header import Header# 文件形式的邮件def email_file():    mail_host = "smtp.qq.com"  # 邮箱服务器    mail_user = "xxxxxxx@qq.com"  # 登录邮箱    mail_pass = "xxxxx"  # 邮箱密码    # 发件人(与登录邮箱一致)    sender = 'xxxxx@qq.com'    # 接收邮件,可设置为你的QQ邮箱或者其他邮箱    receivers = ['xxxxx@qq.com']    '''    # 发送HTML格式的邮件    mail_msg ="        <p>Python 邮件发送测试...</p>        <p><a href="http://www.runoob.com">这是一个链接</a></p>    "    message = MIMEText(mail_msg, 'html', 'utf-8')      '''    # 邮件内容    message = MIMEText('这个是 邮件发送测试...', 'plain', 'utf-8')    message['From'] = sender    message['To'] = ",".join(receivers)    # 邮件主题    subject = 'Python SMTP 邮件测试'    message['Subject'] = Header(subject, 'utf-8')    '''    # 构造附件    att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')    att1["Content-Type"] = 'application/octet-stream'    att1["Content-Disposition"] = 'attachment; filename="test.txt"'    message.attach(att1)    '''    try:        smtpObj = smtplib.SMTP_SSL()        smtpObj.connect(mail_host, 465)  # <span style="font-family: Arial, Helvetica, sans-serif;">465</span><span style="font-family: Arial, Helvetica, sans-serif;"> 为 </span><span style="font-family: Arial, Helvetica, sans-serif;">SMTP_SSL</span><span style="font-family: Arial, Helvetica, sans-serif;">端口号</span><span style="font-family: Arial, Helvetica, sans-serif;"></span>        smtpObj.login(mail_user, mail_pass)        smtpObj.sendmail(sender, receivers, message.as_string())        print "邮件发送成功"    except smtplib.SMTPException:        print "Error: 发送邮件失败"if __name__ == '__main__':    email_file()

0 0
原创粉丝点击