Skip to content

Instantly share code, notes, and snippets.

@alexiskattan
Forked from bergie/.gitignore
Created December 14, 2012 09:06
Show Gist options
  • Save alexiskattan/4283888 to your computer and use it in GitHub Desktop.
Save alexiskattan/4283888 to your computer and use it in GitHub Desktop.
config.json
reading-image.png

Some examples of sending and receiving emails with Node.js.

This uses the following libraries:

Running

Copy config.json.example to config.json and enter your email account details.

Run coffee send.coffee to send yourself an email with an attachment.

Run coffee read.coffee to receive the sent email and write the attachment back to disk with a new name.

{
"name": "My Name",
"email": "user@domain.com",
"username": "user@gmail.com",
"password": "MYPASSWORD",
"imap": {
"host": "imap.gmail.com",
"port": 993,
"secure": true
},
"smtp": {
"host": "smtp.gmail.com",
"ssl": true
}
}
# This example script opens an IMAP connection to the server and
# seeks unread messages sent by the user himself. It will then
# download those messages, parse them, and write their attachments
# to disk.
# Install node-imap with `npm install imap`
imap = require "imap"
# Install mailparser with `npm install mailparser`
mailparser = require "mailparser"
# You need a config file with your email settings
fs = require "fs"
config = JSON.parse fs.readFileSync "#{process.cwd()}/config.json", "utf-8"
server = new imap.ImapConnection
username: config.username
password: config.password
host: config.imap.host
port: config.imap.port
secure: config.imap.secure
exitOnErr = (err) ->
console.error err
do process.exit
server.connect (err) ->
exitOnErr err if err
server.openBox "INBOX", false, (err, box) ->
exitOnErr err if err
console.log "You have #{box.messages.total} messages in your INBOX"
server.search ["UNSEEN", ["SINCE", "Sep 18, 2011"], ["FROM", config.email]], (err, results) ->
exitOnErr err if err
unless results.length
console.log "No unread messages from #{config.email}"
do server.logout
return
fetch = server.fetch results,
request:
body: "full"
headers: false
fetch.on "message", (message) ->
fds = {}
filenames = {}
parser = new mailparser.MailParser
parser.on "headers", (headers) ->
console.log "Message: #{headers.subject}"
parser.on "attachment", (attachment)->
console.log attachment.generatedFileName
output = fs.createWriteStream(attachment.generatedFileName)
attachment.stream.pipe(output)
message.on "data", (data) ->
parser.write data.toString()
message.on "end", ->
do parser.end
fetch.on "end", ->
do server.logout
# This script will send an image as an email attachment to the
# user himself. The receiving part of this is in read.coffee
# Install EmailJS with `npm install emailjs`
email = require "emailjs"
# You need a config file with your email settings
fs = require "fs"
config = JSON.parse fs.readFileSync "#{process.cwd()}/config.json", "utf-8"
server = email.server.connect
user: config.username
password: config.password
host: config.smtp.host
ssl: config.smtp.ssl
message = email.message.create
text: "This is test"
from: "#{config.name} <#{config.email}>"
to: "#{config.name} <#{config.email}>"
subject: "Testing Node.js email capabilities"
message.attach "reading.png", "image/png", "reading-image.png"
server.send message, (err, message) ->
return console.error err if err
console.log "Message sent with id #{message['header']['message-id']}"
@nstewart
Copy link

nstewart commented Jan 9, 2013

Hi, thank you for making this. What version of imap and mailparser are you using? When I run this, send.js works fine but I get an error in read.js. I'm using imap@.075 and mailparser@0.2.31

PS C:\node\emailtest> node read.js
You have 7 messages in your INBOX

C:\node\emailtest\node_modules\imap\lib\imap.js:943
if (wp.id !== undefined && !/^(?:[\d]+[.]{0,1})*[\d]+$/.test(''+wp.id))

TypeError: Cannot read property 'id' of undefined
at ImapConnection._fetch (C:\node\emailtest\node_modules\imap\lib\imap.js:943:11)
at ImapConnection.fetch (C:\node\emailtest\node_modules\imap\lib\imap.js:917:15)
at ImapConnection. (C:\node\emailtest\read.js:43:28)
at ondata (C:\node\emailtest\node_modules\imap\lib\imap.js:662:30)
at CleartextStream.ondata (C:\node\emailtest\node_modules\imap\lib\imap.js:590:16)
at CleartextStream.emit (events.js:67:17)
at CleartextStream._push (tls.js:371:12)
at SecurePair.cycle (tls.js:734:20)
at EncryptedStream.write (tls.js:130:13)
at Socket.ondata (stream.js:38:26)

@nstewart
Copy link

nstewart commented Jan 9, 2013

Got it.
Two things:

  1. for my fetch args I had to set body: true and headers: { parse: false }
  2. I had to set mailparser option "streamAttachments" to true

@marcozingaro
Copy link

Hi guys,

This is my first post on github so please be gentle :-)
Same as nstewart, send works but read doesn't. However I get a different error message:
.>coffee read.coffee
TypeError: undefined is not a function
at Object. (a:\Documents\Webpages\nodejs\read.coffee:15:14)
at Object. (a:\Documents\Webpages\nodejs\read.coffee:7:1)
at Module._compile (module.js:460:26)

  1. I had to set mailparser option "streamAttachments" to true?

Where? Why isn't this code forked into a workable version (or maybe it is?)

Thanks,
Marco

@marcozingaro
Copy link

Got it... I had to remove .ImapConnection (I guess imap was updated since 2012 😄 )
Now I'm having TimeOut issues...

@angy71
Copy link

angy71 commented Jul 6, 2019

Hi, can you help me with solving of:
config = JSON.parse fs.readFileSync "#{process.cwd()}/config.json", "utf-8"
^^

SyntaxError: Unexpected identifier

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment