Merge pull request #285 from AllAboutEE/dev

Read and Send Email Examples
This commit is contained in:
Vowstar 2015-03-16 18:28:43 +08:00
commit d8c8d257ce
4 changed files with 495 additions and 0 deletions

View File

@ -0,0 +1,120 @@
---
-- Working Example: https://www.youtube.com/watch?v=PDxTR_KJLhc
-- @author Miguel (AllAboutEE.com)
-- @description This example will read the first email in your inbox using IMAP and
-- display it through serial. The email server must provided unecrypted access. The code
-- was tested with an AOL and Time Warner cable email accounts (GMail and other services who do
-- not support no SSL access will not work).
require("imap")
local IMAP_USERNAME = "email@domain.com"
local IMAP_PASSWORD = "password"
-- find out your unencrypted imap server and port
-- from your email provided i.e. google "[my email service] imap settings" for example
local IMAP_SERVER = "imap.service.com"
local IMAP_PORT = "143"
local IMAP_TAG = "t1" -- You do not need to change this
local IMAP_DEBUG = true -- change to true if you would like to see the entire conversation between
-- the ESP8266 and IMAP server
local SSID = "ssid"
local SSID_PASSWORD = "password"
local count = 0 -- we will send several IMAP commands/requests, this variable helps keep track of which one to send
-- configure the ESP8266 as a station
wifi.setmode(wifi.STATION)
wifi.sta.config(SSID,SSID_PASSWORD)
wifi.sta.autoconnect(1)
-- create an unencrypted connection
local imap_socket = net.createConnection(net.TCP,0)
---
-- @name setup
-- @description A call back function used to begin reading email
-- upon sucessfull connection to the IMAP server
function setup(sck)
-- Set the email user name and password, IMAP tag, and if debugging output is needed
imap.config(IMAP_USERNAME,
IMAP_PASSWORD,
IMAP_TAG,
IMAP_DEBUG)
imap.login(sck)
end
imap_socket:on("connection",setup) -- call setup() upon connection
imap_socket:connect(IMAP_PORT,IMAP_SERVER) -- connect to the IMAP server
local subject = ""
local from = ""
local message = ""
---
-- @name do_next
-- @description A call back function for a timer alarm used to check if the previous
-- IMAP command reply has been processed. If the IMAP reply has been processed
-- this function will call the next IMAP command function necessary to read the email
function do_next()
-- Check if the IMAP reply was processed
if(imap.response_processed() == true) then
-- The IMAP reply was processed
if (count == 0) then
-- After logging in we need to select the email folder from which we wish to read
-- in this case the INBOX folder
imap.examine(imap_socket,"INBOX")
count = count + 1
elseif (count == 1) then
-- After examining/selecting the INBOX folder we can begin to retrieve emails.
imap.fetch_header(imap_socket,imap.get_most_recent_num(),"SUBJECT") -- Retrieve the SUBJECT of the first/newest email
count = count + 1
elseif (count == 2) then
subject = imap.get_header() -- store the SUBJECT response in subject
imap.fetch_header(imap_socket,imap.get_most_recent_num(),"FROM") -- Retrieve the FROM of the first/newest email
count = count + 1
elseif (count == 3) then
from = imap.get_header() -- store the FROM response in from
imap.fetch_body_plain_text(imap_socket,imap.get_most_recent_num()) -- Retrieve the BODY of the first/newest email
count = count + 1
elseif (count == 4) then
body = imap.get_body() -- store the BODY response in body
imap.logout(imap_socket) -- Logout of the email account
count = count + 1
else
-- display the email contents
-- create patterns to strip away IMAP protocl text from actual message
pattern1 = "(\*.+\}\r\n)" -- to remove "* n command (BODY[n] {n}"
pattern2 = "(%)\r\n.+)" -- to remove ") t1 OK command completed"
from = string.gsub(from,pattern1,"")
from = string.gsub(from,pattern2,"")
print(from)
subject = string.gsub(subject,pattern1,"")
subject = string.gsub(subject,pattern2,"")
print(subject)
body = string.gsub(body,pattern1,"")
body = string.gsub(body,pattern2,"")
print("Message: " .. body)
tmr.stop(0) -- Stop the timer alarm
imap_socket:close() -- close the IMAP socket
collectgarbage() -- clean up
end
end
end
-- A timer alarm is sued to check if an IMAP reply has been processed
tmr.alarm(0,1000,1, do_next)

View File

