Reputation: 569
Python IMAP4 how to reply to an email with a given UID or last email in Inbox
I have been able to login my gmail with IMAP4 and get the last UID , but I dont know how to reply to the last email in the inbox my python automation code:
self.mail = imaplib.IMAP4_SSL('imap.gmail.com')
self.mail.login(self.data["emailUsername"], self.data["emailPassword"])
self.mail.list()
self.mail.select("inbox")
subjectStr = '(HEADER Subject ' + "\"" + mySubject + "\"" + ')'
result, UIDemailsWithGivenSubject = self.mail.uid('search', None, subjectStr)
ids_string = UIDemailsWithGivenSubject[0].decode("utf-8")
ids_string_list = ids_string.split(" ")
self.lastEmailUid = ids_string_list[-1]
Now how do I respond to the last email or respond/reply with a given UID.
Upvotes: 3
Views: 747
Reputation: 755
You can search the selected mailbox like this:
res, data = self.mail.search(None, 'ALL')
Your data will then look something like this: [b'1 2 3 4 5 6 7 8 9 10 11 12']
where 12
is the UID for the latest email in the selected mailbox. You can now fetch this mail with
self.mail.fetch(data[0].split()[-1], '(RFC822)')
IMAP4.search(charset, criterion[, ...])
returns a list of all emails in your current mailbox. They are typically orderd by date with the first one being the oldest.
Provide None
for the charset to search for any mail and the criterion is set to All
.
See Python imaplib documentation
data[0].split()[-1]
returns the last element ([-1]
) of your list of mail UIDs
You are using the IMAP protocol to access a mailserver. IMAP stands for
Internet Message Access Protocol
It is intendet for message access, not to send mail. You need SMTP to send messages. Take a look at this question.
Upvotes: 2