Find a Gmail-based email written in Python. Code It is quite useful. Of course, the error handling is not done. Record it first: View code
1 Import OS 2 Import Smtplib 3 Import Mimetypes 4 From Email. mimemultipart Import Mimemultipart 5 From Email. mimebase Import Mimebase 6 From Email. mimetext Import Mimetext 7 From Email. mimeaudio Import Mimeaudio 8 From Email. mimeimage Import Mimeimage 9 From Email. encoders Import Encode_base64 10 11 Def Sendmail (subject, text ,* Attachmentfilepaths ): 12 Gmailuser = ' Youraccount@gmail.com ' 13 Gmailpassword = ' Yourpasswd ' 14 Recipient = ' Mail1@gmail.com mail2@gmail.com ' 15 16 MSG = Mimemultipart () 17 MSG [ ' From ' ] = Gmailuser 18 MSG [' To ' ] = Recipient 19 MSG [ ' Subject ' ] = Subject 20 MSG. Attach (mimetext (text )) 21 22 For Attachmentfilepath In Attachmentfilepaths: 23 MSG. Attach (getattachment (attachmentfilepath )) 24 25 MailServer = smtplib. SMTP ( ' Smtp.gmail.com ' , 587 ) 26 MailServer. EHLO () 27 MailServer. starttls () 28 MailServer. EHLO () 29 MailServer. login (gmailuser, gmailpassword) 30 MailServer. Sendmail (gmailuser, recipient, MSG. as_string ()) 31 MailServer. Close () 32 33 Print ( ' Sent email to % s ' % Recipient) 34 35 Def Getattachment (attachmentfilepath ): 36 Contenttype, encoding = Mimetypes. guess_type (attachmentfilepath) 37 38 If Contenttype Is None Or Encoding Is Not None: 39 Contenttype = ' Application/octet-stream ' 40 41 Maintype, subtype = contenttype. Split ( ' / ' , 1 ) 42 File = open (attachmentfilepath, ' RB ' ) 43 44 If Maintype = ' Text ' : 45 Attachment = Mimetext (file. Read ()) 46 Elif Maintype = ' Message ' : 47 Attachment = Email. message_from_file (file) 48 Elif Maintype = ' Image ' : 49 Attachment = mimeimage (file. Read (), _ subtype = Subtype) 50 Elif Maintype = ' Audio ' : 51 Attachment = mimeaudio (file. Read (), _ subtype = Subtype) 52 Else : 53 Attachment = Mimebase (maintype, subtype) 54 Attachment. set_payload (file. Read ()) 55 Encode_base64 (Attachment) 56 57 File. Close () 58 59 Attachment. add_header ( ' Content-Disposition ' , ' Attachment ' , Filename = OS. Path. basename (attachmentfilepath )) 60 Return Attachment