Python(2.7.x)使用SMTP发送邮件的简单示例

来源:互联网 发布:arm编程 编辑:程序博客网 时间:2024/05/17 06:23
1. 发送一封简单的邮件:
# encoding: utf-8import smtplibsender = "test@163.com"receivers = ["temp@qq.com"]message = """From: test <test@163.com>To: temp <temp@qq.com>Subject: 测试邮件这是一封测试邮件。"""try:smtpObj = smtplib.SMTP()smtpObj.connect("smtp.163.com", "25") state = smtpObj.login("test@163.com", "123456")if state[0] == 235:smtpObj.sendmail(sender, receivers, message)print "邮件发送成功"smtpObj.quit()except smtplib.SMTPException, e:print str(e)

2. 发送带附件的邮件:
# encoding: utf-8import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartmsg = MIMEMultipart()msg["from"] = "test@163.com"msg["to"] = "temp@qq.com"msg["subject"] = u"测试邮件"txt = MIMEText(u"这是一封带附件的测试邮件。", "plain", "utf-8")   msg.attach(txt)# 构造附件att = MIMEText(open(u"temp.zip", "rb").read(), "base64", "utf-8")att["Content-Type"] = "application/octet-stream"att["Content-Disposition"] = "attachment; filename='temp.zip'"msg.attach(att)try:smtpObj = smtplib.SMTP()smtpObj.connect("smtp.163.com", "25") state = smtpObj.login("test@163.com", "123456")if state[0] == 235:smtpObj.sendmail(msg["from"], msg["to"], msg.as_string())print u"邮件发送成功"smtpObj.quit()except smtplib.SMTPException, e:print str(e)

0 0
原创粉丝点击