In my quest to automate my email - I've started small. I work as a Jr. SysAdmin and people frequently email me things that really should have been sent to our ticket queue. At this point I'm so lazy I'm tired of forwarding the emails and replying that I'm sending it to our queue.
Therefore, I've written (stole) the following ruby code - which allows me to drap (drag + drop) an email into a folder in my inbox - have the ruby script run on a cron and ship it out. So far I'm able talk to my inbox get to the "send to ticket queue" folder, read all emails extract all the info I need to construct my forward and response. Then I can fire off the mail successfully.
What I'd like is constructive criticism. For example, I really don't like lines 36 and 37 where I have two return statements returning arrays. Also, I'd like to better iterate through my "sendEmail" while loop. Something better than using the "bodyArray" length.
I'm going to add to this script to move the emails into another folder "sent to ticket queue" after this scripts does it's thing.
Anyway, be brutal if you want - just help me make it better.
Thanks!
1 #!/bin/ruby
2
3 require 'net/imap'
4 require 'net/smtp'
5
6
7 USERNAME = "myUser"
8 PASSWORD = "neverGonnaGetIt"
9
10 bodyArray = []
11 nameArray = []
12
13
14 #scans emails in "Inbox/.toRT" and builds arrays
15 def getmsgs(username, password, emailBodyArray, emailNameArray)
16 at="@"
17 imap = Net::IMAP.new("imap.myOrg.com",993,true)
18 imap.login(username, password)
19 imap.select("Inbox/.toRT")
20 imap.search(["ALL"]).each do |msg|
21 envelope = imap.fetch(msg, "ENVELOPE")[0].attr["ENVELOPE"]
22 sender = envelope.from[0].mailbox
23 host = envelope.from[0].host
24 emailaddress = sender + at + host
25 body = imap.fetch(msg,'BODY[TEXT]')[0].attr['BODY[TEXT]']
26
27 emailBodyArray.push(body)
28 emailNameArray.push(emailaddress)
29
30 # puts body
31 # puts sender
32 end
33
34 imap.logout
35 imap.disconnect
36 return emailBodyArray
37 return emailNameArray
38 end
39
40 def sendEmail(username, password, bodyToSendArray, nameToSendArray)
41 smtp = Net::SMTP.new 'smtp.myOrg.com',587
42 smtp.enable_starttls
43 smtp.start('myOrg.com',username, password, :login)
44 $i = 0
45 $num = bodyToSendArray.length
46 while $i < $num do
47 msg = "Subject: Hello \n\n requestor: #{nameToSendArray[$i]} \n\n Thank you for your message. I have forwarded your request to our ticketing system ([email protected]). This will ensure the fastest response possible. \n\n Orignal Message: \n #{bodyToSendArray[$i]}"
48 smtp.send_message(msg, '[email protected]', [nameToSendArray[$i], '[email protected]'])
49 $i +=1
50 end
51 end
52
53
54 getmsgs(USERNAME,PASSWORD,bodyArray, nameArray)
55 sendEmail(USERNAME,PASSWORD,bodyArray, nameArray)
~