python smtplib email

監控系統須要觸發報警郵件, 簡單筆記一下的用到的庫.html

 

smtplib

class smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])

返回一個 smtp 實例, 若是指定了 host 和 port, 會調用 SMTP.connect() 進行鏈接, timout 指定超時時間python

 

class smtplib.SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]])

返回一個 ssl 模式的 smtp 實例, 僅在 SMTP.starttls() 沒法或不推薦時使用服務器

 

SMTP.set_debuglevel(level)

設置 debug 輸出級別. 若是 level 設定爲真值, 則會輸出全部的調試信息和整個鏈接過程當中收到和發送的信息.ide

 

SMTP.connect([host[, port]])

鏈接到指定 host 的端口. 默認 host 爲 localhost, 默認端口爲25測試

 

SMTP.helo([hostname])

跟 SMTP 郵件服務器介紹下本身, 通常狀況下不須要直接執行此命令, 直接調用 SMTP.sendmail()ui

 

SMTP.ehlo([hostname])

跟 ESMTP 郵件服務器 say hellothis

 

SMTP.verify(address)

確認郵件地址的有效性, 若是有效會返回 code 250 和完成的有點地址, 大部分郵件服務器會屏蔽此命令以防垃圾郵件spa

 

SMTP.login(userpassword)

登陸到郵件服務器debug

 

SMTP.starttls([keyfile[, certfile]])

 

將 smtp 鏈接切換到 tls 模式調試

 

SMTP.sendmail(from_addrto_addrsmsg[, mail_optionsrcpt_options])

發郵件

from_addr    string    發件人

to_addrs       list        收件人

msg             string     信息

 

SMTP.quit()

終止 smtp 會話, 關閉連接.

 

SMTP Example

import smtplib

def prompt(prompt):
    return raw_input(prompt).strip()

fromaddr = prompt("From: ")
toaddrs  = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, ", ".join(toaddrs)))
while 1:
    try:
        line = raw_input()
    except EOFError:
        break
    if not line:
        break
    msg = msg + line

print "Message length is " + repr(len(msg))

server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

注意到 msg 須要添加一個郵件頭, 格式是 

"""

From: test@gmail.com

To: test@gmail.com, test1@gmail.com, test2@gmail.com



郵件正文

"""

顯然這樣攢 msg 不是一個好辦法, 因此 python 提供了 email

 

郵件發送 html 

#!/usr/bin/env python

import smtplib

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

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttps://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="https://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

1. 注意到 MIMEMultipart 和 MIMEText, 從返回對象的關係看, MIMEText 的對象能夠被 attach 到 MIMEMultipart 返回的對象上

2. 若是實際測試這段代碼, 會發現雖然 attach 兩次, 可是收到的只有一個 html 的內容, 這跟 MIMEMultipart("alternative") 有關

3. 若是初始化時選擇 MIMEMultipart("mixed"), 會發現郵件內容是 text 文本, 同時攜帶一個 .html 的附件

4. 若是隻選擇 attach(part2), 發現郵件內容是 html

5. MIMEMultipart 的實例, 包含郵件標題 Subject, 發件人 From, 收件人 To, 最後 attach MIMEText 的實例

6. 這裏注意, 若是有多個收件人, To 應該是以 ; 間隔的字符串,  雖然使用 , 間隔也能夠成功, 可是 ; 是標準的寫法

7. 這跟 sendmail 中的收件人是不一樣的, sendmail 中的收件人是 list 列表, 若是把 To 做爲參數傳給 sendmail, 那麼只會有第一我的收到郵件 

 

class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]])

_subtype

multipart/mixed

A number of different resources are combined in a single message.             

 

multipart/alternative

The section 5.1.4 of RFC 2046 defines multipart/alternative MIME type to allow the sender to provide different, interchangeable representations of the same message and to leave it up to the receiver to chose the form of presentation most suitable for its capabilities

 

class email.mime.text.MIMEText(_text[, _subtype[, _charset]])

若是發送中文, 須要指定 _charset="utf8"

相關文章
相關標籤/搜索