I'm currently trying to automate incoming emails with python. I'm using the IMAP_TOOLS library. I've already managed to get the necessary values, but I need the time when the email response arrived, but I can't get this information
from imap_tools import MailBox, AND
from datetime import date
data_atual = date.today()
data_hoje = '{}/{}/{}'.format(data_atual.day, data_atual.month,data_atual.year)
valores_lista = []
# pegar emails de um remetente para um destinatário
username = "[REDACTED]@gmail.com"
password = "[REDACTED]"
# lista de imaps: https://www.systoolsgroup.com/imap/
meu_email = MailBox('imap.gmail.com').login(username, password)
lista = []
#pegar emails enviados por remetente especifico
coluna = 0
lista_emails = meu_email.fetch(AND(from_="[REDACTED]@gmail.com", to="c[REDACTED]@gmail.com",subject="MOV:",answered=True))
for email in lista_emails:
email_subject = email.subject
print(email_subject)
email_hora = email.date_str
#print(email_hora)
hora0, hora1, hora2, hora3, hora_enviado,hora4 = email_hora.split()
variavel0,variavel1,variavel2,variavel3,mv,variavel4 = email_subject.split()
mv_ = mv.replace("MOV:","").replace("/UP:","")
print(mv_)
#print("Envio: ",mv + hora_enviado)
#print(email.reply_to)
lista = [data_hoje,hora_enviado,"","","",mv_]
valores_lista.append(lista)
coluna += 1
print(valores_lista)
I tried to use the documentation functions from the imap_tools documentation
msg.to_values
msg.from_values
but it returns empty.
The IMAP standard does not expose this information directly.
What you can examine is:
The
Date:header gets injected by the sender (typically automatically by their email client) and indicates the system time on the sending computer (or, in some circumstances, if this header was not added by the sender, the MTA which initially received the submission), usually in their local time zone, sometimes with formatting which violates the RFC.Date: Tue, 01 Nov 2022 09:03:51 +0200email.message.EmailMessage, the value can be extracted withmessage["date"]and parsed into adatetimeobject withmessage["date"].datetime.email.policywill sometimes balk if theDate:header is not in the standard RFC format, though it is resilient against minor variations; for example, if the weekday is translated, but the month name can be parsed, it will cope just fine, and actually expose the weekday in English even though the original had it in some other language. If theDate:header could not be parsed, thedatetimeattribute will beNone.imap_toolscontains the roughly equivalent information inmsg.date; per the documentation, it will be adatetimeobject which defaults to 1900-01-01 if the header could not be parsed. The originalDate:header is inmsg.date_strThe
Received:headers may contain this information, but their format is not specified in any standard.Received:headers are added from bottom to top. Generally, the topmostReceived:header will be the one to look at, though some systems will add multiple headers, some of them with other information than the actual delivery event.Received: from internal.relay.example.com (unknown [10.9.8.7])by imap.example.com (Postfix) with ESMTP id DEADBEEFABADfor <[email protected]>; Wed, 7 Jul 2022 19:06:47 +0300 (EEST)Received: by 2002:a05:6502:61c:0b:232:4e44:489d with SMTP id g1csp123456abc;Thu, 20 Oct 2022 01:22:33 -0700 (PDT)imaptoolscollects the headers inmsg.headersin a slightly weirddictstructure, but this seems to omit the details and extract only the parsed host name.Received:header out of a Gmail message from theemail.message.EmailMessageobject inmsg.objas provided byimap_tools: See also How to parse a RFC 2822 date/time into a Python datetime? for some variations and amplifications.In a "happy scenario" the difference between the two will be fairly minor, but it is not unheard of for a message to spend several hours or even days in transit, so if you need the time the message was actually delivered, the latter is (unfortunately) the answer.