import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication# 寫成了一個通用的函數接口,想直接用的話,把參數的注釋去掉就好
def send_email(msg_from, passwd, msg_to, text_content, file_path=None):msg = MIMEMultipart()subject = "python 實現郵箱發送郵件" # 主題text = MIMEText(text_content)msg.attach(text)# file_path = r'read.md' #如果需要添加附件,就給定路徑if file_path: # 最開始的函數參數我默認設置了None ,想添加附件,自行更改一下就好docFile = file_pathdocApart = MIMEApplication(open(docFile, 'rb').read())docApart.add_header('Content-Disposition', 'attachment', filename=docFile)msg.attach(docApart)print('發送附件!')msg['Subject'] = subjectmsg['From'] = msg_frommsg['To'] = msg_totry:s = smtplib.SMTP_SSL("smtp.qq.com", 465)s.login(msg_from, passwd)s.sendmail(msg_from, msg_to, msg.as_string())print("發送成功")except smtplib.SMTPException as e:print("發送失敗")finally:s.quit()
msg_from = '@qq.com' # 發送方郵箱
passwd = '' # 填入發送方郵箱的授權碼(就是剛剛你拿到的那個授權碼)
msg_to = '@qq.com' # 收件人郵箱,我是自己發給自己
text_content = "test!" # 發送的郵件內容
file_path = 'read.md' # 需要發送的附件目錄
send_email(msg_from,passwd,msg_to,text_content,file_path)
?注意,郵箱密碼不是授權碼