python學習(十四)python操作發送郵件(163郵箱)


一、163郵箱
1、先導入smtplib庫來發送郵件,導入MIMEText庫用來做純文本的郵件模塊
2、准備發送郵件參數

import smtplib
from email.mime.text import MIMEText

# 發送郵件相關參數
smtpserver = 'smtp.163.com'         # 發件服務器
port = 0                            # 端口
sender = 'zhu1308331523@163.com'         # 發件人郵箱
psw = '*******'                            # 發件人密碼
receiver = "214256271@qq.com"       # 接收人
'''
3、編寫郵件主題和正文,正文用的html格式
4、最后調用發件服務
'''
# 編輯郵件內容
subject = '郵件主題'
body = '<p>這是個發送郵件的正文</p>'  # 定義郵件正文為html
msg = MIMEText(body, 'html', 'utf-8')
msg['from'] = sender
msg['to'] = "214256271@qq.com"
msg['subject'] = subject
# 發送郵件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)    # 鏈接服務器
smtp.login(sender, psw)     # 登錄
smtp.sendmail(sender, receiver, msg.as_string())  # 發送
smtp.quit()             # 關閉

 

可能出現的報錯

python smtplib.SMTPAuthenticationError: (535, b'Error: authentication failed')

解決辦法:163郵箱開啟POP3/SMTP服務,163郵件會讓我們設置客戶端授權碼代替發送的密碼填寫進入,就可以發送成功了

二、帶 附件的發送郵件

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

# 發送郵件相關參數
smtpserver = 'smtp.163.com'         # 發件服務器
port = 0                            # 端口
sender = 'zhu1308331523@163.com'         # 發件人郵箱
psw = '******'                            # 發件人密碼
receiver = "214256271@qq.com"       # 接收人
# 郵件標題
subjext = 'python發送附件郵件'
# 獲取附件信息
with open('result.html', "rb") as f:
    body = f.read().decode()
message = MIMEMultipart()
# 發送地址
message['from'] = sender
message['to'] = receiver
message['subject'] = subjext
# 正文
body = MIMEText(body, 'html', 'utf-8')
message.attach(body)
# 同一目錄下的文件
att = MIMEText(open('result.html', 'rb').read(), 'base64', 'utf-8') 
att["Content-Type"] = 'application/octet-stream'
# filename附件名稱
att["Content-Disposition"] = 'attachment; filename="result.html"'
message.attach(att)
smtp = smtplib.SMTP()
smtp.connect(smtpserver)    # 鏈接服務器
smtp.login(sender, psw)     # 登錄
smtp.sendmail(sender, receiver, message.as_string())  # 發送
smtp.quit()             # 關閉

三、發送多個收件人

'''
1.上面都是發給一個收件人,那么如何一次發給多個收件人呢?只需改兩個小地方
2.把receiver參數改成list對象,單個多個都是可以收到的
3、msg["to"]這個參數不能用list了,得先把receiver參數轉化成字符串
'''
# receiver = ["214256271@qq.com", "130@qq.com"]
# message['to'] = ";".json(receiver)

 


免責聲明!

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



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