SMTP(Simple Mail Transfer Protocol)即簡(jiǎn)單郵件傳輸協(xié)議, 它是一組用于由源地址到目的地址傳送郵件的規(guī)則,由它來(lái)控制信件的中轉(zhuǎn)方式。
python 的 smtplib 提供了一種很方便的途徑發(fā)送電子郵件。它對(duì) smtp 協(xié)議進(jìn)行了簡(jiǎn)單的封裝。
Python 創(chuàng)建 SMTP 對(duì)象語(yǔ)法如下:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
參數(shù)說(shuō)明:
Python SMTP 對(duì)象使用 sendmail 方法發(fā)送郵件,語(yǔ)法如下:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
參數(shù)說(shuō)明:
這里要注意一下第三個(gè)參數(shù),msg 是字符串,表示郵件。我們知道郵件一般由標(biāo)題,發(fā)信人,收件人,郵件內(nèi)容,附件等構(gòu)成,發(fā)送郵件的時(shí)候,要注意 msg 的格式。這個(gè)格式就是 smtp 協(xié)議中定義的格式。
以下是一個(gè)使用 Python 發(fā)送郵件簡(jiǎn)單的實(shí)例:
#!/usr/bin/python
import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Python 發(fā)送 HTML 格式的郵件與發(fā)送純文本消息的郵件不同之處就是將 MIMEText 中 _subtype 設(shè)置為 html。具體代碼如下:
import smtplib
from email.mime.text import MIMEText
mailto_list=["YYY@YYY.com"]
mail_host="smtp.XXX.com" #設(shè)置服務(wù)器
mail_user="XXX" #用戶名
mail_pass="XXXX" #口令
mail_postfix="XXX.com" #發(fā)件箱的后綴
def send_mail(to_list,sub,content): #to_list:收件人;sub:主題;content:郵件內(nèi)容
me="hello"+"<"+mail_user+"@"+mail_postfix+">" #這里的hello可以任意設(shè)置,收到信后,將按照設(shè)置顯示
msg = MIMEText(content,_subtype='html',_charset='gb2312') #創(chuàng)建一個(gè)實(shí)例,這里設(shè)置為html格式郵件
msg['Subject'] = sub #設(shè)置主題
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
s = smtplib.SMTP()
s.connect(mail_host) #連接smtp服務(wù)器
s.login(mail_user,mail_pass) #登陸服務(wù)器
s.sendmail(me, to_list, msg.as_string()) #發(fā)送郵件
s.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(mailto_list,"hello","<a href='http://m.hgci.cn/'>W3Cschool</a>"):
print "發(fā)送成功"
else:
print "發(fā)送失敗"
或者你也可以在消息體中指定 Content-type 為 text/html,如下實(shí)例:
#!/usr/bin/python
import smtplib
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
發(fā)送帶附件的郵件,首先要?jiǎng)?chuàng)建 MIMEMultipart() 實(shí)例,然后構(gòu)造附件,如果有多個(gè)附件,可依次構(gòu)造,最后利用 smtplib.smtp 發(fā)送。
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
#創(chuàng)建一個(gè)帶附件的實(shí)例
msg = MIMEMultipart()
#構(gòu)造附件1
att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="123.doc"'#這里的filename可以任意寫(xiě),寫(xiě)什么名字,郵件中顯示什么名字
msg.attach(att1)
#構(gòu)造附件2
att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="123.txt"'
msg.attach(att2)
#加郵件頭
msg['to'] = 'YYY@YYY.com'
msg['from'] = 'XXX@XXX.com'
msg['subject'] = 'hello world'
#發(fā)送郵件
try:
server = smtplib.SMTP()
server.connect('smtp.XXX.com')
server.login('XXX','XXXXX')#XXX為用戶名,XXXXX為密碼
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.quit()
print '發(fā)送成功'
except Exception, e:
print str(e)
以下實(shí)例指定了 Content-type header 為 multipart/mixed,并發(fā)送 /tmp/test.txt 文本文件:
#!/usr/bin/python
import smtplib
import base64
filename = "/tmp/test.txt"
# 讀取文件內(nèi)容并使用 base64 編碼
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# 定義頭部信息
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# 定義消息動(dòng)作
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# 定義附近部分
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
print "Successfully sent email"
except Exception:
print "Error: unable to send email"
更多建議: