python 3.6: the script send message but without the attachement

180 views
Skip to first unread message

Guillaume France

unread,
Mar 3, 2017, 4:50:06 PM3/3/17
to Google App Engine
Hi!

This script send the message but does not include the attachement. I'm struggling with the create_message_with_attachment function . 

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).

Thanks in advance for your help!


Here is the faulty function (full code bellow)

def create_message_with_attachment(sender, to, subject, msgHtml, msgPlain):
 
 
# multipart container can contain other MIME parts.  (attachment will be independent of the multipart/alternative)
 msg
= MIMEMultipart('alternative')
 msg
['To'] = to
 msg
['From'] = sender
 msg
['Subject'] = subject
 
 
# convert both part to a MIME compatible string
 part1
= MIMEText(msgPlain, 'plain')
 part2
= MIMEText(msgHtml, 'html')
 
 
# create .txt attachment
 filename
=r"C:\Users\xxx\Desktop\test_Attachment.txt"
 fp
=open(filename).read()
 att
= MIMEApplication(fp)
 fp
.close()
 
 
#This will add a header that looks like: "Content-Disposition: attachment; filename="test_Attachment.txt" "
 att
.add_header('content-disposition', 'attachment', filename = ('utf-8', '', 'test_Attachment.txt'))
 
 
# Attach parts into message container.
 msg
.attach(att)
 msg
.attach(part1)
 msg
.attach(part2)


 raw
= base64.urlsafe_b64encode(msg.as_bytes())
 
# raw= encoders.encode_base64(msg)
 raw
= raw.decode()
 body
= {'raw': raw}
 
return body
 

The whole code:

import httplib2
import os
import oauth2client
from oauth2client import client, tools
import base64
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
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)
 
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_with_attachment(sender, to, subject, msgHtml, msgPlain):
 
 
# multipart container can contain other MIME parts.  (attachment will be independent of the multipart/alternative)
 msg
= MIMEMultipart('alternative')
 msg
['To'] = to
 msg
['From'] = sender
 msg
['Subject'] = subject
 
 
# convert both part to a MIME compatible string
 part1
= MIMEText(msgPlain, 'plain')
 part2
= MIMEText(msgHtml, 'html')
 
 
# create .txt attachment
 filename
=r"C:\Users\xxx\Desktop\test_Attachment.txt"
 fp
=open(filename).read()
 att
= MIMEApplication(fp)
 fp
.close()
 
 
#This will add a header that looks like: "Content-Disposition: attachment; filename="test_Attachment.txt" "
 att
.add_header('content-disposition', 'attachment', filename = ('utf-8', '', 'test_Attachment.txt'))
 
 
# Attach parts into message container.
 msg
.attach(att)
 msg
.attach(part1)
 msg
.attach(part2)

 raw
= base64.urlsafe_b64encode(msg.as_bytes())
 
# raw= encoders.encode_base64(msg)
 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
()



Alex Martelli

unread,
Mar 3, 2017, 6:18:17 PM3/3/17
to google-a...@googlegroups.com
As I posted to another one of your duplicate threads:

I would recommend you post this code and question to stackoverflow.com -- a very popular site regularly visited by many programming experts who like to answer technical questions (me included, when I have free time). You may want to just tag the question as python and email, since it's not really germane to google-app-engine (if you tagged it with the latter anyway, your question might be avoided by experts on python and email who are not also expert on App Engine).


Alex


--
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/66315e61-f451-4a3f-83e0-0ed790442983%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages