直接看代码
# FileName : sendEmail.py # Author : Adil # DateTime : 2020/11/5 3:44 PM # SoftWare : PyCharm import smtplib,os from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication _user = "senderEmail" _pwd = "senderPassword" _to = "recieverEmail" # 如名字所示Multipart就是分多个部分 msg = MIMEMultipart() msg["Subject"] = "我是邮件主题,好的主题可以防止被丢到垃圾箱内" msg["From"] = _user msg["To"] = _to # ---这是文字部分--- part = MIMEText("我是邮件内容") msg.attach(part) # ---这是附件部分--- currentPath = os.getcwd() targetPath = os.path.join(currentPath,'testFiles') sqlFileList = os.listdir(targetPath) sqlFilePath = '' sqlFilePathList = [] # 发送多个附件的邮件,这里发送指定目录下所有类型一致的文件 for fileName in sqlFileList: sqlFilePath = os.path.join(targetPath,fileName) print(sqlFilePath) sqlFilePathList.append(sqlFilePath) print(sqlFilePathList) with open(sqlFilePath,'rb') as f: part = MIMEApplication(f.read()) part.add_header('Content-Disposition', 'attachment', filename=fileName) msg.attach(part) # 以下写法都可改为上面的写法 ,以下是当个附件单个附件的设置 # xlsx类型附件 # part = MIMEApplication(open('sqltest.xlsx', 'rb').read()) # part.add_header('Content-Disposition', 'attachment', filename="sqltest.xlsx") # msg.attach(part) # # jpg类型附件 # part = MIMEApplication(open('foo.jpg', 'rb').read()) # part.add_header('Content-Disposition', 'attachment', filename="foo.jpg") # msg.attach(part) # # # pdf类型附件 # part = MIMEApplication(open('foo.pdf', 'rb').read()) # part.add_header('Content-Disposition', 'attachment', filename="foo.pdf") # msg.attach(part) # # # mp3类型附件 # part = MIMEApplication(open('foo.mp3', 'rb').read()) # part.add_header('Content-Disposition', 'attachment', filename="foo.mp3") # msg.attach(part) s = smtplib.SMTP("smtphz.qiye.163.com", 25) # 连接smtp邮件服,这里是网易邮箱 务器,端口默认是25 s.login(_user, _pwd) # 登陆服务器 s.sendmail(_user, _to, msg.as_string()) # 发送邮件 s.close()