12.07.2022, 11:01
Use attached imap.lua to create a user library called imap.
This example fetches 3 newest emails from inbox. (App password is needed for this to work with Gmail dues to 2-step auth requirements).
For each email the first 8k (8192 bytes) of data is fetched. Fetching the whole email can lead to an out-of-memory condition if it has a large attachment. Each email has a unique id (UID) which should be an always increasing value. You can put the maximum UID of already parsed message into storage to skip emails that have already been parsed. Extracting data from the email depends on the format. Usually it's HTML split into lines with fixed width so parsing it might be tricky, unless there's an ICS file attached.
This example fetches 3 newest emails from inbox. (App password is needed for this to work with Gmail dues to 2-step auth requirements).
For each email the first 8k (8192 bytes) of data is fetched. Fetching the whole email can lead to an out-of-memory condition if it has a large attachment. Each email has a unique id (UID) which should be an always increasing value. You can put the maximum UID of already parsed message into storage to skip emails that have already been parsed. Extracting data from the email depends on the format. Usually it's HTML split into lines with fixed width so parsing it might be tricky, unless there's an ICS file attached.
Code:
user = 'user@gmail.com'
pass = 'PASSWORD'
imap = require('user.imap')
conn = imap('imap.gmail.com', 993, { protocol = 'tlsv1_2' })
caps = conn:login(user, pass)
info = conn:examine('INBOX')
mcnt = 3 -- number of messages to fetch
query = math.max(1, info.exist - mcnt)
msgs = conn:fetch('(UID BODY.PEEK[HEADER.FIELDS (From Date Subject)])', query .. ':*')
for _, msg in pairs(msgs) do
log('message', msg.id, msg.UID, msg.BODY.value)
data = conn:fetch('BODY[]<0.8192>', msg.id)
log(data[1].BODY.value)
end
conn:logout()