@ -0,0 +1,129 @@
---
-- Working Example: https://www.youtube.com/watch?v=CcRbFIJ8aeU
-- @description a basic SMTP email example. You must use an account which can provide unencrypted authenticated access.
-- This example was tested with an AOL and Time Warner email accounts. GMail does not offer unecrypted authenticated access.
-- To obtain your email's SMTP server and port simply Google it e.g. [my email domain] SMTP settings
-- For example for timewarner you'll get to this page http://www.timewarnercable.com/en/support/faqs/faqs-internet/e-mailacco/incoming-outgoing-server-addresses.html
-- To Learn more about SMTP email visit:
-- SMTP Commands Reference - http://www.samlogic.net/articles/smtp-commands-reference.htm
-- See "SMTP transport example" in this page http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol
-- @author Miguel
require("base64")
-- The email and password from the account you want to send emails from
local MY_EMAIL = "esp8266@domain.com"
local EMAIL_PASSWORD = "123456"
-- The SMTP server and port of your email provider.
-- If you don't know it google [my email provider] SMTP settings
local SMTP_SERVER = "smtp.server.com"
local SMTP_PORT = "587"
-- The account you want to send email to
local mail_to = "to_email@domain.com"
-- Your access point's SSID and password
local SSID = "ssid"
local SSID_PASSWORD = "password"
-- configure ESP as a station
wifi.setmode(wifi.STATION)
wifi.sta.config(SSID,SSID_PASSWORD)
wifi.sta.autoconnect(1)
-- These are global variables. Don't change their values
-- they will be changed in the functions below
local email_subject = ""
local email_body = ""
local count = 0
local smtp_socket = nil -- will be used as socket to email server
-- The display() function will be used to print the SMTP server's response
function display(sck,response)
print(response)
end
-- The do_next() function is used to send the SMTP commands to the SMTP server in the required sequence.
-- I was going to use socket callbacks but the code would not run callbacks after the first 3.
function do_next()
if(count == 0)then
count = count+1
local IP_ADDRESS = wifi.sta.getip()
smtp_socket:send("HELO "..IP_ADDRESS.."\r\n")
elseif(count==1) then
count = count+1
smtp_socket:send("AUTH LOGIN\r\n")
elseif(count == 2) then
count = count + 1
smtp_socket:send(base64.enc(MY_EMAIL).."\r\n")
elseif(count == 3) then
count = count + 1
smtp_socket:send(base64.enc(EMAIL_PASSWORD).."\r\n")
elseif(count==4) then
count = count+1
smtp_socket:send("MAIL FROM:<" .. MY_EMAIL .. ">\r\n")
elseif(count==5) then
count = count+1
smtp_socket:send("RCPT TO:<" .. mail_to ..">\r\n")
elseif(count==6) then
count = count+1
smtp_socket:send("DATA\r\n")
elseif(count==7) then
count = count+1
local message = string.gsub(
"From: \"".. MY_EMAIL .."\"<"..MY_EMAIL..">\r\n" ..
"To: \"".. mail_to .. "\"<".. mail_to..">\r\n"..
"Subject: ".. email_subject .. "\r\n\r\n" ..
email_body,"\r\n.\r\n","")
smtp_socket:send(message.."\r\n.\r\n")
elseif(count==8) then
count = count+1
tmr.stop(0)
smtp_socket:send("QUIT\r\n")
else
smtp_socket:close()
end
end
-- The connectted() function is executed when the SMTP socket is connected to the SMTP server.
-- This function will create a timer to call the do_next function which will send the SMTP commands
-- in sequence, one by one, every 5000 seconds.
-- You can change the time to be smaller if that works for you, I used 5000ms just because.
function connected(sck)
tmr.alarm(0,5000,1,do_next)
end
-- @name send_email
-- @description Will initiated a socket connection to the SMTP server and trigger the connected() function
-- @param subject The email's subject
-- @param body The email's body
function send_email(subject,body)
count = 0
email_subject = subject
email_body = body
smtp_socket = net.createConnection(net.TCP,0)
smtp_socket:on("connection",connected)
smtp_socket:on("receive",display)
smtp_socket:connect(SMTP_PORT,SMTP_SERVER)
end
-- Send an email
send_email(
"ESP8266",
[[Hi,
How are your IoT projects coming along?
Best Wishes,
ESP8266]])

View File

