Python發送郵件成功的前提,應是先開啟授權碼。目前使用廣泛的郵箱有:163郵箱、qq郵箱等。
163郵箱開啟授權碼的方法如下圖:
qq郵箱開啟授權碼的方法如下圖:
接下來代碼的實現:
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication class SendEmail: def email(self,body, attach): # 發送郵箱 sender = 'xxx@163.com' # 接收郵箱 receivers = 'xxx@163.com' msg = MIMEMultipart() #郵箱的主題 msg['Subject'] = '測試報告' msg['From'] = sender msg['To'] = receivers content = MIMEText(body,'html','utf-8') msg.attach(content) #添加附件,並命名 attachment = MIMEApplication(open(attach, 'rb').read()) attachment.add_header('Content-Disposition', 'attachment', filename='report.rar') msg.attach(attachment) try: #連接郵箱的服務器及端口號,以163郵箱為例 smtpObj = smtplib.SMTP_SSL('smtp.163.com','465') #登錄郵箱:用戶名及密碼 smtpObj.login(user='xxx@163.com', password='xxx') smtpObj.sendmail(sender, receivers, str(msg)) smtpObj.quit() print("郵件發送成功") except smtplib.SMTPException: print("Error: 無法發送郵件") if __name__ == '__main__': #以同一目錄中的report.html為例 with open("./report.html",'r',encoding="utf-8") as file: body=file.read() #以同一目錄中的report.rar為例添加附件 SendEmail().email(body,"./report.rar")