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();
  }

6 Responses to “E-mail Processing”  

  1. 1 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.

  2. 2 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”));

  3. 3 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());

  4. 4 Daniel

    Thanks for the info Sebastian!

  5. 5 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

  6. 6 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

Leave a Reply