Skip to content

Instantly share code, notes, and snippets.

/readEmail.py

Created Apr 23, 2013
Embed
What would you like to do?
import imaplib
import email
imap_server = imaplib.IMAP4_SSL('imap.gmail.com','993')
imap_server.login('ariggs.writing.project@gmail.com','SorryNotInThisGist')
imap_server.select('INBOX')
#Some functions
#http://bitsofpy.blogspot.com/2010/05/python-and-gmail-with-imap.html
def get_emails(email_ids):
data = []
for e_id in email_ids:
_, response = imap_server.fetch(e_id, '(UID BODY[TEXT])')
data.append(response[0][1])
return data
def get_subjects(email_ids):
subjects = []
for e_id in email_ids:
_, response = imap_server.fetch(e_id, '(body[header.fields (subject)])')
subjects.append( response[0][1][9:] )
return subjects
# Search for all new mail
#http://bitsofpy.blogspot.com/2010/05/python-and-gmail-with-imap.html
#Print number of unread messages
#http://stackoverflow.com/questions/953561/check-unread-count-of-gmail-messages-with-python
status, email_ids = imap_server.search(None, '(UNSEEN)')
#print type(email_ids)
numUnread = len(imap_server.search(None, 'UnSeen')[1][0].split())
#print "Num unread: ", numUnread
#If unread emails exist
if(numUnread > 0):
#Turn email_ids into a list of ids
idString = email_ids[0]
lstIDs = idString.split()
#grab body of emails and append together
emailBody = get_emails(lstIDs)
emailString = str(emailBody) #convert to string
#Parse email and grab only text between <start> and <stop>
startIndex = emailString.find("(s)")
stopIndex = emailString.find("(e)")
if(stopIndex != -1):
emailString = emailString[startIndex+3: stopIndex] #Include offsets for bracket and carriage returns
#Print email and write to file "out.txt"
#print "Email String: ", emailString
print emailString
#print "Writing email to out.txt"
#file = open("/Users/allieriggs/Documents/Processing/writing_demo/out.txt", "w") #open file and append to it
#file.write(str(emailString))
#print "Closing file"
#file.close()
#Mark unread as Seen
#http://stackoverflow.com/questions/2251977/python-imap-and-gmail-mark-messages-as-seen
#print "Attempting to mark unread messages as read"
typ, data = imap_server.search(None,'UnSeen')
try:
imap_server.store(data[0].replace(' ',','),'+FLAGS','\Seen')
except:
pass
import os
import smtplib
import random
from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.Utils import formatdate
filePath = "/Users/allieriggs/Documents/Processing/writing_demo/text.png" #Path to the attachment you are sending. MUST BE ABSOLUTE
def sendEmail(TO = "ariggs00@gmail.com",
FROM="ariggs.writing.project@gmail.com"):
HOST = "smtp.gmail.com" #Gmail's host since we are using Gmail
subject = random.choice(["Processing Email", "Hey Allie!", "Regarding your project", "Response thingy"])
#Build message
msg = MIMEMultipart()
msg["From"] = FROM
msg["To"] = TO
msg["Subject"] = subject
msg['Date'] = formatdate(localtime=True)
#Attach a file using filePath
part = MIMEBase('application', "octet-stream")
part.set_payload( open(filePath,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filePath))
msg.attach(part)
#Initialize server. Gmail needs TTLS so start a ttls session too
print "Initializing server"
server = smtplib.SMTP(HOST)
#server.connect(HOST);
server.ehlo()
print "Starting ttls"
server.starttls()
#server.ehlo()
print "Logging in"
server.login("ariggs.writing.project@gmail.com", "SorryNotInThisGist") # optional (Necessary if using Gmail as the client)
#Try sending email. If it fails, print the error message
try:
print "Attempting to send email..."
failed = server.sendmail(FROM, TO, msg.as_string())
server.close()
print "Server is closing. Email should be sent."
except Exception, e:
errorMsg = "Unable to send email. Error: %s" % str(e)
print errorMsg
if __name__ == "__main__":
sendEmail()
/**
* Writing Responses
* Allie Riggs and Jason Wright
*
*/
import java.io.*;
import java.util.*;
import java.lang.Math;
import processing.serial.*;
Serial lightbox;
BufferedReader reader; //reads out.txt
String words; //message body from emails
PFont font; //response font
int words_x; // x coordinate of response location
int words_y; // y coordinate of response location
int xi; // cursor location for char by char printing
int ch_delay = 5; //delay between printing chars
int ch_counter = 0; //counts until reaching the delay
int ch_num = -1; //number of the char in the string of words
boolean writing_word = false; //whether or not text is being written
int write_count = 0; //how long person is writing
int wait_count = 0; //how long person is not writing
boolean waiting_check = false; //checks if person is drawing
LinkedList<int[]> coordinates = new LinkedList<int[]>(); //List of mouse coordinates
int[] blank = {-1, -1}; //predetermined coordinates that means nothing is pressed
int list_size = 1000; //size of list can get before coordinate are removed
int list_cutoff = 800; //point of exponential decay (fade)
int list_fade = 20; //constant in exponential decay - greater = slower delay
boolean mailing = false; //waiting for mail
int print_count = 0; //wait time for printing the response
int print_interval = 0; //counts number of print-ervals
int check_interval = 1000; //interval that determines when email is checked
boolean lightbox_pressed = false;
String[] lightbox_coordinates;
int lightbox_wait_amount = 5;
int lightbox_wait = lightbox_wait_amount;
int actualWidth = displayWidth;
int actualHeight = displayHeight;
void setup() {
actualWidth = displayWidth;
actualHeight = displayHeight;
size(actualWidth, actualHeight);
background(255);
font = loadFont("Archer-Book-24.vlw");
println(Serial.list());
// Open the port you are using at the rate you want:
lightbox = new Serial(this, Serial.list()[4], 115200);
}
void draw() {
stroke(0, 0, 0);
strokeWeight(10);
strokeJoin(ROUND);
strokeCap(ROUND);
while (lightbox.available() > 0) {
String inBuffer = lightbox.readStringUntil(10);
if (inBuffer != null) {
lightbox_coordinates = inBuffer.split(",");
lightbox_pressed = true;
//println("drawing: "+inBuffer);
println(lightbox_coordinates[1]);
println(lightbox_coordinates[2]);
println("---");
} else {
lightbox_pressed = false;
}
}
if (mousePressed || lightbox_pressed) {
lightbox_pressed = false;
//gets current mouse coordinates and adds to List
int[] current = {-1, -1};
if (mousePressed) {
current[0] = mouseX;
current[1] = mouseY;
} else {
try {
current[0] = (actualWidth - Integer.parseInt(lightbox_coordinates[2]) * (actualWidth/320));
current[1] = Integer.parseInt(lightbox_coordinates[1]) * (actualHeight/220);
} catch (Exception e) {
//fuggedabout it
}
lightbox_wait = lightbox_wait_amount;
}
coordinates.addFirst(current);
write_count ++;
wait_count = 0;
}
//if person has stopped drawing, add blanks to the List
else {
if (!waiting_check || coordinates.getFirst() != blank) {
if (lightbox_wait > 0) {
lightbox_wait--;
} else {
coordinates.addFirst(blank);
}
}
if (write_count > 0) {
write_count --;
}
}
//println(print_count);
//checks that person is still drawing
if (write_count > 70) {
waiting_check = true;
}
//checks that the person has stopped drawing
if (waiting_check) {
wait_count ++;
//sends email if person has stopped drawing for long enough
if (wait_count > 100) {
sendmail();
wait_count = 0;
write_count = 0;
waiting_check = false;
mailing = true;
print_count = 0;
print_interval = 0;
}
}
if (mailing) {
print_count ++;
}
// makes sure that coordinates doesn't exceed list_size
if (!coordinates.isEmpty()) {
if (coordinates.size() > list_size) {
coordinates.removeLast();
}
//List Iterator: sets prev value to next value
ListIterator it = coordinates.listIterator();
int[] prev = (int[])it.next();
// fades the drawing by pushing out extra values from the LinkedList
while(it.hasNext()) {
int[] curr = (int[])it.next();
if(curr != blank && prev != blank) {
int index = coordinates.indexOf(curr);
if(index > list_cutoff) {
int fade_color = (int)(255 - (255*Math.exp(-1*(index-list_cutoff)/list_fade)));
fade_color = max(min(255, fade_color), 0);
if (fade_color > 220) {
fade_color = 255;
}
stroke(fade_color, fade_color, fade_color);
strokeWeight(12);
}
// does all the drawing
line(curr[0], curr[1], prev[0], prev[1]);
}
prev = curr;
}
if (print_count > check_interval) {
//prints prev text in white
if (words != null) {
printText(words, words_x, words_y, 255);
}
//reads out.txt
readmail();
print_interval ++;
//if empty, prints "still busy"
if (words == null) {
if (print_interval < 2) {
words = " ";
} else {
words = "Sorry, I'm still busy";
print_interval = 0;
}
} else {
mailing = false;
}
print_count = 0;
//otherwise, prints char sequence at random locations
words_x = int(random(width/10, 8*width/10));
words_y = int(random(height/10, 9*height/10));
xi = words_x;
writing_word = true;
ch_counter = 0;
ch_num = -1;
textFont(font, 24);
fill(50);
}
//loop that prints text char by char
if(writing_word) {
if(ch_num < words.length()-1) {
if(ch_counter == ch_delay) {
ch_num++;
ch_delay = int(random(2, 10));
text(words.charAt(ch_num), xi, words_y);
xi += textWidth(words.charAt(ch_num));
ch_counter = 0;
} else {
ch_counter++;
}
} else {
writing_word = false;
}
}
}
}
void keyPressed() {
// s key saves the image, emails Allie
if (key == 's') {
sendmail();
}
// p key prints contents of out.txt
if (key == 'p') {
//prints over previous text with white
if (words != null) {
printText(words, words_x, words_y, 255);
}
//reads out.txt
readmail();
//if empty, prints "still busy"
if (words == null) {
words = "Sorry, I'm still busy";
}
//otherwise, prints char sequence at random locations
words_x = int(random(width/10, 8*width/10));
words_y = int(random(height/10, 9*height/10));
xi = words_x;
writing_word = true;
ch_counter = 0;
ch_num = -1;
textFont(font, 24);
fill(50);
}
//clears screen
if (key == 'c') {
clearScreen();
}
}
// sends an email of text.png to response.tester.project@gmail.com
void sendmail() {
saveFrame("text.png");
println("DRAWING CREATED! STARTING EMAIL PROCESS!");
try {
Process p = Runtime.getRuntime().exec(new String[] {
"python", "/Users/allieriggs/Documents/Processing/writing_demo/sendemail.py"
});
//Buffered reader will print out anything that gets printed out in the python script
//BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
//String line;
//while ( (line = input.readLine ().trim()) != null) {
//println(line);
//}
}
catch (IOException e) {
println(e.getMessage());
}
catch (Exception e)
{
println(e.getMessage());
}
}
// checks for unread emails and prints message body to out.txt
void readmail() {
println("Checking Emails and printing line");
words = null;
try {
Process p = Runtime.getRuntime().exec(new String[] {
"python", "/Users/allieriggs/Documents/Processing/writing_demo/readEmail.py"
}
);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ( (words = input.readLine ().trim()) != null) {
println(words);
}
}
catch (IOException e) {
println(e.getMessage());
}
catch (Exception e)
{
println(e.getMessage());
}
}
// clears the background
void clearScreen() {
background(255);
coordinates.clear();
}
// prints text according to words, location, and color
void printText(String w, int x, int y, int c) {
textFont(font, 24);
fill(c);
text(w, x, y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.