11#!/usr/bin/python
2+ import os
3+ import glob
4+ import subprocess
5+ from cPickle import load
6+
7+
8+
9+ def mail (From , to , subject , text , filelist = [],bcc = "" ,cc = "" ,headers = "" ):
10+ from email .MIMEMultipart import MIMEMultipart
11+ from email .MIMEBase import MIMEBase
12+ from email .MIMEText import MIMEText
13+ from email import Encoders
14+ from email .generator import Generator
15+ """ send mail to somebody. Return true on success, false on failure
16+
17+ "to" "bcc" and "cc" may be lists of addresses, or a single address as a string.
18+
19+ Note: all attached files are base64 encoded and stored IN MEMORY before being sent to
20+ the server. You probably will not be able to send any file or set of files even close to as
21+ large as your computers memory.
22+
23+ All attachements are given the mime-type "application/octet-stream" which is wrong.
24+ """
25+ msg = MIMEMultipart ()
26+
27+ msg ['From' ] = From
28+ msg ['Subject' ] = subject
29+ try :
30+ test = to .lower ()
31+ #no error? to is a string, convert it to a list.
32+ sendto = [to ]
33+ msg ['To' ] = to
34+ except AttributeError :
35+ #to is a list
36+ sendto = []
37+ for addr in to :
38+ sendto .append (addr )
39+ msg .__setitem__ ('To' ,addr )
40+
41+ if cc :
42+ msg ['Cc' ] = cc
43+ try :
44+ test = bcc .lower ()
45+ to .append (bcc )
46+ msg .__setitem__ ('Cc' ,addr )
47+ except AttributeError :
48+ for addr in bcc :
49+ sendto .append (addr )
50+ msg .__setitem__ ('Cc' ,addr )
51+ if bcc :
52+ #The point of "bcc" is that it's not in the message header, only the smtp reciepients.
53+ #msg['Bcc'] = bcc
54+ try :
55+ test = cc .lower ()
56+ to .append (cc )
57+ except AttributeError :
58+ for addr in bcc :
59+ sendto .append (addr )
60+ if headers :
61+ try :
62+ test = headers .lower ()
63+ #no error? headers is a string, convert it to a list.
64+ headers = [headers ]
65+ except AttributeError :
66+ #already a list
67+ pass
68+ for header in headers :
69+ name , value = header .split (':' ,1 )
70+ msg .__setitem__ (name ,value )
71+
72+ msg .attach (MIMEText (text ))
73+
74+ for attach in filelist :
75+ part = MIMEBase ('application' , 'octet-stream' )
76+ #The "read" call reads and encodes all files INTO MEMORY!!!
77+ # This severly limits the sendable file size.
78+ #TODO: rewrite email and smtplib to accept pointers, so these things can be done on the fly,
79+ #using MUCH less memory.
80+ part .set_payload (open (attach , 'rb' ).read ())
81+ Encoders .encode_base64 (part )
82+ part .add_header ('Content-Disposition' ,
83+ 'attachment; filename="%s"' % os .path .basename (attach ))
84+ msg .attach (part )
85+
86+ sendmail = subprocess .Popen (["/usr/sbin/sendmail" ,"-i" ] + sendto ,stdin = subprocess .PIPE ,bufsize = - 1 )
87+ t = Generator (sendmail .stdin ,mangle_from_ = False ,maxheaderlen = 0 )
88+ t .flatten (msg )
89+ sendmail .stdin .close ()
90+ return sendmail .wait ()
91+
292
3- import libgmail
4- from cPickle import load , dump
593
694#Open for reading
95+
796try :
8- from os .path import expanduser
9- f = open (expanduser ("~/.gmailpasswd" ),"r" )
97+ f = open (os .path .expanduser ("~/.gmailpasswd" ),"r" )
1098except IOError , (errno , strerror ):
1199 if errno == 2 :
12100 print ("""
@@ -24,26 +112,84 @@ except IOError, (errno, strerror):
24112 print "Unhandled IO error type"
25113 raise
26114
27- #Load the stored credentials.
28- credentials = load (f )
115+ #close the file - I really only needed to verify its existance.
29116f .close ()
30117
31- #debug
32- print credentials
33- exit (17 )
118+ #Time to beat:
119+ mytime = os .stat (os .path .expanduser ("~/.gmailpasswd" )).st_mtime
34120
121+ # cycle through all documents in /doc, encrypt and email any which are newer
122+ # filestring = string list of files
123+ fileslist = []
124+ bodystring = ""
125+ filestring = ""
126+ subject = ""
127+ def checkNadd (filename ):
128+ """ Add a file to the file list. IF its newer """
129+ global filestring
130+ global fileslist
131+ global bodystring
132+ global subject
133+ status = os .stat (filename )
134+ if status .st_mtime > mytime :
135+ fileslist .append (filename )
136+ filestring += filename + "\n "
137+ #print filename
138+ if os .path .basename (filename ).startswith ("Journal" ) and filename .endswith (".txt" ):
139+ f = open (filename ,"r" )
140+ addme = False
141+ for line in f :
142+ if line .endswith (":" ):
143+ addme = False
144+ if addme :
145+ bodystring += line
146+ if line .lower ().lstrip ().startswith ("anna:" ):
147+ addme = True
148+ bodystring += "From " + filename + "\n \n "
149+ name , sub = line .split (":" ,1 )
150+ if sub :
151+ subject += sub .strip () + " "
152+ f .close ()
153+ #else:
154+ # print str(status.st_mtime) + "<" + str(mytime)
155+ #For journal entries, add any "anna:" sections to the email body.
35156
36- #login to gmail
37- ga = libgmail .GmailAccount ("j.arthur.gilmore" ,"nDhiRp8w" )
38- ga .login ()
157+ # Backup my Documents directory
158+ for root ,dirs ,files in os .walk (os .path .expanduser ("~/docs" )):
159+ #print root, dirs, files
160+ files .sort ()
161+ for file in files :
162+ checkNadd (os .path .join (root ,file ))
163+
164+ # Backup my firefox bookmarks file
165+ for root ,dirs ,files in os .walk (glob .glob (os .path .expanduser ("~/.mozilla/firefox/*.default/bookmarkbackups" ))[0 ]):
166+ #print root, dirs, files
167+ files .sort ()
168+ for file in files :
169+ checkNadd (os .path .join (root ,file ))
170+
171+ if len (fileslist ) == 0 :
172+ exit (0 )
173+
174+ bodystring += "\n \n Changed files included in the backup:\n \n " + filestring
175+
176+ fileslist .insert (0 ,"-P" )
177+ fileslist .insert (0 ,"-c" )
178+ fileslist .insert (0 ,"/bin/tar" )
179+ #print fileslist
180+ #print fileslist
181+ #print filestring
182+ #print bodystring
183+ # This implements "tar -c --strip-components
184+ tar = subprocess .Popen (fileslist ,stdout = subprocess .PIPE ,bufsize = - 1 )
185+ f = open ("/tmp/autobackup.tar.gpg" ,"wb" )
186+ gpg = subprocess .Popen (["/usr/bin/gpg" ,"-r" ,"j.arthur.gilmore@gmail.com" ,"--encrypt" ],stdout = f ,stdin = tar .stdout ,bufsize = - 1 )
187+
188+ if subject == "" :
189+ subject = "Autobackup Email"
190+
191+ if gpg .wait () == 0 and tar .wait () == 0 :
192+ if not mail ("j.arthur.gilmore@gmail.com" ,"anna.gilmore@gmail.com" ,subject ,bodystring ,filelist = ["/tmp/autobackup.tar.gpg" ,"/home/jgilmore/Safe.dat" ]):
193+ # os.mtime(os.path.expanduser("~/.gmailpasswd"),None)
194+ os .execv ("/usr/bin/touch" ,("touch" ,os .path .expanduser ("~/.gmailpasswd" )))
39195
40- #compose our message
41- msg = libgmail .GmailComposedMessage (
42- "j.arthur.gilmore@gmail.com" ,
43- "Automatic Safe Backup" ,
44- "non-empty body text is not required" ,
45- filenames = ["/home/jgilmore/Safe.dat" ])
46- try :
47- ga .sendMessage (msg )
48- except http404 :
49- ga .sendMessage (msg )
0 commit comments