@ -0,0 +1,41 @@
-- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de>
-- licensed under the terms of the LGPL2
local moduleName = ...
local M = {}
_G[moduleName] = M
-- character table string
local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
-- encoding
function M.enc(data)
return ((data:gsub('.', function(x)
local r,b='',x:byte()
for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
return r;
end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
if (#x < 6) then return '' end
local c=0
for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
return b:sub(c+1,c+1)
end)..({ '', '==', '=' })[#data%3+1])
end
-- decoding
function M.dec(data)
data = string.gsub(data, '[^'..b..'=]', '')
return (data:gsub('.', function(x)
if (x == '=') then return '' end
local r,f='',(b:find(x)-1)
for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
return r;
end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
if (#x ~= 8) then return '' end
local c=0
for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(7-i) or 0) end
return string.char(c)
end))
end
return M

205
lua_modules/email/imap.lua Normal file
View File

@ -0,0 +1,205 @@
---
-- Working Example: https://www.youtube.com/watch?v=PDxTR_KJLhc
-- IMPORTANT: run node.compile("imap.lua") after uploading this script
-- to create a compiled module. Then run file.remove("imap.lua")
-- @name imap
-- @description An IMAP 4rev1 module that can be used to read email.
-- Tested on NodeMCU 0.9.5 build 20150213.
-- @date March 12, 2015
-- @author Miguel
-- GitHub: https://github.com/AllAboutEE
-- YouTube: https://www.youtube.com/user/AllAboutEE
-- Website: http://AllAboutEE.com
--
-- Visit the following URLs to learn more about IMAP:
-- "How to test an IMAP server by using telnet" http://www.anta.net/misc/telnet-troubleshooting/imap.shtml
-- "RFC 2060 - Internet Message Access Protocol - Version 4rev1" http://www.faqs.org/rfcs/rfc2060.html
-------------------------------------------------------------------------------------------------------------
local moduleName = ...
local M = {}
_G[moduleName] = M
local USERNAME = ""
local PASSWORD = ""
local SERVER = ""
local PORT = ""
local TAG = ""
local DEBUG = false
local body = "" -- used to store an email's body / main text
local header = "" -- used to store an email's last requested header field e.g. SUBJECT, FROM, DATA etc.
local most_recent_num = 1 -- used to store the latest/newest email number/id
local response_processed = false -- used to know if the last IMAP response has been processed
---
-- @name response_processed
-- @returns The response process status of the last IMAP command sent
function M.response_processed()
return response_processed
end
---
-- @name display
-- @description A generic IMAP response processing function.
-- Can disply the IMAP response if DEBUG is set to true.
-- Sets the reponse processed variable to true when the string "complete"
-- is found in the IMAP reply/response
local function display(socket, response)
-- If debuggins is enabled print the IMAP response
if(DEBUG) then
print(response)
end
-- Some IMAP responses are long enough that they will cause the display
-- function to be called several times. One thing is certain, IMAP will replay with
-- "<tag> OK <command> complete" when it's done sending data back.
if(string.match(response,'complete') ~= nil) then
response_processed = true
end
end
---
-- @name config
-- @description Initiates the IMAP settings
function M.config(username,password,tag,debug)
USERNAME = username
PASSWORD = password
TAG = tag
DEBUG = debug
end
---
-- @name login
-- @descrpiton Logs into a new email session
function M.login(socket)
response_processed = false -- we are sending a new command
-- which means that the response for it has not been processed
socket:send(TAG .. " LOGIN " .. USERNAME .. " " .. PASSWORD .. "\r\n")
socket:on("receive",display)
end
---
-- @name get_most_recent_num
-- @returns The most recent email number. Should only be called after examine()
function M.get_most_recent_num()
return most_recent_num
end
---
-- @name set_most_recent_num
-- @description Gets the most recent email number from the EXAMINE command.
-- i.e. if EXAMINE returns "* 4 EXISTS" this means that there are 4 emails,
-- so the latest/newest will be identified by the number 4
local function set_most_recent_num(socket,response)
if(DEBUG) then
print(response)
end
local _, _, num = string.find(response,"([0-9]+) EXISTS(\.)") -- the _ and _ keep the index of the string found
-- but we don't care about that.
if(num~=nil) then
most_recent_num = num
end
if(string.match(response,'complete') ~= nil) then
response_processed = true
end
end
---
-- @name examine
-- @description IMAP examines the given mailbox/folder. Sends the IMAP EXAMINE command
function M.examine(socket,mailbox)
response_processed = false
socket:send(TAG .. " EXAMINE " .. mailbox .. "\r\n")
socket:on("receive",set_most_recent_num)
end
---
-- @name get_header
-- @returns The last fetched header field
function M.get_header()
return header
end
---
-- @name set_header
-- @description Records the IMAP header field response in a variable
-- so that it may be read later
local function set_header(socket,response)
if(DEBUG) then
print(response)
end
header = header .. response
if(string.match(response,'complete') ~= nil) then
response_processed = true
end
end
---
-- @name fetch_header
-- @description Fetches an emails header field e.g. SUBJECT, FROM, DATE
-- @param socket The IMAP socket to use
-- @param msg_number The email number to read e.g. 1 will read fetch the latest/newest email
-- @param field A header field such as SUBJECT, FROM, or DATE
function M.fetch_header(socket,msg_number,field)
header = "" -- we are getting a new header so clear this variable
response_processed = false
socket:send(TAG .. " FETCH " .. msg_number .. " BODY[HEADER.FIELDS (" .. field .. ")]\r\n")
socket:on("receive",set_header)
end
---
-- @name get_body
-- @return The last email read's body
function M.get_body()
return body
end
---
-- @name set_body
-- @description Records the IMAP body response in a variable
-- so that it may be read later
local function set_body(socket,response)
if(DEBUG) then
print(response)
end
body = body .. response
if(string.match(response,'complete') ~= nil) then
response_processed = true
end
end
---
-- @name fetch_body_plain_text
-- @description Sends the IMAP command to fetch a plain text version of the email's body
-- @param socket The IMAP socket to use
-- @param msg_number The email number to obtain e.g. 1 will obtain the latest email
function M.fetch_body_plain_text(socket,msg_number)
response_processed = false
body = "" -- clear the body variable since we'll be fetching a new email
socket:send(TAG .. " FETCH " .. msg_number .. " BODY[1]\r\n")
socket:on("receive",set_body)
end
---
-- @name logout
-- @description Sends the IMAP command to logout of the email session
function M.logout(socket)
response_processed = false
socket:send(TAG .. " LOGOUT\r\n")
socket:on("receive",display)
end