E-mail Processing

While it may not be nearly as kooky as calling Processing on the phone, I’ve been asked about checking e-mail from Processing several times this semester. So rather than try to dig up example code on the internets, I’ve quickly thrown together one that checks a POP account and/or sends mail via SMTP. It’s all done with Javamail.

Download the example sketch.

Code snippets after the jump. . .

    Properties props = System.getProperties();
 
    props.put("mail.pop3.host", "pop.gmail.com");
 
    // These are security settings required for gmail
    // May need different code depending on the account
    props.put("mail.pop3.port", "995");
    props.put("mail.pop3.starttls.enable", "true");
    props.setProperty("mail.pop3.socketFactory.fallback", "false");
    props.setProperty("mail.pop3.socketFactory.class","javax.net.ssl.SSLSocketFactory");
 
    // Create authentication object
    Auth auth = new Auth();
 
    // Make a session
    Session session = Session.getDefaultInstance(props, auth);
    Store store = session.getStore("pop3");
    store.connect();
 
    // Get inbox
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);
    System.out.println(folder.getMessageCount() + " total messages.");
 
    // Get array of messages and display them
    Message message[] = folder.getMessages();
    for (int i=0; i < message.length; i++) {
      System.out.println("---------------------");
      System.out.println("Message # " + (i+1));
      System.out.println("From: " + message[i].getFrom()[0]);
      System.out.println("Subject: " + message[i].getSubject());
      System.out.println("Message:");
      String content = message[i].getContent().toString(); 
      System.out.println(content);
    }
 
    // Close the session
    folder.close(false);
    store.close();

