Thanks a lot Alex, you are right the from email import encoders was 
missing. Now it sends the email *but* without the file attached to it. 

Any idea what could go wrong in the create_message_with_attachment() ?


On Friday, March 3, 2017 at 6:08:07 PM UTC+1, Guillaume France wrote:
>
> I'm struggling to send an email with a file attached to it.
>
> Hi!
>
> I'm struggling with the create_message_with_attachment function (the rest 
> works, create_message_without_attachment works ). 
>
> I did read google documentation. The stack threads talking about it focus 
> on complex issue (while mixing up on the top of it different syntax of 
> python version). Posting this in stack will be down-voted as duplicated 
> (stack has its limit).
>
> I'm just trying with the script bellow to create an email, attach a file 
> to it and send it. 
>
>
> *The python 3.6 script returns: *
>
>>   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)
>  
>  # #with attachement
>  message_with_attach = create_message_with_attachment(sender, to, subject, 
> msgHtml, msgPlain)
>  SendMessageInternal(service, "me", message_with_attach)
>
>  # #without attachment
>  # message_without_attachment = create_message_without_attachment(sender, 
> to, subject, msgHtml, msgPlain)
>  # SendMessageInternal(service, "me", message_without_attachment)
>  
>  
> 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 = "yourem...@gmail.com"
>  sender = "myem...@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+unsubscr...@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/7caad6f6-862d-4cfb-b24b-2593b9d6a956%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to