python發送郵件

python發送郵件

準備

python中發送郵件主要用的是smtplib和email兩個模塊,下面主要對這兩個模塊進行講解html

在講解以前須要準備至少兩個測試的郵箱,其中要在郵箱的設置中開啓smtplib協議才能夠進行發送和接受python

smtplib

  • smtplib.SMTP( [host [, port [, local_hostname[,timeout]]]]) hostSMTP主機的服務器,其中163郵箱的是smtp.163.com,其餘的能夠在網上找到,port是端口號,這裏默認的是25local_hostname是你主機的SMTP,若是SMTP在你的本機上,你只須要指定服務器地址爲 localhost 便可。timeout是設置的鏈接的限制時間,若是超過這個時間尚未鏈接上那麼就會出現錯誤git

  • SMTP.set_debuglevel(level):設置是否爲調試模式。默認爲False,即非調試模式,表示不輸出任何調試信息。若是設置爲1就表示輸出調試信息github

  • SMTP.connect([host[, port]]):鏈接到指定的smtp服務器。參數分別表示smpt主機和端口。注意: 也能夠在host參數中指定端口號(如:smpt.yeah.net:25),這樣就不必給出port參數。服務器

  • SMTP.login(user, password) 登陸服務器,這裏的user是郵箱的用戶名,可是這裏的password並非你郵箱的密碼,當你開啓SMTP的時候會提示你設置一個密碼,這裏的密碼就是對應的密碼app

  • SMTP.sendmail(from_addr, [to_addrs,], msg[, mail_options, rcpt_options]) 發送郵件,from_addr是發送方也就是你的郵箱地址,to_addr是接受方的地址,固然這裏的能夠填上多個郵箱帳號發送給多個帳號,若是有多個帳號須要使用列表傳遞參數函數

  • SMTP.quit()斷開鏈接測試

email

emial模塊用來處理郵件消息,包括MIME和其餘基於RFC 2822 的消息文檔。使用這些模塊來定義郵件的內容,是很是簡單的。其包括的類有(更加詳細的介紹可見:http://docs.python.org/librar...):ui

  • class email.mime.base.MIMEBase(_maintype, _subtype, **_params):這是MIME的一個基類。通常不須要在使用時建立實例。其中_maintype是內容類型,如text或者image。_subtype是內容的minor type 類型,如plain或者gif**_params是一個字典,直接傳遞給Message.add_header()。編碼

  • class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]MIMEBase的一個子類,多個MIME對象的集合,_subtype默認值爲mixedboundaryMIMEMultipart的邊界,默認邊界是可數的。當須要發送附件的時候使用的就是這個類

  • class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]])MIMEMultipart的一個子類。

  • class email.mime.audio. MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]])MIME音頻對象

  • class email.mime.image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]])MIME二進制文件對象。主要用來發送圖片

普通文本郵件

  • class email.mime.text.MIMEText(_text[, _subtype[, _charset]])MIME文本對象,其中_text是郵件內容,_subtype郵件類型,能夠是text/plain(普通文本郵件),html/plain(html郵件), _charset編碼,能夠是gb2312等等。

  • 普通文本郵件發送的實現,關鍵是要將MIMEText_subtype設置爲plain。首先導入smtplibmimetext。建立smtplib.smtp實例,connect郵件smtp服務器,login後發送,具體代碼以下*

# 一個格式化郵件的函數,能夠用來使用
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((
        Header(name, 'utf-8').encode(),
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))

from_addr='××××××××'   #你的郵箱地址
from_password='×××××××'   #你的密碼
# to_email='chenjiabing666@yeah.net'
to_email='××××××'    #要發送的郵箱地址

msg=MIMEText('喬裝打扮,不擇手段','plain','utf-8')  #這裏text=喬裝打扮,不擇手段

msg['From'] = _format_addr(u'Python愛好者 <%s>' % from_addr)  #格式化發件人
msg['To'] = _format_addr(u'管理員 <%s>' % to_email)    #格式化收件人
msg['Subject'] = Header(u'來自SMTP的問候……', 'utf-8').encode()    #格式化主題

stmp='smtp.163.com'
server=smtplib.SMTP(stmp,port=25,timeout=30) #鏈接,設置超時時間30s
server.login(from_addr,from_password)    #登陸
server.set_debuglevel(1)        #輸出全部的信息
server.sendmail(from_addr,to_email,msg.as_string())   #這裏的as_string()是將msg轉換成字符串類型的,若是你想要發給多我的,須要講to_email換成一個列表

發送html郵件

仍是用MIMEText來發送,不過其中的_subType設置成html便可,詳細代碼以下:

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((
        Header(name, 'utf-8').encode(),
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))

from_addr='××××××××'   #你的郵箱地址
from_password='×××××××'   #你的密碼
# to_email='chenjiabing666@yeah.net'
to_email='××××××'    #要發送的郵箱地址
html="""
<p><h1 style="color:red">你們好</h1></p>
"""

msg=MIMEText(html,'html','utf-8')  #這裏text=html,設置成html格式的

msg['From'] = _format_addr(u'Python愛好者 <%s>' % from_addr)  #格式化發件人
msg['To'] = _format_addr(u'管理員 <%s>' % to_email)    #格式化收件人
msg['Subject'] = Header(u'來自SMTP的問候……', 'utf-8').encode()    #格式化主題

