Getting a script to send an email (gmail)

OK, so I had a lot of trouble out of this and it took a couple days and a couple humble moments of asking a few people for help to get it right. How could I run a script, say the 404 finder, and have the results of a test sent directly to your user or whoever automatically? Luckily Ruby has multiple Gems to do this, but Gmail is a little different. Now the first thing we're going to do is login into your Google Account and allow less secure apps (https://support.google.com/accounts/answer/6010255?hl=en). Now we can code and that's the fun part!

The gem I am using for this project is the gmail gem which can be installed by "gem install gmail." I found a little piece of code in the documentation that allowed me to do exactly what I wanted aside from one little thing, but let me explain what code I have thus far.







So this should be pretty intuitive. The function takes certain inputs. Sender email with the password so the program can log into gmail. Then it will take the recipient email, a subject, and a text body. Of course, I had a problem I want my program to be fluid, I want to be able to ask the user "Who do you want to send it to?" and then use user input as the email. You can't just make a variable like "email" and equal it to gets.chomp and use it within a function. Variables within a function are local, so you have to make the variables we use global. You can do this very easily by adding a "$" to whatever you want to do. So instead of recipientEmail as our variable, we can use $recipientEmail. This means it is usable within the entire program. 



No comments:

Post a Comment