1. 程式人生 > >Python(2.7.x)使用SMTP傳送郵件的簡單示例

Python(2.7.x)使用SMTP傳送郵件的簡單示例

1. 傳送一封簡單的郵件:
# encoding: utf-8
import smtplib

sender = "[email protected]"
receivers = ["[email protected]"]

message = """From: test <[email protected]>
To: temp <[email protected]>
Subject: 測試郵件

這是一封測試郵件。
"""

try:
	smtpObj = smtplib.SMTP()
	smtpObj.connect("smtp.163.com", "25") 
	state = smtpObj.login("
[email protected]
", "123456") if state[0] == 235: smtpObj.sendmail(sender, receivers, message) print "郵件傳送成功" smtpObj.quit() except smtplib.SMTPException, e: print str(e)

2. 傳送帶附件的郵件:
# encoding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

msg = MIMEMultipart()
msg["from"] = "
[email protected]
" msg["to"] = "[email protected]" 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("
[email protected]
", "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)