and sending:

  // Create a session
  String host="smtp.gmail.com";
  Properties props=new Properties();
 
  // SMTP Session
  props.put("mail.transport.protocol", "smtp");
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.port", "25");
  props.put("mail.smtp.auth", "true");
  // We need TTLS, which gmail requires
  props.put("mail.smtp.starttls.enable","true");
 
  // Create a session
  Session session = Session.getDefaultInstance(props, new Auth());
 
  try
  {
    // Make a new message
    MimeMessage message = new MimeMessage(session);
 
    // Who is this message from
    message.setFrom(new InternetAddress("name@gmail.com", "Name"));
 
    // Who is this message to (we could do fancier things like make a list or add CC's)
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("address@email.com", false));
 
    // Subject and body
    message.setSubject("Hello World!");
    message.setText("It's great to be here. . .");
 
    // We can do more here, set the date, the headers, etc.
    Transport.send(message);
    println("Mail sent!");
  }
  catch(Exception e)
  {
    e.printStackTrace();
  }
  • Acapulco

    Thaks a lot. This is just what I needed, although when I tested it using my gmail account, I couldn’t find a way to stop retrieving the headers, so I had to ctrl-alt-del and stop javaw.exe. Not even using the Processing STOP button or ESC.

    Anyway, it’s pretty simple and easy to use. Thanks again.

  • http://deathofapunchline.com Sebastian Gallese

    Wanted to use the SMTP portion of your library to send text messages via e-mail. I use Teleflip.com to send messages (just e-mail a cellphone number to teleflip.com (e.g., 5555555555@teleflip.com).

    However, wasn’t able to get the sendMail() method working. I did a little online research and found out that I could adjust the SMTP port of javamail to send messages via SSL to gmail.
    I am not sure how secure this is, but it works for the time being.

    I changed the following portions of code under the sendMail() method.

    // SMTP Session
    props.put(“mail.transport.protocol”, “smtp”);
    props.put(“mail.smtp.host”, host);
    props.put(“mail.smtp.port”, “465″);
    props.put(“mail.smtp.auth”, “true”);
    props.put(“mail.smtp.socketFactory.port”, “465″);
    props.put(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);
    // We need TTLS, which gmail requires
    props.put(“mail.smtp.starttls.enable”,”true”);

    // Create a session
    Session session = Session.getDefaultInstance(props, new Auth(“sebastiang@gmail.com”, “mygmailpassword”));

  • http://deathofapunchline.com Sebastian Gallese

    Note: the code I submitted passes in a username and password to Auth. I modified Auth to take those in. In Shiffman’s original code, those Strings are set inside of the Auth class itself.

    Thus the following:

    // Create a session
    Session session = Session.getDefaultInstance(props, new Auth(”sebastiang@gmail.com”, “mygmailpassword”));

    Should look like this with an unaltered Auth class:

    // Create a session
    Session session = Session.getDefaultInstance(props, new Auth());

  • http://www.shiffman.net Daniel

    Thanks for the info Sebastian!

  • Ergy

    Hi I am trying to read an email from from my POP and send an email after a certain event but i get this error:

    javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
    nested exception is:
    java.net.ConnectException: Connection refused
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1227)

    I think for some reason checkmail() is changing the send

  • http://www.artatthelab.com/genDesign marcel

    Hi, i’ve signed an applet with the Email Processing code but it doesn’t work online.

    Errors:

    java.lang.NoClassDefFoundError: javax/mail/Authenticator
    Caused by: java.lang.ClassNotFoundException: javax.mail.Authenticator
    Caused by: java.io.IOException: open HTTP connection failed:http://www.artatthelab.com/genDesign/processing/staMonica/applet/javax/mail/Authenticator.class
    Excepción: java.lang.NoClassDefFoundError: javax/mail/Authenticator

    Any suggestion?

    Thank you very much

  • Pingback: Processing > Flickr SUCCESS! — Natalie Rachel

  • Steve

    Hey, great code – gonna come in handy with a project I’m working on. One problem I have using the example code is I’m only getting 347 total messages, even though the account I’m reading has over 2000. Any suggestions?

  • Anirudh

    Hi
    I tried compiling my program. Its not working.
    This is whats shown on the screen,

    javax.mail.NoSuchProviderException: smtp
    at javax.mail.Session.getService(Session.java:784)
    at javax.mail.Session.getTransport(Session.java:720)
    at javax.mail.Session.getTransport(Session.java:660)
    at javax.mail.Session.getTransport(Session.java:640)
    at javax.mail.Session.getTransport(Session.java:697)
    at javax.mail.Transport.send0(Transport.java:192)
    at javax.mail.Transport.send(Transport.java:124)
    at Processing3.sendMail(Processing3.java:111)
    at Processing3.draw(Processing3.java:69)
    at processing.core.PApplet.handleDraw(Unknown Source)
    at processing.core.PApplet.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:619)

    Any suggestions??

  • Pete Sekan

    It still works!
    With imap, too.

    Thank you, Daniel!

    Greetz,
    Pete

  • Blaise Mibeck

    Best.Trick.Ever!

  • http://mp4tomp3converter.org/ Linda

    I found out about this trick several years ago and still use it, it’s very effective. Kudos to the person who got the idea!

  • lukas

    What do i have to change to make it working on android?

  • Chris

    Hi Daniel
    This works perfectly in processing on my own computer, but I continue to get authorization errors when running from a compiled applet. I’ve heard that Java applets are often automatically denied smtp authorization, unless running on the same server they are trying to send from. I am running mine in the htdocs folder on my own networksolutions hosted server the same one as the email. The error I get is “b.a.n:smtp” Any Ideas?

    PS:
    compiling from processing 2.0a5

  • shiffman

    not sure, you can try signing the applet.  http://wiki.processing.org/w/Sign_an_Applet

  • C_tre25

    How can you edit this to only show new emails?

  • Varun

    hey thanks for the code man. I really need to learn this for a project I’m doing.
    One question:
    When I comment out your checkmail() so I can only use the sendmail(). I did not get any file sent to my gmail account. Maybe because I did not install the javamail library properly.

    I went on the page http://java.sun.com/products/javamail/ to download the java.mail library
    Downloaded JavaMail API 1.4.5 Release (If this is the right folder)
    Inside this folder

    I then changed the renamed the lib folder to library(and placed mail the mail inside this folder too), demo to example and docs to documentations (placed all notepad files inside the this folder too).

    Is this the right way to do it?
    I really want to learn email with processing so help me out here. Thanks in advance.

  • paul

    ?? when I try to compile the pde all I get is an error “Email.pde:-1: error: ‘import’ does not name a type” I assume its not finding the jar files.? so what am I missing hear??

  • Rachael Brown

    How do I get it to work with Imap?

  • http://www.facebook.com/rahul.ranjan.3990 Rahul Ranjan

    I get error that class Properties could not be found. what i do ??

  • Dave Robertson

    Hi – I added “import java.util.Properties;” to the mailstuff.pde – worked!

  • Dave Robertson

    Hi – if anyone wants an IMAP version of this – its here http://dhrobertson.com/processing/Email.zip . IMAP seems to be a lot better for gmail – as you cans search folders and get unread messages. POP3 only gives you everything in the inbox, deleted items and wont show you what’s been read. The check and send work ok – you just need to send the to and from addresses. I also updated to the latest version of javamail – 1.4.7

  • shiffman

    This is great, thank you!