qq賬號發送郵箱登陸密碼需要用授權碼。
可以看我的這個文章:
Python 技術篇-qq郵箱授權碼開通
實現原理
我們用圖片和文檔兩種類型的附件舉個例子。
MIMEBase(",")
這個裏只要有兩個字符串參數就好了。可以隨便填。
m_img.add_header('Content-Disposition', 'attachment', filename = "...")
filename 對應的名字填上就好了,展示就是靠這個名字來識別的,是展示爲圖片樣式或是word文檔樣式。
#!/user/bin/env python
# -*- coding:utf-8 -*-
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
message = MIMEMultipart() # 郵件主體
# 郵件加入圖片
m_img = MIMEBase('', '')
m_img.add_header('Content-Disposition', 'attachment', filename = "hello.jpg")
f = open("hello.jpg", "rb") # 讀取本地圖片
m_img.set_payload(f.read())
encoders.encode_base64(m_img)
message.attach(m_img)
# 郵件加入文檔
m_file = MIMEBase('', '')
m_file.add_header('Content-Disposition', 'attachment', filename = "hello.doc")
f = open("hello.doc", "rb") # 讀取本地文檔
m_file.set_payload(f.read())
encoders.encode_base64(m_file)
message.attach(m_file)
message['From'] = Header('小愛') # 郵件發送者名字
message['To'] = Header('小藍棗') # 郵件接收者名字
message['Subject'] = Header('來自異世界的一封信!') # 郵件主題
mail = smtplib.SMTP()
mail.connect("smtp.qq.com") # 連接 qq 郵箱
mail.login("[email protected]", "授權碼") # 賬號和授權碼
mail.sendmail("[email protected]", ["[email protected]"], message.as_string()) # 發送賬號、接收賬號和郵件信息
運行效果圖:
喜歡的點個贊❤吧!