【Python】SMTP傳送郵件
阿新 • • 發佈:2018-12-27
Python SMTP傳送郵件
一、郵件的幾個要素
使用程式碼發郵件的好處
- 可以批量發郵件,減少人工勞動
- 可以自動,定時,報警,報告等需求
電子郵件的工作原理
簡單郵件傳輸協議(Simple Mail Transfer Protocol, SMTP)
是事實上的在Internet
傳輸Email
的標準。SMTP是一個相對簡單的基於文字的協議。在其之上指定了一條訊息的一個或多個接收者 (在大多數情況下被確認是存在的) ,然後訊息文字會被傳輸。
傳送郵件分幾步?
- 開啟郵件
- 登陸
- 寫正文
- 傳送
- 退出
Python裡面怎麼發郵件?
smtplib模組,使用smtp物件進行各種操作
方法 | 描述 |
---|---|
SMTP.set_debuglevel(level) |
設定輸出debug除錯資訊,預設不輸出 |
SMTP.docmd(cmd[,argstring] | 傳送一個命令到SMTP伺服器) |
SMTP.connect ([host[, port]]) | 連線到指定的SMTP伺服器 |
SMTP.helo([hostname]) | 使用helo指令向SMTP伺服器確認你的身份 |
SMTP.ehlo(hostname) |
使用ehlo指令像ESMTP(SMTP擴充套件)確認你的身份 |
SMTP.ehlo_or_helo_if_needed() | 如果在以前的會話連線中沒有提供ehlo或者helo指令,這個方法會呼叫ehlo()或helo() |
SMTP.has_extn(name) | 判斷指定名稱是否在SMTP伺服器上 |
SMTP.verify(address) | 判斷郵件地址是否在SMTP伺服器上 |
SMTP.starttls([keyfile[, certfile]]) | 使SMTP連線執行在TLS模式,所有的SMTP指令都會被加密 |
SMTP.login(user, password) |
登入SMTP伺服器 |
SMTP.sendmail(from_addr, to_addrs, msg,mail_options=[], rcpt_options=[]) | 傳送郵件 from_addr:郵件發件人 to_addrs:郵件收件人 msg:傳送訊息 |
SMTP.quit() |
關閉SMTP會話 |
SMTP.close() | 關閉SMTP伺服器連線 |
怎麼使用Python發郵件?
Python建立 SMTP 物件語法如下:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
引數說明:
- host: SMTP 伺服器主機。 你可以指定主機的ip地址或者域名如: csdn.com,這個是可選引數。
- 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 協議中定義的格式。
發個郵件普通郵件
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import smtplib
from smtplib import SMTP_SSL
from email.header import Header
from email.mime.text import MIMEText
def get_password(): # 獲取郵箱授權碼
return "郵箱授權碼"
def send_email(username):
smtp = SMTP_SSL("smtp.qq.com","465") # 郵件伺服器地址
smtp.login("[email protected]", get_password()) # 郵件賬戶密碼
text = f"{username}: \n 歡迎來到'延瓚@Yankerp'CSDN部落格站點..."
msg = MIMEText(text, "plain", "utf-8")
msg["Subject"] = Header("歡迎您來到延瓚@Yankerp", "utf-8") # 郵件的標題.
msg["from"] = "[email protected]"
msg["to"] = "[email protected]"
smtp.sendmail("[email protected]", "[email protected]", msg.as_string())
smtp.quit()
if __name__ == "__main__":
send_email("親")
發個帶附件郵件
def send_email_attach(body, attachment):
smtp = SMTP_SSL("smtp.qq.com") # 郵件伺服器地址
smtp.login("[email protected]", get_password()) # 郵件賬戶密碼
msg = MIMEMultipart() # 構造一個MIMEMultipart物件代表郵件本身
msg["Subject"] = Header("歡迎您來到延瓚@Yankerp", "utf-8")
# plain代表純文字
msg.attach(MIMEText(body, "plain", "utf-8"))
with open(attachment, "rb") as f:
mime = MIMEBase("text", "txt", filename=attachment)
mime.add_header("Content-Disposition", "attachment", filename=attachment)
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
try:
smtp.sendmail("[email protected]", "[email protected]", msg.as_string())
smtp.quit()
except smtplib.SMTPException as e:
print(e)
if __name__ == "__main__":
# send_email("親")
send_email_attach("親", r"D:\文件\csdn.md")
帶個html
def send_email_all(body, maintype="plain", attachment=None):
smtp = SMTP_SSL("smtp.qq.com") # 郵件伺服器地址
smtp.login("[email protected]", get_password()) # 郵件賬戶密碼
smtp.set_debuglevel(1)
msg = MIMEMultipart() # 構造一個MIMEMultipart物件代表郵件本身
msg["Subject"] = Header("歡迎您來到延瓚@Yankerp", "utf-8")
# plain代表純文字
msg.attach(MIMEText(body, maintype, "utf-8"))
if attachment:
with open(attachment, "rb") as f:
mime = MIMEBase("text", "txt", filename=attachment)
mime.add_header("Content-Disposition", "attachment", filename=attachment)
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
try:
smtp.sendmail("[email protected]", "[email protected]", msg.as_string())
smtp.quit()
except smtplib.SMTPException as e:
print(e)
if __name__ == "__main__":
send_email_all(html, "html", r"D:\文件\監控平臺.txt")
"""
html = """
<h1>Welcome to [email protected]</h1>
<h2>info</h2>
<table border="1">
<tr>
<th>姓名</th>
<th>城市</th>
</tr>
<tr>
<td>Yankerp</td>
<td>北京</td>
</tr>
</table>
測試程式碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import smtplib
from smtplib import SMTP_SSL
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def get_password(): # 獲取郵箱授權碼
return "郵箱授權碼"
def send_email(username):
smtp = SMTP_SSL("smtp.qq.com", "465") # 郵件伺服器地址
smtp.login("[email protected]", get_password()) # 郵件賬戶密碼
text = f"{username}: \n 歡迎來到'延瓚@Yankerp'CSDN部落格站點..."
msg = MIMEText(text, "plain", "utf-8")
msg["Subject"] = Header("歡迎您來到延瓚@Yankerp", "utf-8") # 郵件的標題.
# msg["from"] = "[email protected]"
# msg["to"] = "[email protected]"
smtp.sendmail("[email protected]", "[email protected]", msg.as_string())
smtp.quit()
def send_email_attach(body, attachment):
smtp = SMTP_SSL("smtp.qq.com") # 郵件伺服器地址
smtp.login("[email protected]", get_password()) # 郵件賬戶密碼
msg = MIMEMultipart() # 構造一個MIMEMultipart物件代表郵件本身
msg["Subject"] = Header("歡迎您來到延瓚@Yankerp", "utf-8")
# plain代表純文字
msg.attach(MIMEText(body, "plain", "utf-8"))
with open(attachment, "rb") as f:
mime = MIMEBase("text", "txt", filename=attachment)
mime.add_header("Content-Disposition", "attachment", filename=attachment)
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
try:
smtp.sendmail("[email protected]", "[email protected]", msg.as_string())
smtp.quit()
except smtplib.SMTPException as e:
print(e)
def send_email_all(body, maintype="plain", attachment=None):
smtp = SMTP_SSL("smtp.qq.com") # 郵件伺服器地址
smtp.login("[email protected]", get_password()) # 郵件賬戶密碼
smtp.set_debuglevel(1)
msg = MIMEMultipart() # 構造一個MIMEMultipart物件代表郵件本身
msg["Subject"] = Header("歡迎您來到延瓚@Yankerp", "utf-8")
# plain代表純文字
msg.attach(MIMEText(body, maintype, "utf-8"))
if attachment:
with open(attachment, "rb") as f:
mime = MIMEBase("text", "txt", filename=attachment)
mime.add_header("Content-Disposition", "attachment", filename=attachment)
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
try:
smtp.sendmail("[email protected]", "[email protected]", msg.as_string())
smtp.quit()
except smtplib.SMTPException as e:
print(e)
html = """
<h1>Welcome to [email protected]</h1>
<h2>info</h2>
<table border="1">
<tr>
<th>姓名</th>
<th>城市</th>
</tr>
<tr>
<td>Yankerp</td>
<td>北京</td>
</tr>
</table>
"""
if __name__ == "__main__":
# send_email("親")
# send_email_attach("親", r"D:\文件\csdn.md")
send_email_all(html, "html", r"D:\文件\監控平臺.txt")