stmp='smtp.163.com'
server=smtplib.SMTP(stmp,port=25,timeout=30) #鏈接,設置超時時間30s
server.login(from_addr,from_password)    #登陸
server.set_debuglevel(1)        #輸出全部的信息
server.sendmail(from_addr,to_email,msg.as_string())   #這裏的as_string()是將msg轉換成字符串類型的,若是你想要發給多我的,須要講to_email換成一個列表

附件的發送

發送帶附件的郵件,首先要建立MIMEMultipart()實例,而後構造附件,若是有多個附件,可依次構造,最後利用smtplib.smtp發送,具體實力以下:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((
        Header(name, 'utf-8').encode(),
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))

from_addr='××××××××'   #你的郵箱地址
from_password='×××××××'   #你的密碼
# to_email='chenjiabing666@yeah.net'
to_email='××××××'    #要發送的郵箱地址


msg=MIMEMultipart()   #建立實例
text=MIMEText('<h2 style="color:red">陳加兵</h2><br/><p>你們好</p>','html','utf-8')
msg.attach(text)   #添加一個正文信息,這裏實在正文中顯示的信息

#建立一個文本附件,這裏是從指定文本中讀取信息,而後建立一個文本信息
att1=MIMEText(open('/home/chenjiabing/文檔/MeiZi_img/full/file.txt','rb').read(),'plain','utf-8')
att1["Content-Type"] = 'application/octet-stream'  #指定類型
att1["Content-Disposition"] = 'attachment; filename="123.txt"'#這裏的filename能夠任意寫,寫什麼名字,郵件中顯示什麼名字
msg.attach(att1)     #向其中添加附件

img_path='/home/chenjiabing/文檔/MeiZi_img/full/file.jpg'  #圖片路徑
image=MIMEImage(open(img_path,'rb').read())     #建立一個圖片附件
image.add_header('Content-ID','<0>')   #指定圖片的編號,這個會在後面用到
image.add_header('Content-Disposition', 'attachment', filename='test.jpg')        
image.add_header('X-Attachment-Id', '0')
msg.attach(image)    #添加附件


stmp='smtp.163.com'
server=smtplib.SMTP(stmp,port=25,timeout=30) #鏈接,設置超時時間30s
server.login(from_addr,from_password)    #登陸
server.set_debuglevel(1)        #輸出全部的信息
server.sendmail(from_addr,to_email,msg.as_string())   #這裏的as_string()是將msg轉換成字符串類型的,若是你想要發給多我的,須要講to_email換成一個列表

將圖片嵌入到正文信息中

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((
        Header(name, 'utf-8').encode(),
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))

from_addr='××××××××'   #你的郵箱地址
from_password='×××××××'   #你的密碼
# to_email='chenjiabing666@yeah.net'
to_email='××××××'    #要發送的郵箱地址


msg=MIMEMultipart()   #建立實例
html="""
<html>
<head></head>
<body>
<p>下面演示嵌入圖片</p>
<section>
<img src='cid:0' style='float:left'/>
<img src='cid:1' style='float:left'/>
</setcion>
</body>
</html>
"""

text=MIMEText('<h2 style="color:red">陳加兵</h2><br/><p>你們好</p>','html','utf-8')
msg.attach(text)   #添加一個正文信息,這裏實在正文中顯示的信息

#建立一個文本附件,這裏是從指定文本中讀取信息,而後建立一個文本信息
att1=MIMEText(open('/home/chenjiabing/文檔/MeiZi_img/full/file.txt','rb').read(),'plain','utf-8')
att1["Content-Type"] = 'application/octet-stream'  #指定類型
att1["Content-Disposition"] = 'attachment; filename="123.txt"'#這裏的filename能夠任意寫,寫什麼名字,郵件中顯示什麼名字
msg.attach(att1)     #向其中添加附件


## 建立一個圖片附件
img_path='/home/chenjiabing/文檔/MeiZi_img/full/file.jpg'  #圖片路徑
image=MIMEImage(open(img_path,'rb').read())     #建立一個圖片附件
image.add_header('Content-ID','<0>')   #指定圖片的編號,
image.add_header('Content-Disposition', 'attachment', filename='test.jpg')        
image.add_header('X-Attachment-Id', '0')
msg.attach(image)    #添加附件

#建立第二個圖片附件
img_path_1='/home/chenjiabing/文檔/MeiZi_img/full/test.jpg'  #圖片路徑
image1=MIMEImage(open(img_path,'rb').read())     #建立一個圖片附件
image1.add_header('Content-ID','<1>')   #指定圖片的編號,這個就是在上面對應的cid:1的那張圖片,所以這裏的編號必定要對應
image1.add_header('Content-Disposition', 'attachment', filename='img.jpg')        
image1.add_header('X-Attachment-Id', '0')
msg1.attach(image)    #添加附件



stmp='smtp.163.com'
server=smtplib.SMTP(stmp,port=25,timeout=30) #鏈接,設置超時時間30s
server.login(from_addr,from_password)    #登陸
server.set_debuglevel(1)        #輸出全部的信息
server.sendmail(from_addr,to_email,msg.as_string())   #這裏的as_string()是將msg轉換成字符串類型的,若是你想要發給多我的,須要講to_email換成一個列表

更多文章請移步本人博客https://chenjiabing666.github.io/

相關文章
相關標籤/搜索