code_junkie

How can I download all emails with attachments from Gmail?

Nov 12th, 2011
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.68 KB | None | 0 0
  1. import email, getpass, imaplib, os
  2.  
  3. detach_dir = '.' # directory where to save attachments (default: current)
  4. user = raw_input("Enter your GMail username:")
  5. pwd = getpass.getpass("Enter your password: ")
  6.  
  7. # connecting to the gmail imap server
  8. m = imaplib.IMAP4_SSL("imap.gmail.com")
  9. m.login(user,pwd)
  10. m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead
  11. # use m.list() to get all the mailboxes
  12.  
  13. resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
  14. items = items[0].split() # getting the mails id
  15.  
  16. for emailid in items:
  17. resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
  18. email_body = data[0][1] # getting the mail content
  19. mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
  20.  
  21. #Check if any attachments at all
  22. if mail.get_content_maintype() != 'multipart':
  23. continue
  24.  
  25. print "["+mail["From"]+"] :" + mail["Subject"]
  26.  
  27. # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
  28. for part in mail.walk():
  29. # multipart are just containers, so we skip them
  30. if part.get_content_maintype() == 'multipart':
  31. continue
  32.  
  33. # is this part an attachment ?
  34. if part.get('Content-Disposition') is None:
  35. continue
  36.  
  37. filename = part.get_filename()
  38. counter = 1
  39.  
  40. # if there is no filename, we create one with a counter to avoid duplicates
  41. if not filename:
  42. filename = 'part-%03d%s' % (counter, 'bin')
  43. counter += 1
  44.  
  45. att_path = os.path.join(detach_dir, filename)
  46.  
  47. #Check if its already there
  48. if not os.path.isfile(att_path) :
  49. # finally write the stuff
  50. fp = open(att_path, 'wb')
  51. fp.write(part.get_payload(decode=True))
  52. fp.close()
  53.  
  54. #!/usr/bin/env python
  55. """Save all attachments for given gmail account."""
  56. import os, sys
  57. from libgmail import GmailAccount
  58.  
  59. ga = GmailAccount("[email protected]", "pA$$w0Rd_")
  60. ga.login()
  61.  
  62. # folders: inbox, starred, all, drafts, sent, spam
  63. for thread in ga.getMessagesByFolder('all', allPages=True):
  64. for msg in thread:
  65. sys.stdout.write('.')
  66. if msg.attachments:
  67. print "n", msg.id, msg.number, msg.subject, msg.sender
  68. for att in msg.attachments:
  69. if att.filename and att.content:
  70. attdir = os.path.join(thread.id, msg.id)
  71. if not os.path.isdir(attdir):
  72. os.makedirs(attdir)
  73. with open(os.path.join(attdir, att.filename), 'wb') as f:
  74. f.write(att.content)
  75.  
  76. # Creates an array of references to every attachment in your account
  77. my $messages = $gmail->get_messages();
  78. my @attachments;
  79.  
  80. foreach ( @{ $messages } ) {
  81. my $email = $gmail->get_indv_email( msg => $_ );
  82. if ( defined( $email->{ $_->{ 'id' } }->{ 'attachments' } ) ) {
  83. foreach ( @{ $email->{ $_->{ 'id' } }->{ 'attachments' } } ) {
  84. push( @attachments, $gmail->get_attachment( attachment => $_ ) );
  85. if ( $gmail->error() ) {
  86. print $gmail->error_msg();
  87. }
  88. }
  89. }
  90. }
  91.  
  92. #retrieve specific attachment
  93. my $msgid = 'F000000000';
  94. my $attachid = '0.1';
  95. my $attach_ref = $gmail->get_attachment( attid => $attachid, msgid => $msgid );
  96.  
  97. import javax.mail.*
  98. import java.util.Properties
  99.  
  100. String gmailServer
  101. int gmailPort
  102. def user, password, LIMIT
  103. def inboxFolder, root, StartDate, EndDate
  104.  
  105.  
  106. // Downloads all attachments from a gmail mail box as per some criteria
  107. // to a specific folder
  108. // Based on code from
  109. // http://agileice.blogspot.com/2008/10/using-groovy-to-connect-to-gmail.html
  110. // http://stackoverflow.com/questions/155504/download-mail-attachment-with-java
  111. //
  112. // Requires:
  113. // java mail jars in the class path (mail.jar and activation.jar)
  114. // openssl, with gmail certificate added to java keystore (see agileice blog)
  115. //
  116. // further improvement: maybe findAll could be used to filter messages
  117. // subject could be added as another criteria
  118. ////////////////////// <CONFIGURATION> //////////////////////
  119. // Maximm number of emails to access in case parameter range is too high
  120. LIMIT = 10000
  121.  
  122. // gmail credentials
  123. gmailServer = "imap.gmail.com"
  124. gmailPort = 993
  125.  
  126. password = "gmailpassword"
  127.  
  128. // gmail label, or "INBOX" for inbox
  129. inboxFolder = "finance"
  130.  
  131. // local file system where the attachment files need to be stored
  132. root = "D:\AttachmentStore"
  133.  
  134. // date range dd-mm-yyyy
  135. StartDate= "31-12-2009"
  136. EndDate = "1-6-2010"
  137. ////////////////////// </CONFIGURATION> //////////////////////
  138.  
  139. StartDate = Date.parse("dd-MM-yyyy", StartDate)
  140. EndDate = Date.parse("dd-MM-yyyy", EndDate)
  141.  
  142. Properties props = new Properties();
  143. props.setProperty("mail.store.protocol", "imaps");
  144. props.setProperty("mail.imaps.host", gmailServer);
  145. props.setProperty("mail.imaps.port", gmailPort.toString());
  146. props.setProperty("mail.imaps.partialfetch", "false");
  147.  
  148. def session = javax.mail.Session.getDefaultInstance(props,null)
  149. def store = session.getStore("imaps")
  150.  
  151. store.connect(gmailServer, user, password)
  152.  
  153. int i = 0;
  154. def folder = store.getFolder(inboxFolder)
  155.  
  156. folder.open(Folder.READ_ONLY)
  157.  
  158. for(def msg : folder.messages) {
  159.  
  160. //if (msg.subject?.contains("bank Statement"))
  161. println "[$i] From: ${msg.from} Subject: ${msg.subject} -- Received: ${msg.receivedDate}"
  162.  
  163. if (msg.receivedDate < StartDate || msg.receivedDate > EndDate) {
  164. println "Ignoring due to date range"
  165. continue
  166. }
  167.  
  168.  
  169. if (msg.content instanceof Multipart) {
  170. Multipart mp = (Multipart)msg.content;
  171.  
  172. for (int j=0; j < mp.count; j++) {
  173.  
  174. Part part = mp.getBodyPart(j);
  175.  
  176. println " ---- ${part.fileName} ---- ${part.disposition}"
  177.  
  178. if (part.disposition?.equalsIgnoreCase(Part.ATTACHMENT)) {
  179.  
  180. if (part.content) {
  181.  
  182. def name = msg.receivedDate.format("yyyy_MM_dd") + " " + part.fileName
  183. println "Saving file to $name"
  184.  
  185. def f = new File(root, name)
  186.  
  187. //f << part.content
  188. try {
  189. if (!f.exists())
  190. f << part.content
  191. }
  192. catch (Exception e) {
  193. println "*** Error *** $e"
  194. }
  195. }
  196. else {
  197. println "NO Content Found!!"
  198. }
  199. }
  200. }
  201. }
  202.  
  203. if (i++ > LIMIT)
  204. break;
  205.  
  206. }
Add Comment
Please, Sign In to add comment