QuickHit: Check Mail Checking from AWS EC2 with JavaMail

To avoid having to install maven or gradle or specialized tools, we just put in a simple class and shell script.    First download the mail jars you need from here.   A simple wget will work on the links.  Keep them in the same dir as the .java and you can use the shell script below.   Real quick and dirty, but works for testing if your local EC2 instance can send email and there’s no firewall or other issues.

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

try { Properties props = System.getProperties();
                props.put("mail.smtp.host", "localhost");
                props.put("mail.debug", "true");
                Session session = Session.getDefaultInstance(props, null);
                session.setDebug(true);
                Transport transport = session.getTransport("smtp");
                MimeMessage message = new MimeMessage(session);
                Address fromAddress = new InternetAddress("root@localhost.localdomain");
                message.setFrom(fromAddress);
                InternetAddress to = new InternetAddress("tspann@COOLDOMAIN.com");
                message.addRecipient(Message.RecipientType.TO, to);
                message.setSubject("Test Mail");
                message.setText("Test Body");
                transport.connect(host, from);
                message.saveChanges();
                Transport.send(message);
                transport.close();
            } catch (Exception x) {
                x.printStackTrace();
            }
    }
}

mailcheck.sh

javac -cp imap-1.5.4.jar:javax.mail.jar:smtp-1.5.4.jar MailCheck.java
java -cp imap-1.5.4.jar:javax.mail.jar:smtp-1.5.4.jar:. MailCheck

Written By bunkertor

Leave a Reply

Your email address will not be published. Required fields are marked *