python初級實戰-----關於郵件傳送問題
python發郵件需要掌握兩個模組的用法,smtplib和email,這倆模組是python自帶的,只需import即可使用。smtplib模組主要負責傳送郵件,email模組主要負責構造郵件。
smtplib模組主要負責傳送郵件:是一個傳送郵件的動作,連線郵箱伺服器,登入郵箱,傳送郵件(有發件人,收信人,郵件內容)。
email模組主要負責構造郵件:指的是郵箱頁面顯示的一些構造,如發件人,收件人,主題,正文,附件等。
1.smtplib模組
smtplib使用較為簡單。以下是最基本的語法。
匯入及使用方法如下:
import smtplib smtp = smtplib.SMTP() smtp.connect('smtp.163.com,25') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
說明:
1)smtplib.SMTP():例項化SMTP()
2)smtp.connect(host,port): host:指定連線的郵箱伺服器。常用郵箱的smtp伺服器地址如下:
新浪郵箱:smtp.sina.com,新浪VIP:smtp.vip.sina.com,搜狐郵箱:smtp.sohu.com,126郵箱:smtp.126.com,139郵箱:smtp.139.com,163網易郵箱:smtp.163.com。
port:指定連線伺服器的埠號,預設為25.
3)smtp.login(user,password):
user:登入郵箱的使用者名稱。password:登入郵箱的密碼,需要在網頁版的網易郵箱中設定授權碼,該授權碼即為客戶端密碼。
4)sendmail(from_addr,to_addrs,msg,...):
from_addr:郵件傳送者地址; to_addrs:郵件接收者地址。字串列表['接收地址1','接收地址2','接收地址3',...]或'接收地址'
5)msg:傳送訊息:郵件內容。一般是msg.as_string():as_string()是將msg(MIMEText物件或者MIMEMultipart物件)變為str。
6)quit():用於結束SMTP會話。
2.email模組
email模組下有mime包,mime英文全稱為“Multipurpose Internet Mail Extensions”,即多用途網際網路郵件擴充套件,是目前網際網路電子郵件普遍遵循的郵件技術規範。
該mime包下常用的有三個模組: text ,image, multpart 。
匯入方法如下:
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage
構造一個郵件物件就是一個 Message
物件,如果構造一個 MIMEText
物件,就表示一個文字郵件物件,如果構造一個 MIMEImage
物件,就表示一個作為附件的圖片,要把多個物件組合起來,就用 MIMEMultipart
物件,而 MIMEBase
可以表示任何物件。它們的繼承關係如下:
Message +- MIMEBase#表示任何物件 +- MIMEMultipart +- MIMENonMultipart#把多個物件組合起來 +- MIMEMessage +- MIMEText#文字 +- MIMEImage#作為附件的圖片
2.1 multpart說明
常見的multipart型別有三種:multipart/alternative, multipart/related和multipart/mixed。
郵件型別為"multipart/alternative"的郵件包括純文字正文(text/plain)和超文字正文(text/html)。
郵件型別為"multipart/related"的郵件正文中包括圖片,聲音等內嵌資源。
郵件型別為"multipart/mixed"的郵件包含附件。向上相容,如果一個郵件有純文字正文,超文字正文,內嵌資源,附件,則選擇mixed型別。
msg = MIMEMultipart('mixed')
我們必須把Subject,From,To新增到MIMEText物件或者MIMEMultipart物件中,郵件中才會顯示主題,發件人,收件人。
msg = MIMEMultipart('mixed') msg['Subject'] = '這是一個標題' msg['From'] = '[email protected] <[email protected]>' msg['To'] = '[email protected]'
2.2 傳送文字郵件
2.2 傳送文字郵件
郵件傳送程式為了防止有些郵件閱讀軟體不能顯示處理HTML格式的資料,通常都會用兩型別分別為"text/plain"和"text/html"
構造MIMEText物件時,第一個引數是郵件正文,第二個引數是MIME的subtype,最後一定要用utf-8編碼保證多語言相容性。
以上的構造的文字新增到MIMEMultipart('mixed')中
建立一個普通文字:
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com" text_plain = MIMEText(text, 'plain', 'utf-8') msg.attach(text_plain)
僅傳送文字郵件:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # 設定smtplib所需的引數 smtpserver = 'smtp.163.com' username = '[email protected]' password = 'xxxxxmima' sender = '[email protected]' receiver=['[email protected]'] # 收件人為多個收件人 #receiver = ['[email protected]', '[email protected]'] # 構造郵件物件MIMEMultipart物件 msg = MIMEMultipart('mixed') msg['Subject'] = '這個是郵件主題' msg['From'] = '[email protected] <[email protected]>' msg['To'] = '[email protected]' # 收件人為多個收件人,通過join將列表轉換為以;為間隔的字串 #msg['To'] = ";".join(receiver) # 構造文字內容 text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com" text_plain = MIMEText(text, 'plain', 'utf-8') msg.attach(text_plain) # 呼叫smtplib模組傳送郵件 smtp = smtplib.SMTP() smtp.connect('smtp.163.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
2.3 傳送超文字附件
內容格式:
html = """ <html> <body> <p> Here is the <a href="http://www.sohu.com">link</a> you wanted. </p> </body> </html> """ text_html = MIMEText(html,'html', 'utf-8') text_html["Content-Disposition"] = 'attachment; filename="baidu.html"' msg.attach(text_html)
2.4 傳送圖片
新增圖片:
# 構造圖片連結 sendimagefile = open(r'D:\0.jpg', 'rb').read() image = MIMEImage(sendimagefile) image.add_header('Content-ID', '<image1>') image["Content-Disposition"] = 'attachment; filename="testimage.png"' msg.attach(image)
僅傳送圖片附件:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage # 設定smtplib所需的引數 smtpserver = 'smtp.163.com' username = '[email protected]' password = 'xxxxxmima' sender = '[email protected]' receiver=['[email protected]'] # 收件人為多個收件人 #receiver = ['[email protected]', '[email protected]'] # 構造郵件物件MIMEMultipart物件 msg = MIMEMultipart('mixed') msg['Subject'] = '這個是郵件主題' msg['From'] = '[email protected] <[email protected]>' msg['To'] = '[email protected]' # 收件人為多個收件人,通過join將列表轉換為以;為間隔的字串 #msg['To'] = ";".join(receiver) # 構造圖片連結 sendimagefile = open(r'D:\0.jpg', 'rb').read() image = MIMEImage(sendimagefile) image.add_header('Content-ID', '<image1>') image["Content-Disposition"] = 'attachment; filename="testimage.png"' msg.attach(image) # 呼叫smtplib模組傳送郵件 smtp = smtplib.SMTP() smtp.connect('smtp.163.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
2.5傳送附件
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage # 設定smtplib所需的引數 smtpserver = 'smtp.163.com' username = '[email protected]' password = 'xxxxxmima' sender = '[email protected]' receiver = ['[email protected]', '[email protected]'] # 構造郵件物件MIMEMultipart物件 msg = MIMEMultipart('mixed') msg['Subject'] = '一個附件' msg['From'] = '[email protected] <[email protected]>' msg['To'] = ";".join(receiver) # 構造附件 sendfile = open(r'D:\111.txt', 'rb').read() text_att = MIMEText(sendfile, 'base64', 'utf-8') text_att["Content-Type"] = 'application/octet-stream' # 以下附件可以重新命名成aaa.txt text_att["Content-Disposition"] = 'attachment; filename="aaa.txt"' msg.attach(text_att) # 傳送郵件 smtp = smtplib.SMTP() smtp.connect('smtp.163.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
2.6文字,html,圖片,附件實現例項
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage # 設定smtplib所需的引數 smtpserver = 'smtp.163.com' username = '[email protected]' password = 'xxxxxmima' sender = '[email protected]' receiver = ['[email protected]', '[email protected]'] # 構造郵件物件MIMEMultipart物件 msg = MIMEMultipart('mixed') msg['Subject'] = '一個測試郵件' msg['From'] = '[email protected] <[email protected]>' msg['To'] = ";".join(receiver) # 構造文字內容 text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com" text_plain = MIMEText(text, 'plain', 'utf-8') msg.attach(text_plain) # 構造圖片連結 sendimagefile = open(r'D:\0.jpg', 'rb').read() image = MIMEImage(sendimagefile) image.add_header('Content-ID', '<image1>') image["Content-Disposition"] = 'attachment; filename="testimage.png"' msg.attach(image) # 構造html html = """ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> </p> </body> </html> """ text_html = MIMEText(html, 'html', 'utf-8') text_html["Content-Disposition"] = 'attachment; filename="texthtml.html"' msg.attach(text_html) # 構造附件 sendfile = open(r'D:\111.txt', 'rb').read() text_att = MIMEText(sendfile, 'base64', 'utf-8') text_att["Content-Type"] = 'application/octet-stream' # 以下附件可以重新命名成aaa.txt text_att["Content-Disposition"] = 'attachment; filename="aaa.txt"' msg.attach(text_att) # 傳送郵件 try: smtp = smtplib.SMTP() smtp.connect('smtp.163.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() print("郵件傳送成功") except smtplib.SMTPException: print("Error: 無法傳送郵件")