I’m trying to reply a mail I received using Gmail API. I tried following code it appends the sending message to thread in my mailbox but for the receiver it send as a new message. What is the proper way to declare In-Reply-To and Reference headers?
JavaScript
x
22
22
1
def create_message(origin=None, destination=to, subject=None, msg_txt=None, thr_id=None):
2
"""Create a message for an email.
3
Args:
4
origin: Email address of the sender.
5
destination: Email address of the receiver.
6
subject: The subject of the email message.
7
msg_txt: The text of the email message.
8
thr_id: the threadId of the message to attach
9
Returns:
10
An object containing a base64url encoded email object.
11
"""
12
message = MIMEText(msg_txt)
13
message['to'] = destination
14
message['from'] = origin
15
message['subject'] = subject
16
raw_msg={'raw': (base64.urlsafe_b64encode(message.as_bytes()).decode())}
17
raw_msg['threadId'] =thr_id
18
raw_msg['Reference'] = '<CANyAw3CWm33sKL80GMKp-b=8JgXz3MVPkvCVbJ_oK4NuGJcb3w@mail.gmail.com>'
19
raw_msg['In-Reply-To'] = '<CANyAw3CWm33sKL80GMKp-b=8JgXz3MVPkvCVbJ_oK4NuGJcb3w@mail.gmail.com>'
20
raw_msg['Message-ID'] = '<CANyAw3CWm33sKL80GMKp-b=8JgXz3MVPkvCVbJ_oK4NuGJcb3w@mail.gmail.com>'
21
return raw_msg
22
My main method is as follow,
JavaScript
1
38
38
1
def main():
2
"""Canned reply responder using the Gmail API.
3
Creates a Gmail API service object and responds to a query with a standard response
4
whilst giving it a label to ensure only 1 response per thread is sent
5
"""
6
7
# get credentials first and create gmail service object
8
store = file.Storage('token.json')
9
creds = store.get()
10
if not creds or creds.invalid:
11
flow = client.flow_from_clientsecrets('gmailApiCredentials.json', SCOPES)
12
creds = tools.run_flow(flow, store)
13
gmail_service = build('gmail', 'v1', http=creds.authorize(Http()))
14
15
# receive email messages
16
q = 'subject:this is a test message'
17
messages = list_messages_matching_query(gmail_service, user_id,
18
query=q,
19
maxResults=1)
20
if not messages:
21
print("No messages to show")
22
else:
23
pprint.pprint('Messages to show: {}'.format(messages))
24
25
# get thread of first document - so you can label the thread itself if need be
26
thread_id = messages[0]['threadId']
27
thread = get_thread(gmail_service, user_id, thread_id)
28
29
msg_id = messages[0]['id']
30
message = get_message(gmail_service, user_id, msg_id)
31
32
subject ='Re:this is a test message'
33
msg = create_message(destination=to, origin=to,
34
subject=subject,
35
msg_txt='Hai', thr_id=thread_id)
36
send_message(gmail_service,"me", msg)
37
print("Message Sent")
38
Advertisement
Answer
The create_message method should be changed as follow to set ‘Reference’ and ‘In-Reply-To’ headers.
JavaScript
1
22
22
1
def create_message(origin=None, destination=TO, subject=None, msg_txt=None, thr_id=None, msgID=None):
2
"""Create a message for an email.
3
Args:
4
origin: Email address of the sender.
5
destination: Email address of the receiver.
6
subject: The subject of the email message.
7
msg_txt: The text of the email message.
8
thr_id: the threadId of the message to attach
9
Returns:
10
An object containing a base64url encoded email object.
11
"""
12
message = MIMEText(msg_txt)
13
message['to'] = destination
14
message['from'] = origin
15
message['subject'] = subject
16
message.add_header('Reference', msgID)
17
message.add_header('In-Reply-To', msgID)
18
raw_msg = {'raw': (base64.urlsafe_b64encode(message.as_bytes()).decode())}
19
raw_msg['threadId'] = thr_id
20
return raw_msg
21
22
The correct msgID can be obtained from following method,
JavaScript
1
13
13
1
def get_mime_message(service, user_id, msg_id):
2
try:
3
message = service.users().messages().get(userId=user_id, id=msg_id,
4
format='raw').execute()
5
6
msg_str = base64.urlsafe_b64decode(message['raw']).decode()
7
8
mime_msg = email.message_from_string(msg_str)
9
10
return mime_msg
11
except errors.HttpError as error:
12
print('An error occurred: %s' % error
13
The msgID can be obtained as follow,
JavaScript
1
3
1
ms = get_mime_message(gmail_service, USER_ID, msg_id)
2
msgID = format(ms['Message-ID'])
3
Do not confuse msg_id with msgID. msg_id is gmail specific and msgID is global. This msgID should be used in ‘Reference’ and ‘In-Reply-To’ headers.