Re: [google-appengine] I'm struggling to attach a file to this email

40 views
Skip to first unread message

Alex Martelli

unread,
Mar 3, 2017, 1:29:47 PM3/3/17
to google-a...@googlegroups.com
I answered on the duplicate thread you opened 2.5 hours later. To repeat: there's a bug in your code, a missing `from email import encoders` at the top. BTW, I think your bug has nothing to do with Google App Engine.

Alex

On Fri, Mar 3, 2017 at 7:08 AM, Guillaume France <gc.c...@gmail.com> wrote:
I'm struggling with the create_message_with_attachment (the rest works, create_message_without_attachment works ). 

I did read google documentation. The stack thread talking about it focus on complicate point (while mixing up the different python version). Posting this in stack will be down-voted as duplicated (stack has its limit).

The script bellow only create an email attach a file to it and send it (well, it's suppose to do so)

This script return: 
  encoders.encode_base64(part)
NameError: name 'encoders' is not defined




import httplib2
import os
import oauth2client
from oauth2client import client, tools
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from apiclient import errors, discovery  


SCOPES
= 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE
= 'client_secret.json'
APPLICATION_NAME
= 'Gmail API Python Send Email'




def get_credentials():
 home_dir
= os.path.expanduser('~')
 credential_dir
= os.path.join(home_dir, '.credentials')
 
if not os.path.exists(credential_dir):
 os
.makedirs(credential_dir)  #create folder if doesnt exist
 credential_path
= os.path.join(credential_dir, 'gmail-python-email-send.json')
 store
= oauth2client.file.Storage(credential_path)
 credentials
= store.get()
 
if not credentials or credentials.invalid:
 flow
= client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
 flow
.user_agent = APPLICATION_NAME
 credentials
= tools.run_flow(flow, store)
 
print('Storing credentials to ' + credential_path)
 
 
return credentials
 




def SendMessage(sender, to, subject, msgHtml, msgPlain):
 credentials
= get_credentials()
 http
= httplib2.Http()
 http
= credentials.authorize(http)
 service
= discovery.build('gmail', 'v1', http=http)
 
 
# #without attachment
 
# message_without_attachment = create_message_without_attachment(sender, to, subject, msgHtml, msgPlain)
 
# SendMessageInternal(service, "me", message_without_attachment)
 
 
# #with attachement
 message_with_attach
= create_message_with_attachment(sender, to, subject, msgHtml, msgPlain)
 
SendMessageInternal(service, "me", message_with_attach)


 
def SendMessageInternal(service, user_id, message):
 
try:
 message
= (service.users().messages().send(userId=user_id, body=message).execute())  ####need  to get user_id before


 message_ID
= message['id']
 
print(f'Message Id: {message_ID}')
 
return [message, message_ID] #return value as list
 
except errors.HttpError as error:
 
print(f'An error occurred: {error}')
 
 
def create_message_without_attachment (sender, to, subject, msgHtml, msgPlain):
 msg
= MIMEMultipart('alternative')
 msg
['Subject'] = subject
 msg
['From'] = sender
 msg
['To'] = to
 msg
.attach(MIMEText(msgPlain, 'plain'))
 msg
.attach(MIMEText(msgHtml, 'html'))
 
 raw
= base64.urlsafe_b64encode(msg.as_bytes())
 raw
= raw.decode()
 body
= {'raw': raw}
 
return body


 
def create_message_with_attachment(sender, to, subject, msgHtml, msgPlain):
 msg
= MIMEMultipart('alternative')
 msg
['To'] = to
 msg
['From'] = sender
 msg
['Subject'] = subject
 msg
.attach(MIMEText(msgPlain, 'plain'))
 msg
.attach(MIMEText(msgHtml, 'html'))

 
# the problem comes from this part
 part
= MIMEBase('application', "octet-stream")
 part
.set_payload( open(r"C:\Users\xx\Desktop\test_Attachment.txt","rb").read() )
 encoders
.encode_base64(part)
 part
.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f)))
 msg
.attach(part)
 
 raw
= base64.urlsafe_b64encode(msg.as_bytes())
 raw
= raw.decode()
 body
= {'raw': raw}
 
return body
 
def main():
 to
= "your...@gmail.com"
 sender
= "mye...@gmail.com"
 subject
= "subject test1"
 msgHtml
= r'Hi<br/>Html <b>hello</b>'
 msgPlain
= "Hi\nPlain Email"
 message_text
= "this is message text"
 
SendMessage(sender, to, subject, msgHtml, msgPlain)


if __name__ == '__main__':
 main
()



--
You received this message because you are subscribed to the Google Groups "Google App Engine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-appengine+unsubscribe@googlegroups.com.
To post to this group, send email to google-appengine@googlegroups.com.
Visit this group at https://groups.google.com/group/google-appengine.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-appengine/f5e41361-c3e8-4cd2-9cb6-fe1a95928790%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages