- 浏览: 26111 次
- 性别:
- 来自: 广西
最新评论
功能:主要用来发送文件。
for Python 2.x
for Python 3.x
for Python 2.x
#!/usr/bin/env python # -*- coding: utf-8 -*- class ConfigFile: def __init__(self): from os.path import expanduser home = expanduser('~') self.rcfile = '%s/.mailfilerc' % home self.loadConfigFile() def initConfigFile(self): c = '''[mail] from=xxx@@xxx.com to=xxx@@xxx.com [smtp] host=smtp.xxx.com port=25 user=xxx passwd=xxx ''' f = open(self.rcfile, 'w') f.write(c) f.close() def loadConfigFile(self): import ConfigParser from os.path import exists if exists(self.rcfile): cf = ConfigParser.ConfigParser() cf.read(self.rcfile) self.host = cf.get('smtp', 'host') self.port = cf.getint('smtp', 'port') self.user = cf.get('smtp', 'user') self.passwd = cf.get('smtp', 'passwd') self.FROM = cf.get('mail','from') self.TO = cf.get('mail','to') else: self.initConfigFile() print ('** Please edit the config file %s !!!' % self.rcfile) def sendmail(host, port, user, passwd, FILE): import email, smtplib, base64, sys from os.path import getsize from os import remove from decimal import Decimal as dec fp1=open(FILE) msg = email.message_from_file(fp1) fp1.close() FROM = email.utils.parseaddr(msg.get('from'))[1] TO = email.utils.parseaddr(msg.get('to'))[1] h = email.Header.Header(msg.get('subject')) SUBJECT = email.Header.decode_header(h)[0][0] print (('Connecting SMTP server %s ...') % host) smtp=smtplib.SMTP(host, port) #smtp.set_debuglevel(1) smtp.docmd('EHLO server') smtp.docmd('AUTH LOGIN') smtp.send(base64.b64encode(user)+'\r\n') smtp.getreply() smtp.send(base64.b64encode(passwd)+'\r\n') smtp.getreply() print('Logined') smtp.docmd('MAIL FROM:<%s>' % FROM) smtp.docmd('RCPT TO:<%s>' % TO) smtp.docmd('DATA') print('begin send data...') BUFSIZE=2048 f=open(FILE,'rb') fileLen=getsize(FILE) curper=0 bytes=f.read(BUFSIZE) while(bytes!=b'' and bytes!=''): curper+=len(bytes) sys.stdout.flush() sys.stdout.write('\r%6.2f %%' % (dec(100*curper)/dec(fileLen))) smtp.send(bytes.decode('utf-8')) bytes=f.read(BUFSIZE) f.close() smtp.send('\r\n.\r\n') smtp.getreply() smtp.quit() remove(FILE) print (('\nmail sended. ^_^')) class Mail: def __init__(self, FROM, TO, SUBJECT = None, CHARSET = 'utf-8'): from email.mime.multipart import MIMEMultipart self.FROM = FROM self.TO = TO self.SUBJECT = SUBJECT self.CHARSET = CHARSET self.text = '' self.fileinfo = '\n----\n' self.files = [] self.msg = MIMEMultipart() self.msg['From'] = '<%s>' % self.FROM self.msg['To'] = '<%s>' % self.TO def addtext(self, text = ''): self.text += text def addfile(self, FILE): import mimetypes from email.mime.image import MIMEImage from email.mime.text import MIMEText from email.mime.audio import MIMEAudio from email.mime.application import MIMEApplication from os.path import basename fileName = r'%s' % FILE baseName = basename(fileName) ctype, encoding = mimetypes.guess_type(fileName) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': att = MIMEText((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], \ _subtype = subtype, _charset = self.CHARSET) att.add_header('Content-Disposition', 'attachment', \ filename = self.header(baseName)) att.set_charset(self.CHARSET) self.files.append(att) elif maintype == 'image': att = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], \ _subtype = subtype) att.add_header('Content-Disposition', 'attachment', \ filename = self.header(baseName)) att.set_charset(self.CHARSET) self.files.append(att) elif maintype == 'audio': att = MIMEAudio((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], \ _subtype = subtype) att.add_header('Content-Disposition', 'attachment', \ filename = self.header(baseName)) att.set_charset(self.CHARSET) self.files.append(att) else: att = MIMEApplication((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], \ _subtype = subtype) att.add_header('Content-Disposition', 'attachment', \ filename = self.header(baseName)) att.set_charset(self.CHARSET) self.files.append(att) if not self.SUBJECT: self.SUBJECT = baseName self.fileinfo += '%s\t%s\n' % (self.md5sum(fileName), baseName) def makemail(self): from email.mime.text import MIMEText import uuid self.msg['Subject'] = self.header(self.SUBJECT) txt = MIMEText(self.utf8(self.text + self.fileinfo), \ 'plain', self.CHARSET) self.msg.attach(txt) for x in self.files: self.msg.attach(x) fName = 'MAIL_' + str(uuid.uuid4()) fp = open(fName,'w') fp.write(self.msg.as_string()) fp.close() return fName def utf8(self, data): try: return data.decode(self.CHARSET).encode(self.CHARSET) except: return data.decode('gb18030').encode(self.CHARSET) def header(self, data): '''encode into base64.''' from email.Header import Header return Header(data, self.CHARSET).encode() def md5sum(self, FILE): '''return a file's md5sum.''' from hashlib import md5 BUFSIZE = 1024 m = md5() file = open(FILE, 'r') bytes = file.read(BUFSIZE) while(bytes != b''): m.update(bytes) bytes = file.read(BUFSIZE) file.close() return m.hexdigest() def main(): import sys from optparse import OptionParser from os.path import exists parser = OptionParser(usage = 'Usage: %prog [options] <address>') parser.add_option('-a', dest = 'fileList', action = 'append', \ help = 'attach FILE', metavar = 'FILE') parser.add_option('-s', dest = 'subject', action = 'store', \ help = 'set SUBJECT', metavar = 'SUBJECT') parser.add_option('-v', dest = 'verbose', action = 'store_true', \ help = 'show only,not send') parser.add_option('-t', dest = 'isType', action = 'store_true', \ help = 'type text from stdin') parser.set_defaults(verbose = False) parser.set_defaults(isType = False) (opts, args) = parser.parse_args() if not opts.fileList and not opts.subject and not args: parser.print_help() sys.exit(1) cf = ConfigFile() From = cf.FROM if not args: mailTo = cf.TO else: mailTo = args[0] mymail = Mail(From, mailTo, opts.subject) if opts.isType: text = sys.stdin.read() mymail.addtext(text) if opts.fileList: for file in opts.fileList: if exists(file): mymail.addfile(file) fileName = mymail.makemail() if opts.verbose: print(mymail.msg.as_string()) else: sendmail(cf.host, cf.port, cf.user, cf.passwd, fileName) if __name__ == '__main__' : main()
for Python 3.x
#!/usr/bin/env python3 '''mailfile.py for python3''' class ConfigFile: def __init__(self): from os.path import expanduser home = expanduser('~') self.rcfile = '%s/.mailfilerc' % home self.loadConfigFile() def initConfigFile(self): c = '''[mail] from=xxx@@xxx.com to=xxx@@xxx.com [smtp] host=smtp.xxx.com port=25 user=xxx passwd=xxx ''' f = open(self.rcfile, 'w') f.write(c) f.close() def loadConfigFile(self): import configparser from os.path import exists if exists(self.rcfile): cf = configparser.ConfigParser() cf.read(self.rcfile) self.host = cf.get('smtp', 'host') self.port = cf.getint('smtp', 'port') self.user = cf.get('smtp', 'user') self.passwd = cf.get('smtp', 'passwd') self.FROM = cf.get('mail','from') self.TO = cf.get('mail','to') else: self.initConfigFile() print ('** Please edit the config file %s !!!' % self.rcfile) def sendmail(host, port, user, passwd, FILE): import email, smtplib, base64, sys from os.path import getsize from os import remove from decimal import Decimal as dec fp=open(FILE) msg = email.message_from_file(fp) fp.close() FROM = email.utils.parseaddr(msg.get('from'))[1] TO = email.utils.parseaddr(msg.get('to'))[1] h = msg.get('subject') SUBJECT = email.header.decode_header(h)[0][0] print(('Connecting SMTP server %s ...') % host) smtp = smtplib.SMTP(host, port) #smtp.set_debuglevel(1) smtp.docmd('EHLO server') smtp.docmd('AUTH LOGIN') smtp.send(base64.b64encode(user.encode('utf-8')).decode('utf-8')+'\r\n') smtp.getreply() smtp.send(base64.b64encode(passwd.encode('utf-8')).decode('utf-8')+'\r\n') smtp.getreply() print('Logined') smtp.docmd('MAIL FROM:<%s>' % FROM) smtp.docmd('RCPT TO:<%s>' % TO) smtp.docmd('DATA') print(('send mail %s to <%s> ...') % (SUBJECT.decode('utf-8'), TO)) print('begin send data...') BUFSIZE = 2048 f = open(FILE, 'rb') fileLen = getsize(FILE) curper = 0 bytes = f.read(BUFSIZE) while(bytes != b'' and bytes != ''): curper += len(bytes) sys.stdout.write('\r%6.2f %%' % (dec(100)*dec(curper)/dec(fileLen))) smtp.send(bytes.decode('utf-8')) bytes = f.read(BUFSIZE) f.close() smtp.send('\r\n.\r\n') smtp.getreply() smtp.quit() remove(FILE) print('\nmail sended. ^_^') class mail: def __init__(self, FROM, TO, SUBJECT = None, CHARSET = 'utf-8'): from email.mime.multipart import MIMEMultipart self.FROM = FROM self.TO = TO self.SUBJECT = SUBJECT self.CHARSET = CHARSET self.text = '' self.fileinfo = '\n----\n' self.files = [] self.msg = MIMEMultipart() self.msg['From'] = self.FROM self.msg['To'] = self.TO def addtext(self, text = ''): self.text += text def addfile(self, FILE): import mimetypes from email.mime.image import MIMEImage from os.path import basename fileName = r'%s' % FILE baseName = basename(fileName) ctype, encoding = mimetypes.guess_type(fileName) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) att = MIMEImage((lambda f: (f.read(), f.close())) \ (open(fileName, 'rb'))[0], _subtype = subtype) att.add_header('Content-Disposition', 'attachment', \ filename = self.header(baseName)) att.set_charset(self.CHARSET) att.set_payload(att.get_payload().decode()) self.files.append(att) if not self.SUBJECT: self.SUBJECT = baseName self.fileinfo += '%s\t%s\n' % (self.md5sum(fileName), baseName) def makemail(self): from email.mime.text import MIMEText import uuid self.msg['Subject'] = self.header(self.SUBJECT) txt = MIMEText(self.utf8(self.text + self.fileinfo), \ 'plain', self.CHARSET) self.msg.attach(txt) for x in self.files: self.msg.attach(x) fName = 'MAIL_' + str(uuid.uuid4()) fp = open(fName,'w') fp.write(self.msg.as_string()) fp.close() return fName def utf8(self, data): return data.encode(self.CHARSET) def header(self, data): '''encode into base64.''' from email.header import Header return Header(data, self.CHARSET).encode() def md5sum(self, FILE): '''return a file's md5sum.''' from hashlib import md5 BUFSIZE = 1024 m = md5() file = open(FILE, 'rb') bytes = file.read(BUFSIZE) while(bytes != b''): m.update(bytes) bytes = file.read(BUFSIZE) file.close() return m.hexdigest() def main(): import sys from optparse import OptionParser from os.path import exists parser = OptionParser(usage = 'Usage: %prog [options] <address>') parser.add_option('-a', dest = 'fileList', action = 'append', \ help = 'attach FILE', metavar = 'FILE') parser.add_option('-s', dest = 'subject', action = 'store', \ help = 'set SUBJECT', metavar = 'SUBJECT') parser.add_option('-v', dest = 'verbose', action = 'store_true', \ help = 'show only,not send') parser.set_defaults(verbose = False) (opts, args) = parser.parse_args() if not opts.fileList and not opts.subject and not args: parser.print_help() sys.exit(1) cf = ConfigFile() From = cf.FROM if not args: mailTo = cf.TO else: mailTo = args[0] mymail = mail(From, mailTo, opts.subject) if opts.fileList: for file in opts.fileList: if exists(file): mymail.addfile(file) fileName = mymail.makemail() if opts.verbose: print(mymail.msg.as_string()) else: sendmail(cf.host, cf.port, cf.user, cf.passwd, fileName) if __name__ == '__main__' : main()
相关推荐
fields = [('file', ('filename', open('local_file.txt', 'rb'), 'text/plain'))] # 发起POST请求 response = opener.open('http://example.com/upload', fields) ``` 在这个例子中,`fields`是一个元组列表,每...
mail.py -b -u @mail.txt -p @pass.txt 3.1.12 字典维护 script/wordlist.py提供了字典文件维护的功能,包括: 将多个字典文件merge到数据库中 对每个字典项进行打分计算 按照评分高低导出字典文件 例如: #...
doc = docx.Document('existing_file.docx') for paragraph in doc.paragraphs: if '特定文本' in paragraph.text: paragraph.text = '替换后的文本' doc.save('updated_file.docx') ``` 3. 插入图片: ```...
listfile = os.listdir(file_path) att_name = listfile[4] # 发送者邮件地址、用户名、密码 sender = 'yangXX.cn' receiver = 'yangXX.cn' subject = "python test message" smtpserver = 'mail.XX.cn' ...
- `merge.py`:利用`docx-mailmerge`库自动生成大量合同。 4. **PowerPoint(PPT)** - 虽然`python-pptx`库没有在描述中提及,但它同样可以用于创建、修改PPT。这个库提供了创建幻灯片、添加文本、图片、形状等...
$ python max_article_sizes.py path/to/cnn_or_dailymail/tokenized/articles运行以下命令以准备包含标记化文章和摘要的json文件 $ python prepare_data.py path/to/pickle_file/of/articles/sizes/created/using/...
dump tables entries, dump the entire DBMS, retrieve an arbitrary file content (if the remote DBMS is MySQL) and provide your own SQL SELECT statement to be evaluated; * It is possible to make ...
为此,您需要使用以下命令: docker build -t selenium_docker .docker run -it selenium_docker --env-file envfile.env该.env文件必须包含以下变量: SMTP_SERVER=smtp.domain.beSMTP_PORT=587SMTP_MAIL=account_...
Usage: mailtop.py -f <mail> Options: -h, --help show this help message and exit -f LOGFILE Logfile name -e Display an example logfile line with columns separated -D, --debug enable debugging ...
麦克伏泰尔勘误表: 在application/config.py创建一个配置文件,内容如下: import osCSRF_ENABLED = TrueSECRET_KEY = 'SEKRIT SEKRIT'basedir = os . path . abspath ( os . path . dirname ( __file__ ))...
优化knn代码matlab ############################################### ################### PROJECT 2: COMP 551 - LANGUAGE CLASSIFICATION ...KUMAR[amar.kumar@mail.mcgill.ca] ...中的“savefile”变量设
HOSTNAME=localhostEMAIL=nouser@nomail.comGAUTH_CLIENTID=Google_OAuth_Web_Client_IDGAUTH_CLIENTSECRET=Google_OAuth_Web_Client_SecretMQTT_TOKEN_PRIVKEY=/path/to/your/test/key/file.pem 创建数据库: make ...
适用于Python3的ProxyLogon ProxyLogon(CVE-2021-26855 + CVE-2021-27065)Exchange Server RCE(SSRF-> GetWebShell) usage : python ProxyLogon . py - - host = exchange .... - - mails : mails file .
标题 "Lettura_web_mail_py" 暗示我们关注的是一个使用 Python 进行 Web 邮件读取的项目。在这个项目中,我们可能会遇到如何使用 Python 的库来访问和处理 Web 邮箱中的邮件。描述 "Lettura_web_mail_py" 与标题相同...
usage: mail.py [-h] [-ex old_file] sender_list attach_path text_body Sends email with attachment to multiple recipients. positional arguments: sender_list Path to the text file containing list of ...
20. End system A breaks the large file into chunks. It adds header to each chunk, thereby generating multiple packets from the file. The header in each packet includes the IP address of the ...
用法: ./email_template.py -h 为您提供命令行选项列表示例用法: ./email_temlate.py -user username -csv_file test.csv -attachments attachment1.dat attachment2.pdf -message Email0.txt -from_mail sender_...
smart_monitor.mailfile 位置:/scripts 功能:您将收到的电子邮件的正文存储在这里我应该触摸它吗?:不!!! smart_monitor.list 位置:/scripts 功能:包含要测试的磁盘列表,理所当然地认为这些磁盘位于 /dev/...
Adapting a File-like Object to a True File Object Recipe 2.16. Walking Directory Trees Recipe 2.17. Swapping One File Extension for Another Throughout a Directory Tree Recipe 2.18. Finding a ...