“””
目标: 把当前目录下指定类型文件发送邮件
说明:
经常需要把一些小文件如*.txt,或者*.py,*.doc之类的文件发送到邮箱里供使用或备份
用qq邮箱客户端什么的实在是太麻烦了
只要把自己需要发送的文件全部放到当前目录下,代码就可以一键发送了.
本人纯编程小白,欢迎指教
“””
import smtplib
import email.mime.text
import email.mime.multipartimport os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# 1.取得当前目录下指定文件的文件名列表,缺省为txt
def get_type_file(keyword='.txt'): # 这里可以更改扩展名如.doc,.py,.zip等等
# 打印当前的工作目录
print("当前目录为: ",os.getcwd())
# 列举当前工作目录下的文件名
files=os.listdir()
keyword=keyword
filelist=[]
i=0
for file in files:
if keyword in file:
i=i+1
print(i,file)
filelist.append(file)
return filelist
# 2. 把列表内的文件发送到指定邮箱
def send_email(filelist, content=""):
smtpHost = 'smtp.139.com' # 139邮箱SMTP服务器
sendAddr = '发送人邮箱'
password = '邮箱密码' # 163邮箱,则为授权码
receiver = '收件人邮箱'
subject = "邮件标题"
content = '正文内容'
msg = MIMEMultipart()
msg['from'] = sendAddr
msg['to'] = receiver
msg['Subject'] = subject
txt = MIMEText(content, 'plain', 'utf-8')
msg.attach(txt) # 添加邮件正文
# 添加附件,传送filelist列表里的文件
filename = ""
i = 0
for file in filelist:
i = i + 1
filename = file
# print(str(i),filename)
part = MIMEApplication(open(filename, 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(part)
server = smtplib.SMTP(smtpHost, 25) # SMTP协议默认端口为25
# server.set_debuglevel(1) # 出错时可以查看
server.login(sendAddr, password)
server.sendmail(sendAddr, receiver, str(msg))
print("\n"+ str(len(filelist)) + "个文件发送成功")
server.quit()
3 主程序
def main(): filelist = get_type_file() send_email(filelist) main()