The Unbearable Lightness of Java

Sending and Receiving Emails email

Sending emails in Java should be easier. Jodd provides several classes for sending emails in an easiler way.

E-mail definition

E-mail is defined as simple POJO bean of type Email. Each part of e-mail message can be set separately. Moreover, Email supports fluent interface, so even definition of an e-mail message would look natural.

Email supports plain text, HTML messages and any combination of both. When only text or html message is set, simple e-mail will be sent. When both text and html message is set, or when attachments are added, multipart e-mail will be sent. Actually, Email supports any number of separate messages that can be sent as na email.

Plain-text email:
Email email = Email.create()
	.from("...@jodd.org").to("...@jodd.org")
	.subject("Hello!")
	.addText("A plain text message...");
HTML email:
Email email = Email.create()
	.from("...@jodd.org").to("...@jodd.org")
	.subject("Hello HTML!")
	.addHtml("<b>HTML</b> message...");
Text and HTML email, with attachments and with high priority:
Email email = Email.create()
	.from("...@jodd.org").to("...@jodd.org")
	.subject("Hello!")
	.addText("text message...")
	.addHtml("<b>HTML</b> message...")
	.attachFile("d:\\starman.jpeg")
	.priority(PRIORITY_HIGHEST);

Attachments

Adding attachments is also easy, by simply adding files (or raw text) to existing Email object. Here we have two options: to attach a file or to embed a file. Attached files are regular attachments. On the other hand, embeded files should be used as CID resources for HTML messages. Some mail clients doesn't show embeded files as attachments.

Email email = Email.create()
				.from("weird@beotel.rs")
				.to("weird@beotel.rs")
				.subject("test5")
				.addText("Здраво!")
				.addHtml("<html><META http-equiv=Content-Type content=\"text/html; charset=utf-8\">" +
                		"<body><h1>Здраво!</h1><img src='cid:huh2.jpg'></body></html>")
				.embedFile("d:\\huh2.jpg")
				.attachFile("d:\\cover.jpg");

There is also more general method addAttachment() that accepts any implementation of EmailAttachment. One such implementation is, for example, InputStreamAttachment, that passes the input stream content as an attachment.

Sending e-mails

Emails are sent using SendMailSession. Mail session encapsulates process of preparing emails, opening and closing transport connection and sending emails. Mail sessions should be created by some SendMailSessionProvider. One such provider already exist: SmtpServer. It encapsulates smtp server that might use simple authentication.

With send mail session it is possible to send several emails at once, using just one connection. This is significantly faster then to opening session for each email.

Here is an example of sending previously defined emails:

SmtpServer smtpServer = new SmtpServer("mail.beotel.rs", new SimpleAuthenticator("user", "pass"));
...
SendMailSession session = smtpServer.createSession();
session.open();
session.sendMail(email1);
session.sendMail(email2);
session.close();

Since opening session and sending emails may produce EmailException, it is necessary to wrap methods in try-catch block and closing the session in the finally block.

Sending using SSL

Prefered way for sending e-mails is using SSL protocol. Jodd supports secure e-mail sending with SmtpSslServer, subclass of SmtpServer. Here is an example of sending e-mail via Gmail (port 465 is set by default):

SmtpServer smtpServer = new SmtpSslServer("smtp.gmail.com", "user@gmail.com", "password"));
...
SendMailSession session = smtpServer.createSession();
session.open();
session.sendMail(email);
session.close();

Everything is the same, just different session provider is used.

Receiving emails

Receiving emails is similar to sending: Pop3Server creates ReceiveMailSession that retrieves ReceivedEmails.

    Pop3Server popServer = new Pop3Server("pop3.beotel.yu",
			new SimpleAuthenticator("username", "password"));
    ReceiveMailSession session = popServer.createSession();
    session.open();
    System.out.println(session.getMessageCount());
    ReceivedEmail[] emails = session.receiveEmail(false);
    if (emails != null) {
        for (ReceivedEmail email : emails) {
            System.out.println("\n\n===[" + email.getMessageNumber() + "]===");
            
			// common info
			Printf.out("%0x", email.getFlags());
            System.out.println("FROM:" + email.getFrom());
            System.out.println("TO:" + email.getTo()[0]);
            System.out.println("SUBJECT:" + email.getSubject());
            System.out.println("PRIORITY:" + email.getPriority());
            System.out.println("SENT DATE:" + email.getSentDate());
            System.out.println("RECEIVED DATE: " + email.getReceiveDate());
            
			// process messages
			LinkedList messages = email.getAllMessages();
            for (EmailMessage msg : messages) {
                System.out.println("------");
                System.out.println(msg.getEncoding());
                System.out.println(msg.getMimeType());
                System.out.println(msg.getContent());
            }
			
			// process attachments
            List<EmailAttachment> attachments = email.getAttachments();
            if (attachments != null) {
                System.out.println("+++++");
                for (EmailAttachment attachment : attachments) {
					System.out.println("name: " + attachment.getName());
					System.out.println("cid: " + attachment.getContentId());
					System.out.println("size: " + attachment.getSize());
					attachment.writeToFile(new File("d:\\", attachment.getName()));
				}
            }
        }
    }
    session.close();

Receiving emails using SSL

Again, very simply: use Pop3SslServer implementation. Here is how it can be used to fetch email from Google:

    Pop3Server popServer = new Pop3SslServer("pop.gmail.com", "username", "password");
    ReceiveMailSession session = popServer.createSession();
    session.open();
	...
    session.close();