Python使用SMTP發送郵件


Python使用SMTP發送郵件

SMTPSimple Mail Transfer Protocol)即簡單郵件傳輸協議,它是一組用於由源地址到目的地址傳送郵件的規則,由它來控制信件的中轉方式。

pythonsmtplib提供了一種很方便的途徑發送電子郵件。它對smtp協議進行了簡單的封裝。

Python創建 SMTP 對象語法如下:

import smtplib

smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

參數說明:

  • host: SMTP 服務器主機。 你可以指定主機的ip地址或者域名如:w3cschool.cn,這個是可選參數。
  • port: 如果你提供了 host 參數, 你需要指定 SMTP 服務使用的端口號,一般情況下SMTP端口號為25
  • local_hostname: 如果SMTP在你的本機上,你只需要指定服務器地址為 localhost 即可。

Python SMTP對象使用sendmail方法發送郵件,語法如下:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]

參數說明:

  • from_addr: 郵件發送者地址。
  • to_addrs: 字符串列表,郵件發送地址。
  • msg: 發送消息

這里要注意一下第三個參數,msg是字符串,表示郵件。我們知道郵件一般由標題,發信人,收件人,郵件內容,附件等構成,發送郵件的時候,要注意msg的格式。這個格式就是smtp協議中定義的格式。

實例

以下是一個使用Python發送郵件簡單的實例:

#!/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"

Windows:

#!C:\Python27\python.exe

# -*- coding: utf-8 -*-

 

import smtplib

 

sender = 'quanweiru@163.com'

receivers = ['quanweiru@hotmail.com']

 

message = """From: From Person <quanweiru@163.com>

To: To Person <quanweiru@hotmail.com>

Subject: SMTP e-mail test

 

This is a test e-mail message.

"""

 

try:

   smtpObj = smtplib.SMTP('smtp.163.com')

   smtpObj.login('quanweiru@163.com','******')#XXX為用戶名,******為密碼

   smtpObj.sendmail(sender, receivers, message)

   smtpObj.quit()

   print "Successfully sent email"

except Exception, e:

   print "Error: unable to send email"

 

使用Python發送HTML格式的郵件

Python發送HTML格式的郵件與發送純文本消息的郵件不同之處就是將MIMEText_subtype設置為html。具體代碼如下:

import smtplib 
from email.mime.text import MIMEText 
mailto_list=["YYY@YYY.com"]
mail_host="smtp.XXX.com"  #
設置服務器
mail_user="XXX"    #
用戶名
mail_pass="XXXX"   #
口令
mail_postfix="XXX.com"  #
發件箱的后綴

 
def send_mail(to_list,sub,content):  #to_list
:收件人;sub:主題;content:郵件內容
    me="hello"+"<"+mail_user+"@"+mail_postfix+">"   #
這里的hello可以任意設置,收到信后,將按照設置顯示
    msg = MIMEText(content,_subtype='html',_charset='gb2312')    #
創建一個實例,這里設置為html格式郵件
    msg['Subject'] = sub    #
設置主題
    msg['From'] = me 
    msg['To'] = ";".join(to_list) 
    try: 
        s = smtplib.SMTP() 
        s.connect(mail_host)  #
連接smtp服務器
        s.login(mail_user,mail_pass)  #
登陸服務器
        s.sendmail(me, to_list, msg.as_string())  #
發送郵件
        s.close() 
        return True 
    except Exception, e: 
        print str(e) 
        return False 
if __name__ == '__main__': 
    if send_mail(mailto_list,"hello","<a href='http://www.cnblogs.com/xiaowuyi'>
小五義</a>"): 
        print "
發送成功
" 
    else: 
        print "
發送失敗
" 

或者你也可以在消息體中指定Content-typetext/html,如下實例:

#!/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"

Windows:

#!C:\Python27\python.exe

# -*- coding: utf-8 -*-

 

import smtplib

 

sender = 'quanweiru@163.com'

receivers = ['quanweiru@hotmail.com']

 

message = """From: From Person <quanweiru@163.com>

To: To Person <quanweiru@hotmail.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('smtp.163.com')

   #smtpObj.connect('smtp.163.com')

   smtpObj.login('xxx@163.com','******')#XXX為用戶名,******為密碼

   smtpObj.sendmail(sender, receivers, message)

   smtpObj.quit()

   print "Successfully sent email"

except Exception, e:

   print "Error: unable to send email"

clip_image001

 

Python發送帶附件的郵件

發送帶附件的郵件,首先要創建MIMEMultipart()實例,然后構造附件,如果有多個附件,可依次構造,最后利用smtplib.smtp發送。

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

#創建一個帶附件的實例
msg = MIMEMultipart()

#構造附件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可以任意寫,寫什么名字,郵件中顯示什么名字

msg.attach(att1)

#構造附件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'
#
發送郵件
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 '
發送成功
'
except Exception, e: 
    print str(e)

 

Windows:

#!C:\Python27\python.exe

# -*- coding: utf-8 -*-

 

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

import smtplib

 

#創建一個帶附件的實例

msg = MIMEMultipart()

 

#構造附件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可以任意寫,寫什么名字,郵件中顯示什么名字

msg.attach(att1)

 

#構造附件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'] = 'xxx@xxx.com'

msg['from'] = 'xxx@163.com'

msg['subject'] = 'hello world'

#發送郵件

try:

    server = smtplib.SMTP()

    server.connect('smtp.163.com')

    server.login('xxx@163.com','******')#XXX為用戶名,******為密碼

    server.sendmail(msg['from'], msg['to'],msg.as_string())

    server.quit()

    print '發送成功'

except Exception, e: 

    print str(e)

clip_image002

 

以下實例指定了Content-type header multipart/mixed,並發送/tmp/test.txt 文本文件:

#!/usr/bin/python

import smtplib
import base64

filename = "/tmp/test.txt"

# 讀取文件內容並使用 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)

# 定義消息動作
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"

 

Windows:

#!C:\Python27\python.exe

# -*- coding: utf-8 -*-

 

import smtplib

import base64

 

filename = r"D:\python\code\123.txt"

 

# 讀取文件內容並使用 base64 編碼

fo = open(filename, "rb")

filecontent = fo.read()

encodedcontent = base64.b64encode(filecontent)  # base64

 

sender = 'quanweiru@163.com'

reciever = 'quanweiru@hotmail.com'

 

marker = "AUNIQUEMARKER"

 

body ="""

This is a test email to send an attachement.

"""

# 定義頭部信息

part1 = """From: From Person <quanweiru@163.com>

To: To Person <quanweiru@hotmail.com>

Subject: Sending Attachement

MIME-Version: 1.0

Content-Type: multipart/mixed; boundary=%s

--%s

""" % (marker, marker)

 

# 定義消息動作

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('smtp.163.com')

   smtpObj.login('xxx@163.com','xxxxxx')#XXX為用戶名,XXXXX為密碼

   smtpObj.sendmail(sender, reciever, message)

   smtpObj.quit()

   print "Successfully sent email"

except Exception:

   print "Error: unable to send email"

 

clip_image003


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM